Files
leleka/crates/deploy/src/profile.rs
T

1036 lines
42 KiB
Rust

//! Memory profiles: which GPU class gets which budget, context ceiling, KAR source and RAM floor.
//!
//! The built-in profiles are the JSON files in `deploy/rust-runtime/profiles/`, embedded at build time so the binary
//! needs no data directory. `--profile FILE` replaces them with an operator file of the same shape. A profile only
//! selects documented switches of `leleka-inference`; it never changes the model, the quantization or the backend
//! mode, so choosing one is not a quality decision.
use crate::facts::Gpu;
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, path::Path};
/// Bytes of the pinned level-2 KAR archive (`InheritedKarArchive` admits exactly this length).
pub const ARCHIVE_BYTES: u64 = 55_295_529_472;
/// SHA-256 of the pinned level-2 archive (`qwen4exp_kar_ple.rs` `ARCHIVE_DIGEST`): what the verification stamp of the
/// archive file is keyed by.
pub const ARCHIVE_SHA256_HEX: &str =
"536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5";
/// SHA-256 of the two pinned IQ3_S shards (`backend.rs` `SHARD0`, `SHARD1`).
pub const SHARD_SHA256_HEX: [&str; 2] = [
"4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3",
"316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113",
];
/// [`ARCHIVE_SHA256_HEX`] as bytes.
pub fn archive_sha256() -> [u8; 32] {
let mut out = [0u8; 32];
hex::decode_to_slice(ARCHIVE_SHA256_HEX, &mut out).expect("the pinned digest is 64 hex digits");
out
}
/// Bytes of the two pinned IQ3_S GGUF shards.
pub const SHARD_BYTES: [u64; 2] = [54_817_524_224, 28_800_138_432];
pub const BUILTIN: [(&str, &str); 4] = [
(
"rtx5090-32g",
include_str!("../../../deploy/rust-runtime/profiles/rtx5090-32g.json"),
),
// Experimental variant of the server profile (the archive as a read-only file, no 55 GB memfd): never auto-selected (empty window).
(
"rtx5090-32g-file",
include_str!("../../../deploy/rust-runtime/profiles/rtx5090-32g-file.json"),
),
// Experimental A/B variant of the server profile without the KAR archive (the PLE rows come from GGUF shard 1): never auto-selected.
(
"rtx5090-32g-gguf-ple",
include_str!("../../../deploy/rust-runtime/profiles/rtx5090-32g-gguf-ple.json"),
),
(
"rtx3080-16g",
include_str!("../../../deploy/rust-runtime/profiles/rtx3080-16g.json"),
),
];
const PREFILL_CAPACITIES: [u32; 8] = [256, 512, 1024, 2048, 3072, 4096, 6144, 8192];
/// How the engine receives the KAR archive.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum KarSource {
/// A sealed memfd made by the supervisor: the whole archive lives in RAM (shmem) while the service runs.
Memfd,
/// An ordinary read-only file (`--kar-archive-file`): only the pages that are read pass through the file cache.
File,
/// EXPERIMENTAL (`rtx5090-32g-gguf-ple`): no KAR archive at all. The engine reads the per-layer n-gram (PLE) rows from the GGUF shard
/// itself (`qwen4exp-native-mtp-v1`, the exact PLE of the Original); the archive is neither required, checked nor passed.
None,
}
impl KarSource {
pub fn as_str(self) -> &'static str {
match self {
KarSource::Memfd => "memfd",
KarSource::File => "file",
KarSource::None => "none",
}
}
}
/// What the sealed memfd of a `kar_source: memfd` profile holds. `ple_only` is the form of `rtx5090-32g` (one resident copy of every model byte:
/// the memfd holds only what the serve path reads); `full` keeps the whole archive (docs/kar-sparse-memfd.md, scripts/e2e/decode/single-copy-ab.sh).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MemfdExtents {
/// The whole 55.3 GB archive (today's form).
#[default]
Full,
/// Only the byte ranges the serve path reads (the PLE rows plus header and directory, about 16 GB); the rest of the memfd is a
/// hole. Verified by the pinned digest of those ranges instead of the archive's SHA-256.
PleOnly,
}
impl MemfdExtents {
pub fn as_str(self) -> &'static str {
match self {
MemfdExtents::Full => "full",
MemfdExtents::PleOnly => "ple_only",
}
}
pub fn is_full(&self) -> bool {
*self == MemfdExtents::Full
}
}
/// Host RAM a `ple_only` memfd holds: 320,001,536 rows x 50 B = 16,000,076,800 B plus the metadata and page rounding; the exact
/// figure of the real archive printed by `kar_census` (2 extents).
pub const SPARSE_MEMFD_BYTES_ESTIMATE: u64 = 16_000_348_672;
/// The pinned SHA-256 of the extents of the pinned archive (`leleka_model_format::kar::PLE_EXTENTS_SHA256`), or, while that is not
/// measured yet (all zero), the operator's `LELEKA_KAR_EXTENTS_SHA256` (64 hex digits, from `kar_census --hash-extents` on an
/// archive that matched its full pinned SHA-256). The second form is explicitly experimental and is logged as such.
pub fn extents_sha256(
env: &dyn Fn(&str) -> Option<String>,
) -> Result<([u8; 32], PinSource), String> {
let compiled = leleka_model_format::kar::PLE_EXTENTS_SHA256;
if compiled != [0u8; 32] {
return Ok((compiled, PinSource::Compiled));
}
let text = env("LELEKA_KAR_EXTENTS_SHA256").ok_or_else(|| {
"memfd_extents=ple_only needs the pinned SHA-256 of the archive's extents, which is not compiled in yet: measure it with `kar_census ARCHIVE --hash-extents` (an archive that matched its full pinned SHA-256) and either commit it as PLE_EXTENTS_SHA256 or set LELEKA_KAR_EXTENTS_SHA256 for this experiment".to_owned()
})?;
let mut out = [0u8; 32];
hex::decode_to_slice(text.trim(), &mut out)
.map_err(|_| "LELEKA_KAR_EXTENTS_SHA256 must be 64 hex digits".to_owned())?;
if out == [0u8; 32] {
return Err("LELEKA_KAR_EXTENTS_SHA256 is all zero".into());
}
Ok((out, PinSource::Operator))
}
/// Where the extents pin came from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PinSource {
Compiled,
Operator,
}
/// How the routed experts are admitted (`leleka-inference --expert-source`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ExpertSource {
/// A page-locked RAM copy of the routed experts (about 50 GB): the server form.
Resident,
/// Read-only mappings of shard 0, nothing copied: the low-RAM form.
Mapped,
}
impl ExpertSource {
pub fn as_str(self) -> &'static str {
match self {
ExpertSource::Resident => "resident",
ExpertSource::Mapped => "mapped",
}
}
}
/// The memory-governor settings a profile carries (`docs/memory-safety.md`). Every field is optional: absent means the
/// engine's own default (floors from the host size, an `auto` cache sized from what is left, lock `try`). They become
/// `--prefix-cache-mib` and `LELEKA_MEMORY_*` / `LELEKA_ORIGINAL_SERVE_RESIDENT_BUDGET_GIB` for the engine.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MemoryBudget {
/// `--prefix-cache-mib`: `auto` (a share of what the governor leaves elastic), `0` (off) or MiB.
#[serde(default)]
pub prefix_cache_mib: Option<String>,
/// `--prefix-cache-tail`: `off`, `prompt` (a checkpoint at the end of the prefill) or `reply` (also one at the end of the decode,
/// where the agent's next turn resumes: the slot-equivalent resume, `docs/prefix-cache.md`). Absent: the engine's default (off).
#[serde(default)]
pub prefix_cache_tail: Option<String>,
/// `--prefix-cache-block`: tokens per prefix block and chunk-grid step (a multiple of 256, at most 8192; 0 = the prefill chunk).
/// Only passed while the prefix cache is on.
#[serde(default)]
pub prefix_cache_block: Option<u32>,
/// Minutes an idle cached session is kept (`LELEKA_PREFIX_RETENTION_S`; 0 = no time limit). Only passed while the cache is on.
#[serde(default)]
pub prefix_retention_min: Option<u64>,
/// Below this much available host memory the caches shed (`LELEKA_MEMORY_SOFT_FLOOR_MIB`).
#[serde(default)]
pub soft_floor_mib: Option<u64>,
/// Below this new requests are refused with 503 `memory_pressure` (`LELEKA_MEMORY_HARD_FLOOR_MIB`).
#[serde(default)]
pub hard_floor_mib: Option<u64>,
/// Slack kept above the soft floor after the fixed footprint (`LELEKA_MEMORY_RESERVE_MIB`).
#[serde(default)]
pub reserve_mib: Option<u64>,
/// Share of the elastic memory an `auto` cache takes, percent (`LELEKA_MEMORY_CACHE_SHARE_PERCENT`).
#[serde(default)]
pub cache_share_percent: Option<u64>,
/// Keep the sealed KAR memfd resident: `off`, `try` (lock when RLIMIT_MEMLOCK allows, else guard and heal) or `require`.
#[serde(default)]
pub lock: Option<String>,
/// Pull swapped memfd pages back in (`LELEKA_MEMORY_HEAL`).
#[serde(default)]
pub heal: Option<bool>,
/// `--resident-budget-gib` of the mapped expert source: GiB of experts page-locked in RAM (`LELEKA_ORIGINAL_SERVE_RESIDENT_BUDGET_GIB`).
#[serde(default)]
pub resident_budget_gib: Option<u32>,
}
impl MemoryBudget {
pub fn validate(&self) -> Result<(), String> {
if let Some(value) = &self.prefix_cache_mib
&& value != "auto"
&& value.parse::<u64>().ok().is_none_or(|mib| mib > (1 << 30))
{
return Err("memory.prefix_cache_mib must be \"auto\", \"0\" or a size in MiB".into());
}
if let Some(tail) = &self.prefix_cache_tail
&& !matches!(tail.as_str(), "off" | "prompt" | "reply")
{
return Err("memory.prefix_cache_tail must be off, prompt or reply".into());
}
if let Some(block) = self.prefix_cache_block
&& (block % 256 != 0 || block > 8192)
{
return Err("memory.prefix_cache_block must be a multiple of 256, at most 8192 (0 = the prefill chunk)".into());
}
if let (Some(soft), Some(hard)) = (self.soft_floor_mib, self.hard_floor_mib)
&& hard >= soft
{
return Err("memory.hard_floor_mib must be below memory.soft_floor_mib".into());
}
if let Some(percent) = self.cache_share_percent
&& !(1..=100).contains(&percent)
{
return Err("memory.cache_share_percent must be 1..=100".into());
}
if let Some(lock) = &self.lock
&& !matches!(lock.as_str(), "off" | "try" | "require")
{
return Err("memory.lock must be off, try or require".into());
}
Ok(())
}
/// The engine arguments this section adds.
pub fn args(&self) -> Vec<String> {
let mut args = Vec::new();
if let Some(value) = &self.prefix_cache_mib {
args.extend(["--prefix-cache-mib".to_owned(), value.clone()]);
}
if let Some(tail) = &self.prefix_cache_tail {
args.extend(["--prefix-cache-tail".to_owned(), tail.clone()]);
}
if let Some(block) = self.prefix_cache_block
&& self.prefix_cache_on()
{
args.extend(["--prefix-cache-block".to_owned(), block.to_string()]);
}
args
}
/// The explicit MiB cap of the prefix cache: `Some(n)` for a number above zero, `None` for `auto`, off or unset. An `auto` cache
/// is sized from the memory that is free when the stack opens (75 % of it, ceiling 96 GiB), so it grows whenever RAM is freed
/// elsewhere; a number never does (`leleka_memory::plan::explicit_prefix_budget`).
pub fn prefix_cache_cap_mib(&self) -> Option<u64> {
self.prefix_cache_mib
.as_deref()?
.parse::<u64>()
.ok()
.filter(|mib| *mib > 0)
}
/// The prefix cache is configured and not switched off (`0`).
pub fn prefix_cache_on(&self) -> bool {
self.prefix_cache_mib
.as_deref()
.is_some_and(|mib| mib != "0")
}
/// The engine environment this section adds.
pub fn env(&self) -> BTreeMap<String, String> {
let mut env = BTreeMap::new();
let mut put = |key: &str, value: Option<String>| {
if let Some(value) = value {
env.insert(key.to_owned(), value);
}
};
put(
"LELEKA_MEMORY_SOFT_FLOOR_MIB",
self.soft_floor_mib.map(|v| v.to_string()),
);
put(
"LELEKA_MEMORY_HARD_FLOOR_MIB",
self.hard_floor_mib.map(|v| v.to_string()),
);
put(
"LELEKA_MEMORY_RESERVE_MIB",
self.reserve_mib.map(|v| v.to_string()),
);
put(
"LELEKA_MEMORY_CACHE_SHARE_PERCENT",
self.cache_share_percent.map(|v| v.to_string()),
);
put("LELEKA_MEMORY_LOCK", self.lock.clone());
if self.prefix_cache_on() {
put(
"LELEKA_PREFIX_RETENTION_S",
self.prefix_retention_min
.map(|minutes| minutes.saturating_mul(60).to_string()),
);
}
put(
"LELEKA_MEMORY_HEAL",
self.heal.map(|v| if v { "1" } else { "0" }.to_owned()),
);
put(
"LELEKA_ORIGINAL_SERVE_RESIDENT_BUDGET_GIB",
self.resident_budget_gib.map(|v| v.to_string()),
);
env
}
}
/// Automatic selection window (`sm` is compute capability times ten; `sm_max` and `vram_mib_max` are exclusive).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Selector {
pub sm_min: u32,
pub sm_max: u32,
pub vram_mib_min: u64,
pub vram_mib_max: u64,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Profile {
pub name: String,
pub description: String,
#[serde(default)]
pub select: Selector,
pub gpu_budget_bytes: u64,
pub context_tokens: u32,
#[serde(default)]
pub prefill_capacity: Option<u32>,
#[serde(default)]
pub kv: Option<String>,
#[serde(default)]
pub kv_resident: Option<u32>,
#[serde(default)]
pub prompt_cache: Option<u32>,
/// MTP draft confidence floor (`--spec-min-p`, 0..=1). The reference agent runs used 0.5; unset keeps the engine default.
#[serde(default)]
pub spec_min_p: Option<f64>,
pub kar_source: KarSource,
/// What the sealed memfd holds (`kar_source: memfd` only; default `full`).
#[serde(default, skip_serializing_if = "MemfdExtents::is_full")]
pub memfd_extents: MemfdExtents,
pub expert_source: ExpertSource,
pub min_driver_major: u32,
pub min_vram_total_mib: u64,
/// Free VRAM required at start. Defaults to the budget; a profile whose budget is an upper bound that the
/// engine does not fully reach (the laptop: 15 GiB budget, 14.2 GiB measured peak) names the measured need.
#[serde(default)]
pub min_vram_free_mib: Option<u64>,
pub min_ram_total_bytes: u64,
pub min_ram_available_bytes: u64,
/// Advice only: the `memory=` value for `.wslconfig` when WSL2 gives the VM too little.
#[serde(default)]
pub wsl_memory_gib: Option<u32>,
/// Path relative to the assets directory of an optional ranked expert profile (VRAM expert tier).
#[serde(default)]
pub expert_profile: Option<String>,
#[serde(default)]
pub expert_profile_sha256: Option<String>,
/// Extra `LELEKA_ORIGINAL_SERVE_*` switches for the engine process.
#[serde(default)]
pub engine_env: BTreeMap<String, String>,
/// Memory budget settings (`docs/memory-safety.md`).
#[serde(default)]
pub memory: MemoryBudget,
}
impl Profile {
/// Host RAM the sealed memfd holds for the life of the service (0 for a file-backed archive).
pub fn memfd_bytes(&self) -> u64 {
match (self.kar_source, self.memfd_extents) {
(KarSource::File | KarSource::None, _) => 0,
(KarSource::Memfd, MemfdExtents::Full) => ARCHIVE_BYTES,
(KarSource::Memfd, MemfdExtents::PleOnly) => SPARSE_MEMFD_BYTES_ESTIMATE,
}
}
/// `min_ram_available_bytes` for this profile. The profile figure is written for the full archive copy; a `ple_only` memfd
/// needs that much less.
pub fn min_ram_available(&self) -> u64 {
let saved = match (self.kar_source, self.memfd_extents) {
(KarSource::Memfd, MemfdExtents::PleOnly) => {
ARCHIVE_BYTES - SPARSE_MEMFD_BYTES_ESTIMATE
}
_ => 0,
};
self.min_ram_available_bytes.saturating_sub(saved)
}
pub fn builtin(name: &str) -> Option<Profile> {
BUILTIN
.iter()
.find(|(candidate, _)| *candidate == name)
.map(|(_, text)| {
let profile: Profile =
serde_json::from_str(text).expect("built-in profile JSON is valid");
profile
})
}
pub fn builtins() -> Vec<Profile> {
BUILTIN
.iter()
.map(|(name, _)| Profile::builtin(name).expect("built-in"))
.collect()
}
pub fn from_file(path: &Path) -> Result<Profile, String> {
let bytes = std::fs::read(path)
.map_err(|error| format!("cannot read profile {}: {error}", path.display()))?;
if bytes.len() > 64 * 1024 {
return Err("profile file exceeds 64 KiB".into());
}
let profile: Profile = serde_json::from_slice(&bytes)
.map_err(|error| format!("invalid profile {}: {error}", path.display()))?;
profile.validate()?;
Ok(profile)
}
pub fn validate(&self) -> Result<(), String> {
if self.memfd_extents == MemfdExtents::PleOnly {
if self.kar_source != KarSource::Memfd {
return Err("memfd_extents=ple_only needs kar_source=memfd (a file-backed archive has no memfd to make sparse)".into());
}
// Freed RAM must not be refilled "on purpose" by an `auto` cache (docs/design/memory-single-copy-and-elastic-state.md section B).
if self.memory.prefix_cache_cap_mib().is_none() && self.memory.prefix_cache_on() {
return Err("memfd_extents=ple_only needs an explicit memory.prefix_cache_mib (or 0): `auto` would size the cache from the RAM the sparse memfd frees".into());
}
}
if self.name.is_empty()
|| self.name.len() > 64
|| !self
.name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
{
return Err("profile name must be 1..64 characters of [A-Za-z0-9._-]".into());
}
if self.gpu_budget_bytes < (1 << 30) || self.gpu_budget_bytes > (1 << 40) {
return Err("gpu_budget_bytes must be between 1 GiB and 1 TiB".into());
}
if !(1..=262_144).contains(&self.context_tokens) {
return Err("context_tokens must be 1..=262144 for the Original serve path".into());
}
if let Some(capacity) = self.prefill_capacity
&& !PREFILL_CAPACITIES.contains(&capacity)
{
return Err(format!(
"prefill_capacity must be one of {PREFILL_CAPACITIES:?}"
));
}
if let Some(p) = self.spec_min_p
&& !(0.0..=1.0).contains(&p)
{
return Err("spec_min_p must be within 0..=1".into());
}
if let Some(kv) = &self.kv
&& kv != "int8"
{
return Err("kv must be int8 (the engine refuses other formats)".into());
}
if let Some(digest) = &self.expert_profile_sha256
&& (digest.len() != 64 || !digest.bytes().all(|b| b.is_ascii_hexdigit()))
{
return Err("expert_profile_sha256 must be 64 hex digits".into());
}
if let Some(path) = &self.expert_profile
&& (path.is_empty()
|| path.starts_with('/')
|| path.split('/').any(|part| part == ".." || part.is_empty()))
{
return Err(
"expert_profile must be a relative path inside the assets directory".into(),
);
}
self.memory.validate()?;
for (key, value) in &self.engine_env {
// LELEKA_CHAIN selects the chain-kernel group (docs/chain-kernels.md), LELEKA_SM120_* the compute-capability-12 kernel switches
// (docs/experiments/draft-round-5090.md), LELEKA_PLE_* the GGUF PLE row reader (`kar_source: none`); every other switch is a serve-stack one
if !(key.starts_with("LELEKA_ORIGINAL_SERVE_")
|| key.starts_with("LELEKA_SM120_")
|| key.starts_with("LELEKA_PLE_")
|| key == "LELEKA_CHAIN")
|| !key
.bytes()
.all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_')
{
return Err(format!(
"engine_env key {key} must be an upper-case LELEKA_ORIGINAL_SERVE_*, LELEKA_SM120_* or LELEKA_PLE_* name (or LELEKA_CHAIN)"
));
}
if value.is_empty() || value.len() > 1024 || value.chars().any(char::is_control) {
return Err(format!(
"engine_env value of {key} is empty or not printable"
));
}
}
Ok(())
}
/// True when the compute capability and VRAM of `gpu` fall inside the selection window.
pub fn matches(&self, gpu: &Gpu) -> bool {
let Some(sm) = gpu.sm else { return false };
(self.select.sm_min..self.select.sm_max).contains(&sm)
&& (self.select.vram_mib_min..self.select.vram_mib_max).contains(&gpu.vram_total_mib)
}
}
/// Resolve `--profile`: `auto` (or nothing), a built-in name, or a path to a JSON file.
pub fn resolve(spec: Option<&str>, gpu: Option<&Gpu>) -> Result<Profile, String> {
let spec = spec.unwrap_or("auto");
if spec != "auto" {
if let Some(profile) = Profile::builtin(spec) {
return Ok(profile);
}
if spec.contains('/') || spec.contains('\\') || spec.ends_with(".json") {
return Profile::from_file(Path::new(spec));
}
let names: Vec<_> = BUILTIN.iter().map(|(name, _)| *name).collect();
return Err(format!(
"unknown profile {spec:?}; built-in profiles: {}; or pass a JSON file (see `leleka profiles show NAME`)",
names.join(", ")
));
}
let gpu = gpu.ok_or(
"no NVIDIA GPU was detected, so no profile can be selected automatically; pass --profile NAME|FILE",
)?;
let matches: Vec<Profile> = Profile::builtins()
.into_iter()
.filter(|profile| profile.matches(gpu))
.collect();
match matches.len() {
1 => Ok(matches.into_iter().next().expect("one")),
0 => Err(format!(
"no built-in profile fits {} (sm_{}, {} MiB); built-in: {}; write a profile file from `leleka profiles show NAME` and pass --profile FILE",
gpu.name,
gpu.sm.map_or("?".into(), |sm| sm.to_string()),
gpu.vram_total_mib,
BUILTIN
.iter()
.map(|(name, _)| *name)
.collect::<Vec<_>>()
.join(", ")
)),
_ => Err("more than one built-in profile matches; pass --profile NAME".into()),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn gpu(name: &str, sm: u32, mib: u64) -> Gpu {
Gpu {
index: 0,
name: name.into(),
driver: "595.99.02".into(),
vram_total_mib: mib,
vram_free_mib: mib,
sm: Some(sm),
}
}
#[test]
fn built_in_profiles_parse_and_validate() {
for profile in Profile::builtins() {
profile.validate().unwrap();
}
assert_eq!(Profile::builtins().len(), 4);
}
#[test]
fn the_file_variant_of_the_server_profile_differs_only_where_the_archive_form_matters() {
let server = Profile::builtin("rtx5090-32g").unwrap();
let file = Profile::builtin("rtx5090-32g-file").unwrap();
file.validate().unwrap();
assert_eq!(
(file.kar_source, file.expert_source),
(KarSource::File, ExpertSource::Resident)
);
// same engine configuration: only the archive form, the RAM it needs and the cache budget (explicit, so that the RAM the memfd no longer
// holds is not handed to the prefix cache) and the memfd-only lock/heal switches differ
for (name, same) in [
(
"gpu_budget_bytes",
server.gpu_budget_bytes == file.gpu_budget_bytes,
),
(
"context_tokens",
server.context_tokens == file.context_tokens,
),
(
"prefill_capacity",
server.prefill_capacity == file.prefill_capacity,
),
("spec_min_p", server.spec_min_p == file.spec_min_p),
(
"expert_profile",
server.expert_profile == file.expert_profile,
),
("engine_env", server.engine_env == file.engine_env),
(
"prefix_cache_tail",
server.memory.prefix_cache_tail == file.memory.prefix_cache_tail,
),
(
"prefix_cache_block",
server.memory.prefix_cache_block == file.memory.prefix_cache_block,
),
(
"floors",
(
server.memory.soft_floor_mib,
server.memory.hard_floor_mib,
server.memory.reserve_mib,
) == (
file.memory.soft_floor_mib,
file.memory.hard_floor_mib,
file.memory.reserve_mib,
),
),
] {
assert!(same, "{name} must match rtx5090-32g");
}
assert_eq!(file.memory.prefix_cache_mib.as_deref(), Some("6144"));
assert!(
file.min_ram_available_bytes + ARCHIVE_BYTES - 5_000_000_000
<= server.min_ram_available_bytes,
"the file form does not need the archive's RAM"
);
// an experimental profile: no GPU is ever matched to it, so `auto` keeps choosing exactly one profile
assert!(!file.matches(&gpu("NVIDIA GeForce RTX 5090", 120, 32607)));
assert_eq!(
resolve(None, Some(&gpu("NVIDIA GeForce RTX 5090", 120, 32607)))
.unwrap()
.name,
"rtx5090-32g"
);
assert_eq!(
resolve(Some("rtx5090-32g-file"), None).unwrap().kar_source,
KarSource::File
);
}
#[test]
fn the_gguf_ple_variant_differs_from_the_server_profile_only_in_the_ple_source() {
let server = Profile::builtin("rtx5090-32g").unwrap();
let ggufp = Profile::builtin("rtx5090-32g-gguf-ple").unwrap();
ggufp.validate().unwrap();
assert_eq!(ggufp.kar_source, KarSource::None);
assert_eq!(ggufp.memfd_bytes(), 0);
assert_eq!(KarSource::None.as_str(), "none");
for (name, same) in [
("gpu_budget_bytes", server.gpu_budget_bytes == ggufp.gpu_budget_bytes),
("context_tokens", server.context_tokens == ggufp.context_tokens),
("prefill_capacity", server.prefill_capacity == ggufp.prefill_capacity),
("spec_min_p", server.spec_min_p == ggufp.spec_min_p),
("expert_profile", server.expert_profile == ggufp.expert_profile),
("expert_source", server.expert_source == ggufp.expert_source),
("prefix_cache_mib", server.memory.prefix_cache_mib == ggufp.memory.prefix_cache_mib),
("prefix_cache_tail", server.memory.prefix_cache_tail == ggufp.memory.prefix_cache_tail),
("prefix_cache_block", server.memory.prefix_cache_block == ggufp.memory.prefix_cache_block),
] {
assert!(same, "{name} must match rtx5090-32g");
}
// the engine switches are the server's plus the page-cache form of the PLE reader
let mut expected = server.engine_env.clone();
expected.insert("LELEKA_PLE_DIRECT".into(), "0".into());
expected.insert("LELEKA_ORIGINAL_SERVE_GGUF_PLE".into(), "1".into());
assert_eq!(ggufp.engine_env, expected);
// experimental: never auto-selected
assert!(!ggufp.matches(&gpu("NVIDIA GeForce RTX 5090", 120, 32607)));
assert_eq!(
resolve(None, Some(&gpu("NVIDIA GeForce RTX 5090", 120, 32607))).unwrap().name,
"rtx5090-32g"
);
// only the PLE reader family is let through next to the serve-stack switches
let mut bad = ggufp.clone();
bad.engine_env.insert("LELEKA_PLEX".into(), "1".into());
assert!(bad.validate().is_err());
let mut json: serde_json::Value = serde_json::to_value(&ggufp).unwrap();
assert_eq!(json["kar_source"], "none");
json["kar_source"] = "memfd".into();
let back: Profile = serde_json::from_value(json).unwrap();
assert_eq!(back.kar_source, KarSource::Memfd);
}
#[test]
fn only_the_server_profile_turns_the_prompt_routing_seed_off() {
// placement-class setting (docs/experiments/decode-tail-5090.md): off for the 5090 profile, the engine default and the laptop profile are unchanged
let server = Profile::builtin("rtx5090-32g").unwrap();
assert_eq!(
server
.engine_env
.get("LELEKA_ORIGINAL_SERVE_SEED")
.map(String::as_str),
Some("off")
);
let laptop = Profile::builtin("rtx3080-16g").unwrap();
assert!(!laptop.engine_env.contains_key("LELEKA_ORIGINAL_SERVE_SEED"));
}
#[test]
fn only_the_server_profile_enables_the_mtp_draft_attention_switch() {
// bitwise draft-attention kernels of the compute capability 12 card (docs/experiments/draft-round-5090.md); the laptop (sm_86) has no companion for them
let server = Profile::builtin("rtx5090-32g").unwrap();
assert_eq!(
server
.engine_env
.get("LELEKA_SM120_ATTN_DAILY_MTP")
.map(String::as_str),
Some("1")
);
let laptop = Profile::builtin("rtx3080-16g").unwrap();
assert!(
!laptop
.engine_env
.contains_key("LELEKA_SM120_ATTN_DAILY_MTP")
);
// the key space of engine_env still refuses everything else
let mut bad = server.clone();
bad.engine_env.insert("LELEKA_SM86_X".into(), "1".into());
assert!(bad.validate().is_err());
let mut ok = server;
ok.engine_env
.insert("LELEKA_SM120_ATTN_DAILY_MTP".into(), "1".into());
ok.validate().unwrap();
}
#[test]
fn auto_selection_picks_the_server_and_the_laptop_profile() {
let server = resolve(None, Some(&gpu("NVIDIA GeForce RTX 5090", 120, 32607))).unwrap();
assert_eq!(server.name, "rtx5090-32g");
assert_eq!(server.kar_source, KarSource::Memfd);
let laptop = resolve(
Some("auto"),
Some(&gpu("NVIDIA GeForce RTX 3080 Laptop GPU", 86, 16384)),
)
.unwrap();
assert_eq!(laptop.name, "rtx3080-16g");
assert_eq!(laptop.kar_source, KarSource::File);
assert_eq!(
laptop.context_tokens, 262144,
"the owner's real work is 256k"
);
assert_eq!(
(laptop.prefill_capacity, laptop.memory.prefix_cache_block),
(Some(6144), Some(6144))
);
assert_eq!(laptop.memory.prefix_cache_tail.as_deref(), Some("prompt"));
}
#[test]
fn unmatched_gpu_and_missing_gpu_give_actionable_errors() {
let error = resolve(None, Some(&gpu("NVIDIA GeForce RTX 4090", 89, 24564))).unwrap_err();
assert!(error.contains("--profile FILE"), "{error}");
assert!(resolve(None, None).unwrap_err().contains("--profile"));
assert!(
resolve(Some("nope"), None)
.unwrap_err()
.contains("rtx5090-32g")
);
}
#[test]
fn explicit_name_overrides_the_detected_gpu() {
let forced = resolve(
Some("rtx3080-16g"),
Some(&gpu("NVIDIA GeForce RTX 5090", 120, 32607)),
)
.unwrap();
assert_eq!(forced.name, "rtx3080-16g");
}
#[test]
fn validation_rejects_unsafe_values() {
let mut profile = Profile::builtin("rtx5090-32g").unwrap();
profile
.engine_env
.insert("LD_PRELOAD".into(), "/tmp/x.so".into());
assert!(profile.validate().unwrap_err().contains("LD_PRELOAD"));
let mut profile = Profile::builtin("rtx5090-32g").unwrap();
profile.context_tokens = 524_288;
assert!(profile.validate().is_err());
let mut profile = Profile::builtin("rtx5090-32g").unwrap();
profile.prefill_capacity = Some(1000);
assert!(profile.validate().is_err());
let mut profile = Profile::builtin("rtx3080-16g").unwrap();
profile.expert_profile = Some("../x".into());
assert!(profile.validate().is_err());
profile.expert_profile = Some("/etc/passwd".into());
assert!(profile.validate().is_err());
}
#[test]
fn the_builtin_profiles_carry_the_memory_budget_into_engine_arguments_and_environment() {
let server = Profile::builtin("rtx5090-32g").unwrap();
assert_eq!(
server.memory.args(),
[
"--prefix-cache-mib",
"6144",
"--prefix-cache-tail",
"reply",
"--prefix-cache-block",
"8192"
]
.map(str::to_owned)
.to_vec()
);
let mut bad = server.memory.clone();
bad.prefix_cache_tail = Some("always".into());
assert!(bad.validate().is_err());
let env = server.memory.env();
assert_eq!(env["LELEKA_MEMORY_SOFT_FLOOR_MIB"], "4096");
assert_eq!(env["LELEKA_MEMORY_HARD_FLOOR_MIB"], "2048");
assert_eq!(env["LELEKA_MEMORY_LOCK"], "try");
let laptop = Profile::builtin("rtx3080-16g").unwrap();
assert_eq!(
laptop.memory.env()["LELEKA_MEMORY_LOCK"],
"off",
"the laptop archive is a file, not a memfd"
);
for profile in Profile::builtins() {
profile.validate().unwrap();
}
}
#[test]
fn the_5090_profile_carries_an_explicit_prefix_cap_so_freed_ram_cannot_grow_the_store() {
let server = Profile::builtin("rtx5090-32g").unwrap();
// 6144 MiB = what `auto` resolves to on this host today (5.7-6.1 GiB, docs/memory-safety.md section 8): behaviour at 245k is unchanged
assert_eq!(server.memory.prefix_cache_cap_mib(), Some(6144));
assert!(server.memory.prefix_cache_on());
assert!(
server
.memory
.args()
.windows(2)
.any(|w| w == ["--prefix-cache-mib", "6144"])
);
// a cache that fits the cap with room to spare: 245k tokens x 14,208 B + ~4 nodes of ~127 MiB is about 4 GiB
let session_245k = 245_000u64 * 14_208 + 4 * (127 << 20);
assert!(session_245k < 6144 << 20, "{session_245k}");
// `auto`, `0`, off and unset are not caps
for (value, cap) in [
(Some("auto"), None),
(Some("0"), None),
(None, None),
(Some("8192"), Some(8192)),
] {
let mut memory = server.memory.clone();
memory.prefix_cache_mib = value.map(str::to_owned);
assert_eq!(memory.prefix_cache_cap_mib(), cap, "{value:?}");
}
// the dedicated memfd profile must keep an explicit cap; the laptop (file archive, mapped experts) is a different machine
for profile in Profile::builtins()
.iter()
.filter(|p| p.kar_source == KarSource::Memfd)
{
assert!(
profile.memory.prefix_cache_cap_mib().is_some(),
"{} uses `auto`",
profile.name
);
}
}
fn sparse_server() -> Profile {
Profile::builtin("rtx5090-32g").unwrap()
}
#[test]
fn only_the_5090_profile_uses_a_sparse_memfd_and_full_is_never_serialized() {
for profile in Profile::builtins() {
let want = if profile.name == "rtx5090-32g" {
MemfdExtents::PleOnly
} else {
MemfdExtents::Full
};
assert_eq!(profile.memfd_extents, want, "{}", profile.name);
assert_eq!(
serde_json::to_string(&profile)
.unwrap()
.contains("\"memfd_extents\":"),
want == MemfdExtents::PleOnly,
"{}",
profile.name
);
}
let mut full = sparse_server();
full.memfd_extents = MemfdExtents::Full;
assert!(
!serde_json::to_string(&full)
.unwrap()
.contains("\"memfd_extents\":")
);
let text = serde_json::to_string(&sparse_server()).unwrap();
assert!(text.contains("\"memfd_extents\":\"ple_only\""), "{text}");
let back: Profile = serde_json::from_str(&text).unwrap();
assert_eq!(back, sparse_server());
let mut value: serde_json::Value = serde_json::from_str(
&serde_json::to_string(&Profile::builtin("rtx5090-32g").unwrap()).unwrap(),
)
.unwrap();
value["memfd_extents"] = "everything".into();
assert!(serde_json::from_value::<Profile>(value).is_err());
}
#[test]
fn a_sparse_memfd_profile_needs_a_memfd_and_an_explicit_prefix_cap() {
sparse_server().validate().unwrap();
// 0 (cache off) and any number are fine; `auto` would refill the freed RAM
for (value, ok) in [("6144", true), ("0", true), ("auto", false)] {
let mut profile = sparse_server();
profile.memory.prefix_cache_mib = Some(value.into());
assert_eq!(profile.validate().is_ok(), ok, "{value}");
}
let mut profile = sparse_server();
profile.memory.prefix_cache_mib = None;
assert!(
profile.validate().is_ok(),
"no cache at all cannot refill anything"
);
let mut file_backed = sparse_server();
file_backed.kar_source = KarSource::File;
let error = file_backed.validate().unwrap_err();
assert!(
error.contains("ple_only") && error.contains("memfd"),
"{error}"
);
// the same profile in the full form validates with `auto`
let mut full = Profile::builtin("rtx5090-32g").unwrap();
full.memfd_extents = MemfdExtents::Full;
full.memory.prefix_cache_mib = Some("auto".into());
full.validate().unwrap();
}
#[test]
fn a_sparse_memfd_holds_a_third_of_the_archive_and_lowers_the_ram_the_profile_asks_for() {
let mut full = Profile::builtin("rtx5090-32g").unwrap();
full.memfd_extents = MemfdExtents::Full;
let sparse = sparse_server();
assert_eq!(full.memfd_bytes(), ARCHIVE_BYTES);
assert_eq!(sparse.memfd_bytes(), SPARSE_MEMFD_BYTES_ESTIMATE);
// 320,001,536 rows x 50 B = 16,000,076,800 B are the floor of what the serve path reads
const {
assert!(
SPARSE_MEMFD_BYTES_ESTIMATE > 16_000_076_800
&& SPARSE_MEMFD_BYTES_ESTIMATE < ARCHIVE_BYTES / 3
)
};
assert_eq!(full.min_ram_available(), full.min_ram_available_bytes);
assert_eq!(
sparse.min_ram_available(),
full.min_ram_available_bytes - (ARCHIVE_BYTES - SPARSE_MEMFD_BYTES_ESTIMATE)
);
assert!(
sparse.min_ram_available() > 70_000_000_000
&& sparse.min_ram_available() < 80_000_000_000
);
let laptop = Profile::builtin("rtx3080-16g").unwrap();
assert_eq!(
(laptop.memfd_bytes(), laptop.min_ram_available()),
(0, laptop.min_ram_available_bytes)
);
}
#[test]
fn the_extents_pin_is_the_compiled_one_or_an_explicit_operator_value_and_never_silent() {
let none = |_: &str| None;
let with = |value: &str| {
let value = value.to_owned();
move |key: &str| (key == "LELEKA_KAR_EXTENTS_SHA256").then(|| value.clone())
};
let hex64 = "ab".repeat(32);
let zeros = "00".repeat(32);
let compiled = leleka_model_format::kar::PLE_EXTENTS_SHA256;
if compiled == [0u8; 32] {
// not measured yet: the sparse form refuses to start without an explicit value, and says how to get one
let error = extents_sha256(&none).unwrap_err();
assert!(
error.contains("kar_census") && error.contains("--hash-extents"),
"{error}"
);
assert!(extents_sha256(&with("zz")).unwrap_err().contains("64 hex"));
assert!(
extents_sha256(&with("abcd"))
.unwrap_err()
.contains("64 hex")
);
assert!(extents_sha256(&with(&zeros)).unwrap_err().contains("zero"));
let (pin, source) = extents_sha256(&with(&hex64)).unwrap();
assert_eq!((pin, source), ([0xab; 32], PinSource::Operator));
} else {
// measured: the binary's value wins and an environment value cannot override it
assert_eq!(
extents_sha256(&none).unwrap(),
(compiled, PinSource::Compiled)
);
assert_eq!(
extents_sha256(&with(&hex64)).unwrap(),
(compiled, PinSource::Compiled)
);
}
}
#[test]
fn memory_budget_validation_rejects_nonsense() {
let mut profile = Profile::builtin("rtx5090-32g").unwrap();
profile.memory.hard_floor_mib = Some(8192);
assert!(profile.validate().unwrap_err().contains("hard_floor"));
let mut profile = Profile::builtin("rtx5090-32g").unwrap();
profile.memory.lock = Some("maybe".into());
assert!(profile.validate().is_err());
let mut profile = Profile::builtin("rtx5090-32g").unwrap();
profile.memory.prefix_cache_mib = Some("lots".into());
assert!(profile.validate().is_err());
profile.memory.prefix_cache_mib = Some("0".into());
assert!(profile.validate().is_ok());
profile.memory.cache_share_percent = Some(0);
assert!(profile.validate().is_err());
}
#[test]
fn unknown_fields_in_a_profile_file_are_refused() {
let text = BUILTIN[0].1.replacen('{', "{\"typo\": 1,", 1);
assert!(serde_json::from_str::<Profile>(&text).is_err());
}
}