normalize line endings of the files touched by the resource-preset and telemetry commits back to LF
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
07a540aa52
commit
85185ecd00
+3420
-3420
File diff suppressed because it is too large
Load Diff
+528
-528
File diff suppressed because it is too large
Load Diff
+561
-561
File diff suppressed because it is too large
Load Diff
+513
-513
File diff suppressed because it is too large
Load Diff
+20
-20
@@ -1,20 +1,20 @@
|
||||
//! `leleka`: deploy and run the Leleka runtime (engine + gateway + API) with one command.
|
||||
//!
|
||||
//! No Python, no shell glue at run time: `leleka up` preflights the host, fetches and verifies the model, builds the
|
||||
//! KAR archive, installs the binaries, writes the configuration, starts the service and waits for readiness;
|
||||
//! `leleka run` is the supervisor that the systemd unit (or a terminal) executes. See `docs/deploy.md`.
|
||||
pub mod app;
|
||||
pub mod cli;
|
||||
pub mod config;
|
||||
pub mod facts;
|
||||
pub mod http;
|
||||
pub mod layout;
|
||||
pub mod manifest;
|
||||
pub mod plan;
|
||||
pub mod preflight;
|
||||
pub mod profile;
|
||||
pub mod resources;
|
||||
pub mod sealed;
|
||||
pub mod steps;
|
||||
pub mod supervisor;
|
||||
pub mod units;
|
||||
//! `leleka`: deploy and run the Leleka runtime (engine + gateway + API) with one command.
|
||||
//!
|
||||
//! No Python, no shell glue at run time: `leleka up` preflights the host, fetches and verifies the model, builds the
|
||||
//! KAR archive, installs the binaries, writes the configuration, starts the service and waits for readiness;
|
||||
//! `leleka run` is the supervisor that the systemd unit (or a terminal) executes. See `docs/deploy.md`.
|
||||
pub mod app;
|
||||
pub mod cli;
|
||||
pub mod config;
|
||||
pub mod facts;
|
||||
pub mod http;
|
||||
pub mod layout;
|
||||
pub mod manifest;
|
||||
pub mod plan;
|
||||
pub mod preflight;
|
||||
pub mod profile;
|
||||
pub mod resources;
|
||||
pub mod sealed;
|
||||
pub mod steps;
|
||||
pub mod supervisor;
|
||||
pub mod units;
|
||||
|
||||
+1140
-1140
File diff suppressed because it is too large
Load Diff
+1060
-1060
File diff suppressed because it is too large
Load Diff
+377
-377
@@ -1,377 +1,377 @@
|
||||
//! Resource presets: how much of the host `leleka up` lets the engine take (`docs/deploy.md`, "Resource presets").
|
||||
//!
|
||||
//! * `dedicated` (default): the host belongs to the runtime. The profile's VRAM budget as it is, engine defaults for the
|
||||
//! memory governor, CPU workers up to the useful maximum.
|
||||
//! * `workstation`: Docker, agents and the IDE share the machine. At least 4 cores (8 on hosts with more than 16) stay
|
||||
//! free of engine workers, the memory governor keeps 8-16 GiB of host RAM free (it sheds the prefix cache first), and
|
||||
//! about 4 GiB of VRAM is left to the desktop; the expert tier is sized from what remains.
|
||||
//!
|
||||
//! `compute` is a pure function of the host facts and the profile; `apply` writes the result into the profile and the
|
||||
//! engine environment. Explicit profile fields and command-line overrides always win over a preset.
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{
|
||||
facts::{Facts, Gpu},
|
||||
profile::{ARCHIVE_BYTES, ExpertSource, KarSource, Profile},
|
||||
};
|
||||
|
||||
const GIB: u64 = 1 << 30;
|
||||
const MIB: u64 = 1 << 20;
|
||||
/// Decode is bound by host memory bandwidth: more CPU expert workers than this do not help (`docs/roofline.md`).
|
||||
const MAX_USEFUL_WORKERS: u32 = 8;
|
||||
/// VRAM the desktop/browser keeps in the workstation preset.
|
||||
const WORKSTATION_VRAM_MARGIN_MIB: u64 = 4096;
|
||||
/// Resident host memory of a memfd-backed engine besides the archive (tokenizer, pinned buffers, CUDA host state).
|
||||
const ENGINE_EXTRA_BYTES: u64 = 3 * GIB;
|
||||
/// Host memory the mapped form keeps for the engine itself, the tokenizer and the working set of the page cache.
|
||||
const MAPPED_OVERHEAD_BYTES: u64 = 8 * GIB;
|
||||
/// What the mapped form still needs available to start.
|
||||
const MAPPED_MIN_AVAILABLE_BYTES: u64 = 10 * GIB;
|
||||
pub const CPU_WORKERS_ENV: &str = "LELEKA_ORIGINAL_SERVE_CPU_WORKERS";
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Preset {
|
||||
#[default]
|
||||
Dedicated,
|
||||
Workstation,
|
||||
}
|
||||
|
||||
impl Preset {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Preset::Dedicated => "dedicated",
|
||||
Preset::Workstation => "workstation",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> Result<Preset, String> {
|
||||
match text {
|
||||
"dedicated" => Ok(Preset::Dedicated),
|
||||
"workstation" => Ok(Preset::Workstation),
|
||||
other => Err(format!(
|
||||
"unknown preset '{other}' (use dedicated or workstation)"
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct ResourcePlan {
|
||||
pub preset: Preset,
|
||||
pub cores: u32,
|
||||
/// `None` when the core count is unknown: the engine keeps its own default.
|
||||
pub cpu_workers: Option<u32>,
|
||||
pub gpu_budget_bytes: u64,
|
||||
/// The profile's `min_vram_free_mib`, lowered when the preset lowered the budget.
|
||||
pub min_vram_free_mib: Option<u64>,
|
||||
pub vram_free_after_mib: Option<u64>,
|
||||
/// Host RAM the memory governor keeps available: (soft, hard) floors in MiB, `None` = engine defaults.
|
||||
pub ram_floors_mib: Option<(u64, u64)>,
|
||||
pub ram_expected_free_after_bytes: Option<u64>,
|
||||
/// Host RAM cannot hold the sealed archive and the experts next to the free target: serve from SSD/HDD instead
|
||||
/// (archive as a read-only file, experts memory-mapped, this many GiB of them page-locked).
|
||||
pub mapped_resident_gib: Option<u32>,
|
||||
/// Shortfalls that make the preset unachievable (the preflight fails on them).
|
||||
pub problems: Vec<String>,
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
fn gib_text(bytes: u64) -> String {
|
||||
format!("{:.1} GiB", bytes as f64 / GIB as f64)
|
||||
}
|
||||
|
||||
/// RAM the workstation preset keeps free: 8 GiB on small hosts up to 16 GiB from 64 GiB of RAM.
|
||||
pub fn workstation_ram_target(total: u64) -> u64 {
|
||||
if total >= 64 * GIB {
|
||||
16 * GIB
|
||||
} else if total >= 32 * GIB {
|
||||
12 * GIB
|
||||
} else {
|
||||
8 * GIB
|
||||
}
|
||||
}
|
||||
|
||||
pub fn compute(facts: &Facts, gpu: Option<&Gpu>, profile: &Profile, preset: Preset) -> ResourcePlan {
|
||||
let mut plan = ResourcePlan {
|
||||
preset,
|
||||
cores: facts.cpu_cores,
|
||||
cpu_workers: None,
|
||||
gpu_budget_bytes: profile.gpu_budget_bytes,
|
||||
min_vram_free_mib: profile.min_vram_free_mib,
|
||||
vram_free_after_mib: None,
|
||||
ram_floors_mib: None,
|
||||
ram_expected_free_after_bytes: None,
|
||||
mapped_resident_gib: None,
|
||||
problems: Vec::new(),
|
||||
warnings: Vec::new(),
|
||||
};
|
||||
|
||||
// CPU
|
||||
if facts.cpu_cores > 0 {
|
||||
let cores = facts.cpu_cores;
|
||||
let leave = match preset {
|
||||
Preset::Dedicated => 2,
|
||||
Preset::Workstation if cores <= 16 => 4,
|
||||
Preset::Workstation => 8,
|
||||
};
|
||||
plan.cpu_workers = Some(cores.saturating_sub(leave).clamp(1, MAX_USEFUL_WORKERS));
|
||||
if preset == Preset::Workstation && cores < leave + 1 {
|
||||
plan.warnings.push(format!(
|
||||
"only {cores} CPU cores: the workstation preset cannot leave {leave} of them free (1 worker)"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// VRAM
|
||||
if let Some(gpu) = gpu {
|
||||
let budget_mib = profile.gpu_budget_bytes / MIB;
|
||||
if preset == Preset::Workstation {
|
||||
let cap_mib = (gpu.vram_free_mib.saturating_sub(WORKSTATION_VRAM_MARGIN_MIB) / 1024) * 1024;
|
||||
if cap_mib < budget_mib {
|
||||
plan.gpu_budget_bytes = cap_mib * MIB;
|
||||
let need = profile.min_vram_free_mib.unwrap_or(budget_mib).min(cap_mib);
|
||||
plan.min_vram_free_mib = Some(need);
|
||||
// Below half of the profile budget the expert tier and KV window shrink past what was measured.
|
||||
if cap_mib * 2 < budget_mib {
|
||||
plan.problems.push(format!(
|
||||
"the workstation preset leaves {} MiB of VRAM free, which gives the engine {} MiB; the profile {} needs about {} MiB (free the GPU or use --preset dedicated)",
|
||||
WORKSTATION_VRAM_MARGIN_MIB, cap_mib, profile.name, budget_mib
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
let used = (plan.gpu_budget_bytes / MIB).max(plan.min_vram_free_mib.unwrap_or(0));
|
||||
plan.vram_free_after_mib = Some(gpu.vram_free_mib.saturating_sub(used));
|
||||
}
|
||||
|
||||
// Host RAM
|
||||
let ram = &facts.memory;
|
||||
if ram.total > 0 {
|
||||
let target = match preset {
|
||||
Preset::Workstation => workstation_ram_target(ram.total),
|
||||
Preset::Dedicated => profile.memory.soft_floor_mib.map_or(4 * GIB, |mib| mib * MIB),
|
||||
};
|
||||
if preset == Preset::Workstation {
|
||||
let soft = target / MIB;
|
||||
plan.ram_floors_mib = Some((soft, soft / 2));
|
||||
}
|
||||
if profile.kar_source == KarSource::Memfd {
|
||||
let footprint = ARCHIVE_BYTES + ENGINE_EXTRA_BYTES;
|
||||
let after = ram.available.saturating_sub(footprint);
|
||||
if after >= target {
|
||||
plan.ram_expected_free_after_bytes = Some(after);
|
||||
} else {
|
||||
// Not enough RAM for the pinned form: map the archive and the experts from disk instead of failing.
|
||||
let resident = ram.available.saturating_sub(target + MAPPED_OVERHEAD_BYTES) / GIB;
|
||||
let resident = resident.min(u64::from(u32::MAX)) as u32;
|
||||
plan.mapped_resident_gib = Some(resident);
|
||||
plan.ram_expected_free_after_bytes = Some(ram.available.saturating_sub(u64::from(resident) * GIB + MAPPED_OVERHEAD_BYTES));
|
||||
plan.warnings.push(format!(
|
||||
"{} of host RAM available, the pinned form needs about {} plus {} free: the archive and the experts are served from disk (memory-mapped), {} GiB of experts stay page-locked; decode is slower than with everything in RAM",
|
||||
gib_text(ram.available),
|
||||
gib_text(footprint),
|
||||
gib_text(target),
|
||||
resident
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
plan
|
||||
}
|
||||
|
||||
/// Write the plan into the profile and the engine environment. Values the profile or the command line already set win.
|
||||
pub fn apply(
|
||||
plan: &ResourcePlan,
|
||||
profile: &mut Profile,
|
||||
engine_env: &mut BTreeMap<String, String>,
|
||||
budget_overridden: bool,
|
||||
) {
|
||||
if !budget_overridden {
|
||||
profile.gpu_budget_bytes = plan.gpu_budget_bytes;
|
||||
profile.min_vram_free_mib = plan.min_vram_free_mib;
|
||||
}
|
||||
if let Some((soft, hard)) = plan.ram_floors_mib {
|
||||
// The profile's floors are its dedicated-host values; the workstation preset only raises them.
|
||||
let raised = |current: Option<u64>, wanted: u64| Some(current.map_or(wanted, |c| c.max(wanted)));
|
||||
profile.memory.soft_floor_mib = raised(profile.memory.soft_floor_mib, soft);
|
||||
profile.memory.hard_floor_mib = raised(profile.memory.hard_floor_mib, hard);
|
||||
}
|
||||
if let Some(resident) = plan.mapped_resident_gib {
|
||||
profile.kar_source = KarSource::File;
|
||||
profile.expert_source = ExpertSource::Mapped;
|
||||
profile.memory.resident_budget_gib.get_or_insert(resident);
|
||||
profile.memory.lock = Some("off".into());
|
||||
profile.memory.heal = Some(false);
|
||||
profile.min_ram_total_bytes = profile.min_ram_total_bytes.min(16 * GIB);
|
||||
profile.min_ram_available_bytes = profile.min_ram_available_bytes.min(MAPPED_MIN_AVAILABLE_BYTES);
|
||||
}
|
||||
if let Some(workers) = plan.cpu_workers
|
||||
&& !profile.engine_env.contains_key(CPU_WORKERS_ENV)
|
||||
{
|
||||
engine_env.insert(CPU_WORKERS_ENV.to_owned(), workers.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
impl ResourcePlan {
|
||||
/// The table `leleka up` prints: what the engine takes and what stays free.
|
||||
pub fn render(&self, facts: &Facts) -> String {
|
||||
let mut out = format!("resources ({} preset)\n", self.preset.as_str());
|
||||
if let Some(workers) = self.cpu_workers {
|
||||
out.push_str(&format!(
|
||||
" cpu {workers} expert workers of {} cores; ~{} cores stay free\n",
|
||||
self.cores,
|
||||
self.cores.saturating_sub(workers + 1)
|
||||
));
|
||||
}
|
||||
out.push_str(&format!(
|
||||
" vram budget {}{}\n",
|
||||
gib_text(self.gpu_budget_bytes),
|
||||
self.vram_free_after_mib
|
||||
.map_or(String::new(), |free| format!(", ~{} MiB stay free", free))
|
||||
));
|
||||
match (self.ram_floors_mib, self.ram_expected_free_after_bytes) {
|
||||
(Some((soft, hard)), after) => out.push_str(&format!(
|
||||
" host ram caches shed below {} MiB available, requests refused below {} MiB{}\n",
|
||||
soft,
|
||||
hard,
|
||||
after.map_or(String::new(), |b| format!("; ~{} free after the start", gib_text(b)))
|
||||
)),
|
||||
(None, Some(after)) => out.push_str(&format!(
|
||||
" host ram engine defaults; ~{} of {} free after the start\n",
|
||||
gib_text(after),
|
||||
gib_text(facts.memory.total)
|
||||
)),
|
||||
(None, None) => {}
|
||||
}
|
||||
for warning in &self.warnings {
|
||||
out.push_str(&format!(" warning {warning}\n"));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::facts::Memory;
|
||||
|
||||
fn gpu(total: u64, free: u64) -> Gpu {
|
||||
Gpu { index: 0, name: "gpu".into(), driver: "595.1".into(), vram_total_mib: total, vram_free_mib: free, sm: Some(120) }
|
||||
}
|
||||
|
||||
fn host(cores: u32, ram_gib: u64, avail_gib: u64) -> Facts {
|
||||
Facts {
|
||||
cpu_cores: cores,
|
||||
memory: Memory { total: ram_gib * GIB, available: avail_gib * GIB, swap_total: 0 },
|
||||
..Facts::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn server() -> Profile {
|
||||
Profile::builtin("rtx5090-32g").unwrap()
|
||||
}
|
||||
fn laptop() -> Profile {
|
||||
Profile::builtin("rtx3080-16g").unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dedicated_takes_the_profile_and_caps_workers_at_the_useful_maximum() {
|
||||
let plan = compute(&host(32, 121, 100), Some(&gpu(32607, 32100)), &server(), Preset::Dedicated);
|
||||
assert_eq!(plan.cpu_workers, Some(8));
|
||||
assert_eq!(plan.gpu_budget_bytes, server().gpu_budget_bytes);
|
||||
assert_eq!(plan.ram_floors_mib, None);
|
||||
assert!(plan.problems.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workstation_leaves_cores_ram_and_vram_on_the_server() {
|
||||
let plan = compute(&host(32, 121, 100), Some(&gpu(32607, 32100)), &server(), Preset::Workstation);
|
||||
assert_eq!(plan.cpu_workers, Some(8), "32 cores - 8 left free = 24, capped at 8");
|
||||
assert_eq!(plan.gpu_budget_bytes, 27 * GIB, "32100 MiB free - 4096 MiB, rounded down to GiB");
|
||||
assert_eq!(plan.ram_floors_mib, Some((16384, 8192)));
|
||||
assert!(plan.problems.is_empty(), "{:?}", plan.problems);
|
||||
let mut profile = server();
|
||||
let mut env = BTreeMap::new();
|
||||
apply(&plan, &mut profile, &mut env, false);
|
||||
assert_eq!(profile.gpu_budget_bytes, 27 * GIB);
|
||||
assert_eq!(profile.memory.soft_floor_mib, Some(16384));
|
||||
assert_eq!(profile.memory.hard_floor_mib, Some(8192));
|
||||
assert_eq!(env.get(CPU_WORKERS_ENV).map(String::as_str), Some("8"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workstation_on_a_16_thread_laptop_leaves_four_cores_and_scales_the_ram_target() {
|
||||
let plan = compute(&host(16, 24, 21), Some(&gpu(16384, 15500)), &laptop(), Preset::Workstation);
|
||||
assert_eq!(plan.cpu_workers, Some(8));
|
||||
assert_eq!(plan.ram_floors_mib, Some((8192, 4096)));
|
||||
assert_eq!(plan.gpu_budget_bytes, 11 * GIB);
|
||||
assert!(plan.problems.is_empty(), "{:?}", plan.problems);
|
||||
let small = compute(&host(8, 24, 21), Some(&gpu(16384, 15500)), &laptop(), Preset::Workstation);
|
||||
assert_eq!(small.cpu_workers, Some(4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unachievable_workstation_vram_target_is_a_problem_not_a_silent_shrink() {
|
||||
let plan = compute(&host(16, 24, 21), Some(&gpu(16384, 9000)), &laptop(), Preset::Workstation);
|
||||
assert!(!plan.problems.is_empty());
|
||||
let dedicated = compute(&host(16, 24, 21), Some(&gpu(16384, 9000)), &laptop(), Preset::Dedicated);
|
||||
assert!(dedicated.problems.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_values_win_and_floors_are_only_raised() {
|
||||
let plan = compute(&host(32, 121, 100), Some(&gpu(32607, 32100)), &server(), Preset::Workstation);
|
||||
let mut profile = server();
|
||||
profile.memory.soft_floor_mib = Some(30000);
|
||||
profile.engine_env.insert(CPU_WORKERS_ENV.into(), "3".into());
|
||||
let mut env = BTreeMap::new();
|
||||
apply(&plan, &mut profile, &mut env, true);
|
||||
assert_eq!(profile.gpu_budget_bytes, server().gpu_budget_bytes, "--gpu-budget-gib wins");
|
||||
assert_eq!(profile.memory.soft_floor_mib, Some(30000));
|
||||
assert_eq!(profile.memory.hard_floor_mib, Some(8192), "floors are only ever raised");
|
||||
assert!(env.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_core_count_leaves_the_engine_default() {
|
||||
let plan = compute(&host(0, 121, 100), None, &server(), Preset::Workstation);
|
||||
assert_eq!(plan.cpu_workers, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn not_enough_ram_for_the_pinned_form_switches_to_mapped_files_instead_of_failing() {
|
||||
// 121 GiB host with 70 GiB available: 58 GiB of pinned archive leaves 12 GiB, below the 16 GiB workstation target
|
||||
let plan = compute(&host(32, 121, 70), Some(&gpu(32607, 32100)), &server(), Preset::Workstation);
|
||||
assert_eq!(plan.mapped_resident_gib, Some(46), "70 - 16 target - 8 overhead");
|
||||
assert_eq!(plan.warnings.len(), 1, "{:?}", plan.warnings);
|
||||
assert!(plan.render(&host(32, 121, 70)).contains("served from disk"));
|
||||
let mut profile = server();
|
||||
let mut env = BTreeMap::new();
|
||||
apply(&plan, &mut profile, &mut env, false);
|
||||
assert_eq!(profile.kar_source, KarSource::File);
|
||||
assert_eq!(profile.expert_source, ExpertSource::Mapped);
|
||||
assert_eq!(profile.memory.resident_budget_gib, Some(46));
|
||||
assert_eq!(profile.memory.lock.as_deref(), Some("off"));
|
||||
assert!(profile.min_ram_available_bytes <= 10 * GIB && profile.min_ram_total_bytes <= 16 * GIB);
|
||||
profile.validate().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_small_host_gets_zero_resident_experts_and_dedicated_switches_too() {
|
||||
let plan = compute(&host(16, 24, 12), Some(&gpu(16384, 15500)), &server(), Preset::Dedicated);
|
||||
assert_eq!(plan.mapped_resident_gib, Some(0), "12 GiB available is below the 4 GiB target plus 8 GiB overhead");
|
||||
let ample = compute(&host(32, 121, 100), Some(&gpu(32607, 32100)), &server(), Preset::Workstation);
|
||||
assert_eq!(ample.mapped_resident_gib, None);
|
||||
assert!(ample.warnings.is_empty(), "{:?}", ample.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn presets_parse_and_default_to_dedicated() {
|
||||
assert_eq!(Preset::default(), Preset::Dedicated);
|
||||
assert_eq!(Preset::parse("workstation").unwrap(), Preset::Workstation);
|
||||
assert!(Preset::parse("x").is_err());
|
||||
}
|
||||
}
|
||||
//! Resource presets: how much of the host `leleka up` lets the engine take (`docs/deploy.md`, "Resource presets").
|
||||
//!
|
||||
//! * `dedicated` (default): the host belongs to the runtime. The profile's VRAM budget as it is, engine defaults for the
|
||||
//! memory governor, CPU workers up to the useful maximum.
|
||||
//! * `workstation`: Docker, agents and the IDE share the machine. At least 4 cores (8 on hosts with more than 16) stay
|
||||
//! free of engine workers, the memory governor keeps 8-16 GiB of host RAM free (it sheds the prefix cache first), and
|
||||
//! about 4 GiB of VRAM is left to the desktop; the expert tier is sized from what remains.
|
||||
//!
|
||||
//! `compute` is a pure function of the host facts and the profile; `apply` writes the result into the profile and the
|
||||
//! engine environment. Explicit profile fields and command-line overrides always win over a preset.
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{
|
||||
facts::{Facts, Gpu},
|
||||
profile::{ARCHIVE_BYTES, ExpertSource, KarSource, Profile},
|
||||
};
|
||||
|
||||
const GIB: u64 = 1 << 30;
|
||||
const MIB: u64 = 1 << 20;
|
||||
/// Decode is bound by host memory bandwidth: more CPU expert workers than this do not help (`docs/roofline.md`).
|
||||
const MAX_USEFUL_WORKERS: u32 = 8;
|
||||
/// VRAM the desktop/browser keeps in the workstation preset.
|
||||
const WORKSTATION_VRAM_MARGIN_MIB: u64 = 4096;
|
||||
/// Resident host memory of a memfd-backed engine besides the archive (tokenizer, pinned buffers, CUDA host state).
|
||||
const ENGINE_EXTRA_BYTES: u64 = 3 * GIB;
|
||||
/// Host memory the mapped form keeps for the engine itself, the tokenizer and the working set of the page cache.
|
||||
const MAPPED_OVERHEAD_BYTES: u64 = 8 * GIB;
|
||||
/// What the mapped form still needs available to start.
|
||||
const MAPPED_MIN_AVAILABLE_BYTES: u64 = 10 * GIB;
|
||||
pub const CPU_WORKERS_ENV: &str = "LELEKA_ORIGINAL_SERVE_CPU_WORKERS";
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Preset {
|
||||
#[default]
|
||||
Dedicated,
|
||||
Workstation,
|
||||
}
|
||||
|
||||
impl Preset {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Preset::Dedicated => "dedicated",
|
||||
Preset::Workstation => "workstation",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> Result<Preset, String> {
|
||||
match text {
|
||||
"dedicated" => Ok(Preset::Dedicated),
|
||||
"workstation" => Ok(Preset::Workstation),
|
||||
other => Err(format!(
|
||||
"unknown preset '{other}' (use dedicated or workstation)"
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct ResourcePlan {
|
||||
pub preset: Preset,
|
||||
pub cores: u32,
|
||||
/// `None` when the core count is unknown: the engine keeps its own default.
|
||||
pub cpu_workers: Option<u32>,
|
||||
pub gpu_budget_bytes: u64,
|
||||
/// The profile's `min_vram_free_mib`, lowered when the preset lowered the budget.
|
||||
pub min_vram_free_mib: Option<u64>,
|
||||
pub vram_free_after_mib: Option<u64>,
|
||||
/// Host RAM the memory governor keeps available: (soft, hard) floors in MiB, `None` = engine defaults.
|
||||
pub ram_floors_mib: Option<(u64, u64)>,
|
||||
pub ram_expected_free_after_bytes: Option<u64>,
|
||||
/// Host RAM cannot hold the sealed archive and the experts next to the free target: serve from SSD/HDD instead
|
||||
/// (archive as a read-only file, experts memory-mapped, this many GiB of them page-locked).
|
||||
pub mapped_resident_gib: Option<u32>,
|
||||
/// Shortfalls that make the preset unachievable (the preflight fails on them).
|
||||
pub problems: Vec<String>,
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
fn gib_text(bytes: u64) -> String {
|
||||
format!("{:.1} GiB", bytes as f64 / GIB as f64)
|
||||
}
|
||||
|
||||
/// RAM the workstation preset keeps free: 8 GiB on small hosts up to 16 GiB from 64 GiB of RAM.
|
||||
pub fn workstation_ram_target(total: u64) -> u64 {
|
||||
if total >= 64 * GIB {
|
||||
16 * GIB
|
||||
} else if total >= 32 * GIB {
|
||||
12 * GIB
|
||||
} else {
|
||||
8 * GIB
|
||||
}
|
||||
}
|
||||
|
||||
pub fn compute(facts: &Facts, gpu: Option<&Gpu>, profile: &Profile, preset: Preset) -> ResourcePlan {
|
||||
let mut plan = ResourcePlan {
|
||||
preset,
|
||||
cores: facts.cpu_cores,
|
||||
cpu_workers: None,
|
||||
gpu_budget_bytes: profile.gpu_budget_bytes,
|
||||
min_vram_free_mib: profile.min_vram_free_mib,
|
||||
vram_free_after_mib: None,
|
||||
ram_floors_mib: None,
|
||||
ram_expected_free_after_bytes: None,
|
||||
mapped_resident_gib: None,
|
||||
problems: Vec::new(),
|
||||
warnings: Vec::new(),
|
||||
};
|
||||
|
||||
// CPU
|
||||
if facts.cpu_cores > 0 {
|
||||
let cores = facts.cpu_cores;
|
||||
let leave = match preset {
|
||||
Preset::Dedicated => 2,
|
||||
Preset::Workstation if cores <= 16 => 4,
|
||||
Preset::Workstation => 8,
|
||||
};
|
||||
plan.cpu_workers = Some(cores.saturating_sub(leave).clamp(1, MAX_USEFUL_WORKERS));
|
||||
if preset == Preset::Workstation && cores < leave + 1 {
|
||||
plan.warnings.push(format!(
|
||||
"only {cores} CPU cores: the workstation preset cannot leave {leave} of them free (1 worker)"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// VRAM
|
||||
if let Some(gpu) = gpu {
|
||||
let budget_mib = profile.gpu_budget_bytes / MIB;
|
||||
if preset == Preset::Workstation {
|
||||
let cap_mib = (gpu.vram_free_mib.saturating_sub(WORKSTATION_VRAM_MARGIN_MIB) / 1024) * 1024;
|
||||
if cap_mib < budget_mib {
|
||||
plan.gpu_budget_bytes = cap_mib * MIB;
|
||||
let need = profile.min_vram_free_mib.unwrap_or(budget_mib).min(cap_mib);
|
||||
plan.min_vram_free_mib = Some(need);
|
||||
// Below half of the profile budget the expert tier and KV window shrink past what was measured.
|
||||
if cap_mib * 2 < budget_mib {
|
||||
plan.problems.push(format!(
|
||||
"the workstation preset leaves {} MiB of VRAM free, which gives the engine {} MiB; the profile {} needs about {} MiB (free the GPU or use --preset dedicated)",
|
||||
WORKSTATION_VRAM_MARGIN_MIB, cap_mib, profile.name, budget_mib
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
let used = (plan.gpu_budget_bytes / MIB).max(plan.min_vram_free_mib.unwrap_or(0));
|
||||
plan.vram_free_after_mib = Some(gpu.vram_free_mib.saturating_sub(used));
|
||||
}
|
||||
|
||||
// Host RAM
|
||||
let ram = &facts.memory;
|
||||
if ram.total > 0 {
|
||||
let target = match preset {
|
||||
Preset::Workstation => workstation_ram_target(ram.total),
|
||||
Preset::Dedicated => profile.memory.soft_floor_mib.map_or(4 * GIB, |mib| mib * MIB),
|
||||
};
|
||||
if preset == Preset::Workstation {
|
||||
let soft = target / MIB;
|
||||
plan.ram_floors_mib = Some((soft, soft / 2));
|
||||
}
|
||||
if profile.kar_source == KarSource::Memfd {
|
||||
let footprint = ARCHIVE_BYTES + ENGINE_EXTRA_BYTES;
|
||||
let after = ram.available.saturating_sub(footprint);
|
||||
if after >= target {
|
||||
plan.ram_expected_free_after_bytes = Some(after);
|
||||
} else {
|
||||
// Not enough RAM for the pinned form: map the archive and the experts from disk instead of failing.
|
||||
let resident = ram.available.saturating_sub(target + MAPPED_OVERHEAD_BYTES) / GIB;
|
||||
let resident = resident.min(u64::from(u32::MAX)) as u32;
|
||||
plan.mapped_resident_gib = Some(resident);
|
||||
plan.ram_expected_free_after_bytes = Some(ram.available.saturating_sub(u64::from(resident) * GIB + MAPPED_OVERHEAD_BYTES));
|
||||
plan.warnings.push(format!(
|
||||
"{} of host RAM available, the pinned form needs about {} plus {} free: the archive and the experts are served from disk (memory-mapped), {} GiB of experts stay page-locked; decode is slower than with everything in RAM",
|
||||
gib_text(ram.available),
|
||||
gib_text(footprint),
|
||||
gib_text(target),
|
||||
resident
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
plan
|
||||
}
|
||||
|
||||
/// Write the plan into the profile and the engine environment. Values the profile or the command line already set win.
|
||||
pub fn apply(
|
||||
plan: &ResourcePlan,
|
||||
profile: &mut Profile,
|
||||
engine_env: &mut BTreeMap<String, String>,
|
||||
budget_overridden: bool,
|
||||
) {
|
||||
if !budget_overridden {
|
||||
profile.gpu_budget_bytes = plan.gpu_budget_bytes;
|
||||
profile.min_vram_free_mib = plan.min_vram_free_mib;
|
||||
}
|
||||
if let Some((soft, hard)) = plan.ram_floors_mib {
|
||||
// The profile's floors are its dedicated-host values; the workstation preset only raises them.
|
||||
let raised = |current: Option<u64>, wanted: u64| Some(current.map_or(wanted, |c| c.max(wanted)));
|
||||
profile.memory.soft_floor_mib = raised(profile.memory.soft_floor_mib, soft);
|
||||
profile.memory.hard_floor_mib = raised(profile.memory.hard_floor_mib, hard);
|
||||
}
|
||||
if let Some(resident) = plan.mapped_resident_gib {
|
||||
profile.kar_source = KarSource::File;
|
||||
profile.expert_source = ExpertSource::Mapped;
|
||||
profile.memory.resident_budget_gib.get_or_insert(resident);
|
||||
profile.memory.lock = Some("off".into());
|
||||
profile.memory.heal = Some(false);
|
||||
profile.min_ram_total_bytes = profile.min_ram_total_bytes.min(16 * GIB);
|
||||
profile.min_ram_available_bytes = profile.min_ram_available_bytes.min(MAPPED_MIN_AVAILABLE_BYTES);
|
||||
}
|
||||
if let Some(workers) = plan.cpu_workers
|
||||
&& !profile.engine_env.contains_key(CPU_WORKERS_ENV)
|
||||
{
|
||||
engine_env.insert(CPU_WORKERS_ENV.to_owned(), workers.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
impl ResourcePlan {
|
||||
/// The table `leleka up` prints: what the engine takes and what stays free.
|
||||
pub fn render(&self, facts: &Facts) -> String {
|
||||
let mut out = format!("resources ({} preset)\n", self.preset.as_str());
|
||||
if let Some(workers) = self.cpu_workers {
|
||||
out.push_str(&format!(
|
||||
" cpu {workers} expert workers of {} cores; ~{} cores stay free\n",
|
||||
self.cores,
|
||||
self.cores.saturating_sub(workers + 1)
|
||||
));
|
||||
}
|
||||
out.push_str(&format!(
|
||||
" vram budget {}{}\n",
|
||||
gib_text(self.gpu_budget_bytes),
|
||||
self.vram_free_after_mib
|
||||
.map_or(String::new(), |free| format!(", ~{} MiB stay free", free))
|
||||
));
|
||||
match (self.ram_floors_mib, self.ram_expected_free_after_bytes) {
|
||||
(Some((soft, hard)), after) => out.push_str(&format!(
|
||||
" host ram caches shed below {} MiB available, requests refused below {} MiB{}\n",
|
||||
soft,
|
||||
hard,
|
||||
after.map_or(String::new(), |b| format!("; ~{} free after the start", gib_text(b)))
|
||||
)),
|
||||
(None, Some(after)) => out.push_str(&format!(
|
||||
" host ram engine defaults; ~{} of {} free after the start\n",
|
||||
gib_text(after),
|
||||
gib_text(facts.memory.total)
|
||||
)),
|
||||
(None, None) => {}
|
||||
}
|
||||
for warning in &self.warnings {
|
||||
out.push_str(&format!(" warning {warning}\n"));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::facts::Memory;
|
||||
|
||||
fn gpu(total: u64, free: u64) -> Gpu {
|
||||
Gpu { index: 0, name: "gpu".into(), driver: "595.1".into(), vram_total_mib: total, vram_free_mib: free, sm: Some(120) }
|
||||
}
|
||||
|
||||
fn host(cores: u32, ram_gib: u64, avail_gib: u64) -> Facts {
|
||||
Facts {
|
||||
cpu_cores: cores,
|
||||
memory: Memory { total: ram_gib * GIB, available: avail_gib * GIB, swap_total: 0 },
|
||||
..Facts::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn server() -> Profile {
|
||||
Profile::builtin("rtx5090-32g").unwrap()
|
||||
}
|
||||
fn laptop() -> Profile {
|
||||
Profile::builtin("rtx3080-16g").unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dedicated_takes_the_profile_and_caps_workers_at_the_useful_maximum() {
|
||||
let plan = compute(&host(32, 121, 100), Some(&gpu(32607, 32100)), &server(), Preset::Dedicated);
|
||||
assert_eq!(plan.cpu_workers, Some(8));
|
||||
assert_eq!(plan.gpu_budget_bytes, server().gpu_budget_bytes);
|
||||
assert_eq!(plan.ram_floors_mib, None);
|
||||
assert!(plan.problems.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workstation_leaves_cores_ram_and_vram_on_the_server() {
|
||||
let plan = compute(&host(32, 121, 100), Some(&gpu(32607, 32100)), &server(), Preset::Workstation);
|
||||
assert_eq!(plan.cpu_workers, Some(8), "32 cores - 8 left free = 24, capped at 8");
|
||||
assert_eq!(plan.gpu_budget_bytes, 27 * GIB, "32100 MiB free - 4096 MiB, rounded down to GiB");
|
||||
assert_eq!(plan.ram_floors_mib, Some((16384, 8192)));
|
||||
assert!(plan.problems.is_empty(), "{:?}", plan.problems);
|
||||
let mut profile = server();
|
||||
let mut env = BTreeMap::new();
|
||||
apply(&plan, &mut profile, &mut env, false);
|
||||
assert_eq!(profile.gpu_budget_bytes, 27 * GIB);
|
||||
assert_eq!(profile.memory.soft_floor_mib, Some(16384));
|
||||
assert_eq!(profile.memory.hard_floor_mib, Some(8192));
|
||||
assert_eq!(env.get(CPU_WORKERS_ENV).map(String::as_str), Some("8"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workstation_on_a_16_thread_laptop_leaves_four_cores_and_scales_the_ram_target() {
|
||||
let plan = compute(&host(16, 24, 21), Some(&gpu(16384, 15500)), &laptop(), Preset::Workstation);
|
||||
assert_eq!(plan.cpu_workers, Some(8));
|
||||
assert_eq!(plan.ram_floors_mib, Some((8192, 4096)));
|
||||
assert_eq!(plan.gpu_budget_bytes, 11 * GIB);
|
||||
assert!(plan.problems.is_empty(), "{:?}", plan.problems);
|
||||
let small = compute(&host(8, 24, 21), Some(&gpu(16384, 15500)), &laptop(), Preset::Workstation);
|
||||
assert_eq!(small.cpu_workers, Some(4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unachievable_workstation_vram_target_is_a_problem_not_a_silent_shrink() {
|
||||
let plan = compute(&host(16, 24, 21), Some(&gpu(16384, 9000)), &laptop(), Preset::Workstation);
|
||||
assert!(!plan.problems.is_empty());
|
||||
let dedicated = compute(&host(16, 24, 21), Some(&gpu(16384, 9000)), &laptop(), Preset::Dedicated);
|
||||
assert!(dedicated.problems.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_values_win_and_floors_are_only_raised() {
|
||||
let plan = compute(&host(32, 121, 100), Some(&gpu(32607, 32100)), &server(), Preset::Workstation);
|
||||
let mut profile = server();
|
||||
profile.memory.soft_floor_mib = Some(30000);
|
||||
profile.engine_env.insert(CPU_WORKERS_ENV.into(), "3".into());
|
||||
let mut env = BTreeMap::new();
|
||||
apply(&plan, &mut profile, &mut env, true);
|
||||
assert_eq!(profile.gpu_budget_bytes, server().gpu_budget_bytes, "--gpu-budget-gib wins");
|
||||
assert_eq!(profile.memory.soft_floor_mib, Some(30000));
|
||||
assert_eq!(profile.memory.hard_floor_mib, Some(8192), "floors are only ever raised");
|
||||
assert!(env.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_core_count_leaves_the_engine_default() {
|
||||
let plan = compute(&host(0, 121, 100), None, &server(), Preset::Workstation);
|
||||
assert_eq!(plan.cpu_workers, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn not_enough_ram_for_the_pinned_form_switches_to_mapped_files_instead_of_failing() {
|
||||
// 121 GiB host with 70 GiB available: 58 GiB of pinned archive leaves 12 GiB, below the 16 GiB workstation target
|
||||
let plan = compute(&host(32, 121, 70), Some(&gpu(32607, 32100)), &server(), Preset::Workstation);
|
||||
assert_eq!(plan.mapped_resident_gib, Some(46), "70 - 16 target - 8 overhead");
|
||||
assert_eq!(plan.warnings.len(), 1, "{:?}", plan.warnings);
|
||||
assert!(plan.render(&host(32, 121, 70)).contains("served from disk"));
|
||||
let mut profile = server();
|
||||
let mut env = BTreeMap::new();
|
||||
apply(&plan, &mut profile, &mut env, false);
|
||||
assert_eq!(profile.kar_source, KarSource::File);
|
||||
assert_eq!(profile.expert_source, ExpertSource::Mapped);
|
||||
assert_eq!(profile.memory.resident_budget_gib, Some(46));
|
||||
assert_eq!(profile.memory.lock.as_deref(), Some("off"));
|
||||
assert!(profile.min_ram_available_bytes <= 10 * GIB && profile.min_ram_total_bytes <= 16 * GIB);
|
||||
profile.validate().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_small_host_gets_zero_resident_experts_and_dedicated_switches_too() {
|
||||
let plan = compute(&host(16, 24, 12), Some(&gpu(16384, 15500)), &server(), Preset::Dedicated);
|
||||
assert_eq!(plan.mapped_resident_gib, Some(0), "12 GiB available is below the 4 GiB target plus 8 GiB overhead");
|
||||
let ample = compute(&host(32, 121, 100), Some(&gpu(32607, 32100)), &server(), Preset::Workstation);
|
||||
assert_eq!(ample.mapped_resident_gib, None);
|
||||
assert!(ample.warnings.is_empty(), "{:?}", ample.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn presets_parse_and_default_to_dedicated() {
|
||||
assert_eq!(Preset::default(), Preset::Dedicated);
|
||||
assert_eq!(Preset::parse("workstation").unwrap(), Preset::Workstation);
|
||||
assert!(Preset::parse("x").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,24 +1,24 @@
|
||||
//! Memory safety for the Leleka runtime: an allocation inventory, a startup budget that refuses what cannot fit and
|
||||
//! sizes the caches from what is left, a runtime pressure monitor that sheds load in a fixed order instead of letting the
|
||||
//! OOM killer or a swap storm decide, a residency guard for the sealed KAR memfd, and the census used by the soak tests.
|
||||
//!
|
||||
//! Model-free and CUDA-free by design: the runtime feeds it numbers (what it will allocate, what the device reports) and
|
||||
//! acts on its decisions (evict, refuse, lock). See `docs/memory-safety.md`.
|
||||
|
||||
pub mod census;
|
||||
pub mod governor;
|
||||
pub mod heap;
|
||||
pub mod host;
|
||||
pub mod inventory;
|
||||
pub mod ledger;
|
||||
pub mod lock;
|
||||
pub mod plan;
|
||||
pub mod pressure;
|
||||
pub mod procfs;
|
||||
pub mod telemetry;
|
||||
|
||||
pub use governor::{Admission, Governor, GovernorConfig, LockReport, Refuse, RequestShape, SamplerGuard, ShedDirective, published_report};
|
||||
pub use host::{FakeProc, HostFacts, ProcSource, RealProc};
|
||||
pub use inventory::{Entry, Inventory, Space, When};
|
||||
pub use plan::{CacheWish, FixedItem, GIB, KarForm, MIB, Plan, PlanInput, Policy, Refusal, VramFacts, VramPlan, check_vram};
|
||||
pub use pressure::Level;
|
||||
//! Memory safety for the Leleka runtime: an allocation inventory, a startup budget that refuses what cannot fit and
|
||||
//! sizes the caches from what is left, a runtime pressure monitor that sheds load in a fixed order instead of letting the
|
||||
//! OOM killer or a swap storm decide, a residency guard for the sealed KAR memfd, and the census used by the soak tests.
|
||||
//!
|
||||
//! Model-free and CUDA-free by design: the runtime feeds it numbers (what it will allocate, what the device reports) and
|
||||
//! acts on its decisions (evict, refuse, lock). See `docs/memory-safety.md`.
|
||||
|
||||
pub mod census;
|
||||
pub mod governor;
|
||||
pub mod heap;
|
||||
pub mod host;
|
||||
pub mod inventory;
|
||||
pub mod ledger;
|
||||
pub mod lock;
|
||||
pub mod plan;
|
||||
pub mod pressure;
|
||||
pub mod procfs;
|
||||
pub mod telemetry;
|
||||
|
||||
pub use governor::{Admission, Governor, GovernorConfig, LockReport, Refuse, RequestShape, SamplerGuard, ShedDirective, published_report};
|
||||
pub use host::{FakeProc, HostFacts, ProcSource, RealProc};
|
||||
pub use inventory::{Entry, Inventory, Space, When};
|
||||
pub use plan::{CacheWish, FixedItem, GIB, KarForm, MIB, Plan, PlanInput, Policy, Refusal, VramFacts, VramPlan, check_vram};
|
||||
pub use pressure::Level;
|
||||
|
||||
Reference in New Issue
Block a user