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

277 lines
12 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
/// (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: impl 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. 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). 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>,
}
/// 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.
#[serde(default)]
pub memory: MemoryBudget,
}
#[cfg(test)]
mod tests;
mod catalog;
mod memory_budget;
mod profile_limits;
pub use catalog::resolve;