Merge claude/debt-final-ctx4: request counters, adaptive-tier tuning and the VRAM ledger leave the process cells; vague exception reasons fixed (STRA-338)
Rust port / port-typecheck (push) Successful in 1m46s
Desktop foundation / core (ubuntu-latest) (push) Successful in 5m6s
Rust port / port-linux-tests (push) Failing after 3m30s
Rust port / port-fast (push) Successful in 6m23s
Linux / verify (push) Failing after 7m48s
Linux / linux-static-cli (push) Skipped
Linux / linux-cli-container (push) Skipped
Linux / release-cli (push) Skipped
Rust port / port-oracles (push) Successful in 5m34s
Product / product (push) Failing after 30m51s

This commit is contained in:
Pavlo Ratushnyi
2026-11-24 07:52:28 +01:00
36 changed files with 331 additions and 256 deletions
+8 -11
View File
@@ -152,17 +152,16 @@
{"crate": "leleka-backend-api", "file": "src/scripted.rs", "ratchet": "dyn-trait", "reason": "the scripted test engine stores the test's responder closure"},
{"crate": "leleka-gateway-domain", "file": "src/responses/schema.rs", "ratchet": "process-global", "reason": "kept: pure memo (not state): the validity of a tool schema keyed by its compact text, so the dozen schemas of a coding agent compile once, not three times per request; the result depends on the key alone, so no caller can observe the cache; a per-request owner would defeat it"},
{"crate": "leleka-gateway-text", "file": "src/prompt/renderer.rs", "ratchet": "process-global", "reason": "kept: the compiled pinned chat template is an immutable constant of the build, compiled on first use and read by every request; a pure memo of a constant"},
{"crate": "leleka-control-plane", "file": "src/request_log.rs", "ratchet": "process-global", "reason": "kept for now (NOT a boundary): the request counters and histograms that /metrics renders are written by the request middleware and read by the metrics handler; both reach AppState, so the registry can move into Services. Left because it touches the request path of every endpoint and the metrics tests; follow-up of STRA-338"},
{"crate": "leleka-control-plane", "file": "src/stage_trace.rs", "ratchet": "process-global", "reason": "kept: diagnostic stage table of the replay harness and STRATA_STAGE_TRACE; time() and span() are called from deep helpers (render, tokenize) that carry no state argument, and the output is diagnostic only, never read by serving logic"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/settings/source.rs", "ratchet": "env-read", "reason": "the one reader of the process environment of the engine: ProcessEnv is the adapter of the EnvSource port, and Settings parses every variable into typed fields there (S13)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_engine/round_tally/serve_rounds.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per traced port call, only when the bring-up trace is on); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_lookahead.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per routing prediction on the lookahead thread); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_pool/direct_group_steps.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per CPU expert group of a decode round); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_pool/direct_tier.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per eager admission, once at start-up); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_pool.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per pool phase lap of a decode round); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_residency/pcie_share_controllers.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per PCIe lag probe and adaptation round); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/prefill_profile.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per prefill stage span, only when the profile switch is on); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/prompt_device_rows/prompt_device_read/produce_original_gdn.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per GDN layer producer lap, only when the command profile is on); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_engine/round_tally/serve_rounds.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: one reading per traced port call, only when the bring-up trace is on; the reading is a Duration that only feeds a log line or a counter, never a decision"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_lookahead.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: one reading per routing prediction on the lookahead thread; the reading is a Duration that only feeds a log line or a counter, never a decision"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_pool/direct_group_steps.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: one reading per CPU expert group of a decode round; the reading is a Duration that only feeds a log line or a counter, never a decision"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_pool/direct_tier.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: one reading per eager admission, once at start-up; the reading is a Duration that only feeds a log line or a counter, never a decision"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_pool.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: one reading per pool phase lap of a decode round; the reading is a Duration that only feeds a log line or a counter, never a decision"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_residency/pcie_share_controllers.rs", "ratchet": "instant-now", "reason": "control input, not a log line: PcieLag spins until the PCIe copies of a group have landed and PcieAuto times a round from one apply_pending to the next, and the control law reads those wall-clock durations to move the PCIe share; both controllers are opt-in experiments (LELEKA_PCIE_AUTO=lag|on, off in every shipped profile) and their unit tests drive the control law through round() without the clock"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/prefill_profile.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: one reading per prefill stage span, only when the profile switch is on; the reading is a Duration that only feeds a log line or a counter, never a decision"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/prompt_device_rows/prompt_device_read/produce_original_gdn.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: one reading per GDN layer producer lap, only when the command profile is on; the reading is a Duration that only feeds a log line or a counter, never a decision"},
{"crate": "leleka-engine-core", "file": "src/family.rs", "ratchet": "dyn-trait", "reason": "EngineFamily::spawn returns Box<dyn Backend>: the family seam is the process boundary of the engine, called once at start-up"},
{"crate": "leleka-engine-fake", "file": "src/lib.rs", "ratchet": "dyn-trait", "reason": "Box<dyn Backend> is the process boundary: the factory hands the composed engine to the host, which holds one Backend per process (startup composition only, never per round)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/family.rs", "ratchet": "dyn-trait", "reason": "Box<dyn Backend> is the process boundary: the factory hands the composed engine to the host, which holds one Backend per process (startup composition only, never per round)"},
@@ -174,7 +173,6 @@
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/original_serve/runner.rs", "ratchet": "dyn-trait", "reason": "the GPU telemetry probe is a stored callback handed in by the host at load (port, sampled by the telemetry tick, not per token)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding.rs", "ratchet": "process-global", "reason": "not a process global: `std::cell::OnceCell` is an instance field of the binding (lazy PLE reader); the gate pattern matches the type name"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding/model_binding.rs", "ratchet": "process-global", "reason": "not a process global: `std::cell::OnceCell::new()` initialises the instance field `ple_reader` of one ModelBinding; the gate pattern matches the type name"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_residency/split_group_pcie.rs", "ratchet": "process-global", "reason": "kept for now: the adaptive-tier tuning tuple is derived once from the process settings capture and emits the invalid-LELEKA_ADAPT_DECAY line once; it is read from three files (cross_layer_potential, source_spans, this one), so passing it needs a field on the residency state; not moved in this change (STRA-338 follow-up)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack.rs", "ratchet": "process-global", "reason": "kept: DBG_T0, the epoch of the bring-up trace timestamps (dbg_el()); diagnostics only, called from trace macros in many files that hold no common owner, never read by serving logic"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session.rs", "ratchet": "process-global", "reason": "not a process global: `std::cell::OnceCell` is an instance field of the session; the gate pattern matches the type name"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session/qwen_session.rs", "ratchet": "process-global", "reason": "not a process global: `std::cell::OnceCell::new()` initialises an instance field of one session; the gate pattern matches the type name"},
@@ -223,7 +221,6 @@
{"crate": "leleka-cuda-driver", "file": "src/qsa_prompt_resolver.rs", "ratchet": "process-global", "reason": "kept: pure memo of the resolver ABI proof of the embedded module, a function of the embedded bytes alone"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_ffi/asset_admission.rs", "ratchet": "process-global", "reason": "kept: per-operation pure memo of the PTX proof of an embedded sealed image, a function of the embedded bytes alone"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_ffi/n_types.rs", "ratchet": "process-global", "reason": "kept: the table of the PTX proof memos of asset_admission.rs, one cell per operation; pure functions of embedded bytes"},
{"crate": "leleka-cuda-driver", "file": "src/vram_ledger.rs", "ratchet": "process-global", "reason": "kept for now (diagnostic, NOT a boundary): the LELEKA_VRAM_LEDGER singleton is fed by every allocation site through free functions; the correct owner is the Context, which every allocation already reaches. Not moved in this change (STRA-338 follow-up)"},
{"crate": "leleka-cuda-driver", "file": "src/marker_files.rs", "ratchet": "process-global", "reason": "kept: the marker files of the A/B controls are operator-named paths read once with the time of the first look, so a hot path stats the disk at most every 250 ms; one type serves three controls"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_bench_frontend.rs", "ratchet": "process-global", "reason": "kept: FFI. `static mut stdout` is libc's C stream, declared in an extern block; it is the C library's own global, not ours"},
{"crate": "leleka-native-cpu-expert", "file": "src/settings.rs", "ratchet": "process-global", "reason": "kept: the cell of each `static Setting` (operator switches and the CPU probes the kernels dispatch on), computed on first read from the immutable environment and the CPU; the kernels are free functions called from pool worker threads that carry no context to pass a value through, and a hot path pays one atomic load"}
@@ -29,6 +29,7 @@ fn worker_config(tokenizer: Arc<Tokenizer>) -> BackendWorkerConfig {
cancel_drain_timeout: Duration::from_secs(5),
prefix_view: None,
memory_view: None,
request_metrics: Default::default(),
}
}
+1 -1
View File
@@ -77,7 +77,7 @@ pub(super) async fn metrics(State(state): State<AppState>, RawQuery(query): RawQ
let all = query.as_deref().is_some_and(|q| q.split('&').any(|pair| pair == "requests=all"));
let document = metrics_document(&state, all).await;
if crate::prometheus::wanted(query.as_deref(), accept) {
let mut response = crate::prometheus::render(&document).into_response();
let mut response = crate::prometheus::render(&document, &state.services.request_metrics).into_response();
response.headers_mut().insert(
axum::http::header::CONTENT_TYPE,
axum::http::HeaderValue::from_static(crate::prometheus::CONTENT_TYPE),
+1
View File
@@ -87,6 +87,7 @@ pub fn router(state: AppState) -> Router {
model: state.model.name.clone(),
memory: state.model.memory.clone(),
clock: state.services.clock.clone(),
metrics: state.services.request_metrics.clone(),
};
let routes = model_routes(server_routes(Router::new()));
let routes = chat_routes(response_routes(routes, &state, &observe), &state, &observe);
+3
View File
@@ -80,6 +80,8 @@ pub struct Services {
/// The MCP servers configured for the operator (`GET /mcp`).
pub mcp: Option<SharedToolHub>,
pub settings: Arc<crate::settings::Settings>,
/// The request counters and histograms that `/metrics` renders: written by the request middleware and the worker.
pub request_metrics: Arc<crate::request_log::RequestMetrics>,
/// Wall and monotonic time: queue deadlines, uptime, response timestamps.
pub clock: SharedClock,
pub started_at: SystemTime,
@@ -135,6 +137,7 @@ impl Default for Services {
monitor: Arc::new(Default::default()),
mcp: None,
settings: Arc::new(crate::settings::Settings::default()),
request_metrics: Arc::default(),
started_at: clock.system_time(),
clock,
}
+2
View File
@@ -74,6 +74,8 @@ pub struct BackendWorkerConfig {
/// Where the engine's memory-governor report is copied (health tick and after every request); `None` = not shown,
/// no gate.
pub memory_view: Option<Arc<crate::memory_view::MemoryView>>,
/// Where the worker counts the engine attaches and losses that `/metrics` renders.
pub request_metrics: Arc<crate::request_log::RequestMetrics>,
}
type Engine = Arc<Mutex<Box<dyn api::Backend>>>;
+2 -2
View File
@@ -167,7 +167,7 @@ impl AttachLoop {
/// The engine has the model: report ready and answer the `Load` requests that waited.
async fn become_ready(&mut self) {
self.attached_before = true;
crate::request_log::note_engine_attached();
self.config.request_metrics.note_engine_attached();
self.publish_ready_status().await;
self.answer_waiting_loads();
}
@@ -238,7 +238,7 @@ impl AttachLoop {
/// The engine is gone: record why and fail the worker.
async fn report_engine_lost(&self, reason: &str) {
crate::request_log::note_engine_lost(reason);
self.config.request_metrics.note_engine_lost(reason);
update(&self.status, WorkerState::Failed, None).await;
}
+2 -2
View File
@@ -35,7 +35,7 @@ pub(super) fn format_value(value: f64) -> String {
}
/// Render the `/metrics` document. `model` (when the document has one) labels `leleka_info`.
pub fn render(document: &Value) -> String {
pub fn render(document: &Value, requests: &crate::request_log::RequestMetrics) -> String {
let mut out = String::new();
let mut described: Vec<&str> = Vec::new();
for series in SERIES {
@@ -54,7 +54,7 @@ pub fn render(document: &Value) -> String {
let _ = writeln!(out, "# TYPE leleka_info gauge");
let model = document.get("model").and_then(Value::as_str).unwrap_or("");
let _ = writeln!(out, "leleka_info{{model=\"{}\"}} 1", escape(model));
crate::request_log::render_prometheus(&mut out);
requests.render_prometheus(&mut out);
out
}
+5 -4
View File
@@ -2,6 +2,7 @@
//! their fixed labels, unmeasured figures left out, and the choice of format by query or `Accept` header.
use super::*;
use crate::request_log::RequestMetrics;
use serde_json::json;
fn document() -> Value {
@@ -27,7 +28,7 @@ fn document() -> Value {
#[test]
fn counters_gauges_and_labels_render_in_the_text_format() {
let text = render(&document());
let text = render(&document(), &RequestMetrics::default());
assert!(text.contains("# TYPE leleka_generations_started_total counter\nleleka_generations_started_total 5\n"));
assert!(text.contains("leleka_prefill_seconds_total 2.5\n"));
assert!(text.contains("leleka_decode_seconds_total 1.25\n"));
@@ -85,7 +86,7 @@ const ENGINE_LINES: [&str; 16] = [
#[test]
fn engine_gauges_counters_and_throttle_reasons_are_exposed_with_fixed_labels() {
let text = render(&engine_document());
let text = render(&engine_document(), &RequestMetrics::default());
for expected in ENGINE_LINES {
assert!(text.contains(expected), "{expected} missing:\n{text}");
}
@@ -108,11 +109,11 @@ fn engine_gauges_counters_and_throttle_reasons_are_exposed_with_fixed_labels() {
#[test]
fn unmeasured_figures_are_not_exposed() {
let text = render(&document());
let text = render(&document(), &RequestMetrics::default());
// null in the document: no lifetime decode rate, no GPU clock, no swap
assert!(!text.contains("window=\"lifetime\""));
assert!(!text.contains("leleka_gpu_sm_clock_megahertz"));
let bare = render(&json!({"model": "m", "up": false}));
let bare = render(&json!({"model": "m", "up": false}), &RequestMetrics::default());
assert!(bare.contains("leleka_up 0\n"));
assert!(!bare.contains("leleka_gpu_") && !bare.contains("leleka_engine_phase"));
// every line is HELP, TYPE or a sample
+23 -17
View File
@@ -11,10 +11,10 @@
//! finalises the request, or, for a request that never reached the engine (a rejection, a client that left the queue),
//! when the last reference is dropped.
//!
//! The same moment feeds the Prometheus histograms and counters of [`render_prometheus`], whose labels are enums of
//! The same moment feeds the Prometheus histograms and counters of [`RequestMetrics`], whose labels are enums of
//! fixed size (endpoint x outcome, error class): there is no label whose value comes from a client.
use std::sync::{
Arc, LazyLock, Mutex,
Arc, Mutex,
atomic::{AtomicU64, Ordering},
};
@@ -85,6 +85,7 @@ struct Live {
pub struct ReqCtx {
state: Mutex<Live>,
clock: crate::ports::SharedClock,
metrics: Arc<RequestMetrics>,
}
/// What the request middleware leaves for the handler and the worker.
@@ -101,6 +102,7 @@ pub struct Observe {
pub model: Option<String>,
pub memory: Arc<crate::memory_view::MemoryView>,
pub clock: crate::ports::SharedClock,
pub metrics: Arc<RequestMetrics>,
}
/// Everything the line says, resolved.
@@ -128,7 +130,7 @@ pub struct Record {
pub hardware: Option<crate::memory_view::Brief>,
}
struct Registry {
pub struct RequestMetrics {
requests: Vec<AtomicU64>,
errors: Vec<AtomicU64>,
restarts: AtomicU64,
@@ -143,20 +145,24 @@ struct Registry {
prefill_tps: Histogram,
}
static REGISTRY: LazyLock<Registry> = LazyLock::new(|| Registry {
requests: (0..ENDPOINTS.len() * OUTCOMES.len()).map(|_| AtomicU64::new(0)).collect(),
errors: (0..ERROR_CLASSES.len()).map(|_| AtomicU64::new(0)).collect(),
restarts: AtomicU64::new(0),
engine_lost: AtomicU64::new(0),
engine_attached: AtomicU64::new(0),
ttft: Histogram::new(&[0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0]),
duration: Histogram::new(&[0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0, 600.0, 1800.0]),
queue: Histogram::new(&[0.001, 0.01, 0.1, 0.5, 1.0, 5.0, 15.0, 60.0]),
prompt_tokens: Histogram::new(&[256.0, 1024.0, 4096.0, 16384.0, 65536.0, 131072.0, 262144.0]),
output_tokens: Histogram::new(&[16.0, 64.0, 256.0, 1024.0, 4096.0, 16384.0, 65536.0]),
decode_tps: Histogram::new(&[5.0, 10.0, 20.0, 40.0, 60.0, 80.0, 100.0, 150.0]),
prefill_tps: Histogram::new(&[100.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0, 16000.0]),
});
impl Default for RequestMetrics {
fn default() -> Self {
Self {
requests: (0..ENDPOINTS.len() * OUTCOMES.len()).map(|_| AtomicU64::new(0)).collect(),
errors: (0..ERROR_CLASSES.len()).map(|_| AtomicU64::new(0)).collect(),
restarts: AtomicU64::new(0),
engine_lost: AtomicU64::new(0),
engine_attached: AtomicU64::new(0),
ttft: Histogram::new(&[0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0]),
duration: Histogram::new(&[0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0, 600.0, 1800.0]),
queue: Histogram::new(&[0.001, 0.01, 0.1, 0.5, 1.0, 5.0, 15.0, 60.0]),
prompt_tokens: Histogram::new(&[256.0, 1024.0, 4096.0, 16384.0, 65536.0, 131072.0, 262144.0]),
output_tokens: Histogram::new(&[16.0, 64.0, 256.0, 1024.0, 4096.0, 16384.0, 65536.0]),
decode_tps: Histogram::new(&[5.0, 10.0, 20.0, 40.0, 60.0, 80.0, 100.0, 150.0]),
prefill_tps: Histogram::new(&[100.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0, 16000.0]),
}
}
}
#[cfg(test)]
mod tests;
+97 -95
View File
@@ -1,107 +1,109 @@
//! The request metrics in the Prometheus text format (requests by endpoint and outcome, errors by class, engine lost,
//! attached and restart counters, time and token histograms) and the note that a worker attached to a loaded engine.
use super::{ENDPOINTS, ERROR_CLASSES, OUTCOMES, Ordering, REGISTRY};
use super::{ENDPOINTS, ERROR_CLASSES, OUTCOMES, Ordering, RequestMetrics};
use std::fmt::Write as _;
/// The worker attached to a loaded engine (at start and after every restart).
pub fn note_engine_attached() {
let n = REGISTRY.engine_attached.fetch_add(1, Ordering::Relaxed) + 1;
leleka_obs::emit_always(leleka_obs::Level::Info, "api", "engine_attached", &[("attaches", n.into())]);
}
impl RequestMetrics {
/// The worker attached to a loaded engine (at start and after every restart).
pub fn note_engine_attached(&self) {
let n = self.engine_attached.fetch_add(1, Ordering::Relaxed) + 1;
leleka_obs::emit_always(leleka_obs::Level::Info, "api", "engine_attached", &[("attaches", n.into())]);
}
/// Append the request metrics in the Prometheus text format.
pub fn render_prometheus(out: &mut String) {
render_requests(out);
render_errors(out);
render_engine_counters(out);
render_histograms(out);
}
/// Append the request metrics in the Prometheus text format.
pub fn render_prometheus(&self, out: &mut String) {
self.render_requests(out);
self.render_errors(out);
self.render_engine_counters(out);
self.render_histograms(out);
}
/// `leleka_requests_total` by endpoint and outcome (a zero line when there is none).
fn render_requests(out: &mut String) {
let reg = &*REGISTRY;
leleka_obs::hist::header(
"leleka_requests_total",
"Generation requests by endpoint and how they ended.",
"counter",
out,
);
let mut any = false;
for (e, endpoint) in ENDPOINTS.iter().enumerate() {
for (o, outcome) in OUTCOMES.iter().enumerate() {
let n = reg.requests[e * OUTCOMES.len() + o].load(Ordering::Relaxed);
if n > 0 {
any = true;
let _ = writeln!(out, "leleka_requests_total{{endpoint=\"{endpoint}\",outcome=\"{outcome}\"}} {n}");
/// `leleka_requests_total` by endpoint and outcome (a zero line when there is none).
fn render_requests(&self, out: &mut String) {
let reg = self;
leleka_obs::hist::header(
"leleka_requests_total",
"Generation requests by endpoint and how they ended.",
"counter",
out,
);
let mut any = false;
for (e, endpoint) in ENDPOINTS.iter().enumerate() {
for (o, outcome) in OUTCOMES.iter().enumerate() {
let n = reg.requests[e * OUTCOMES.len() + o].load(Ordering::Relaxed);
if n > 0 {
any = true;
let _ = writeln!(out, "leleka_requests_total{{endpoint=\"{endpoint}\",outcome=\"{outcome}\"}} {n}");
}
}
}
if !any {
let _ = writeln!(out, "leleka_requests_total{{endpoint=\"responses\",outcome=\"stop\"}} 0");
}
}
if !any {
let _ = writeln!(out, "leleka_requests_total{{endpoint=\"responses\",outcome=\"stop\"}} 0");
/// `leleka_request_errors_total` by error class.
fn render_errors(&self, out: &mut String) {
let reg = self;
leleka_obs::hist::header(
"leleka_request_errors_total",
"Failed or rejected requests by error class.",
"counter",
out,
);
for (c, class) in ERROR_CLASSES.iter().enumerate().skip(1) {
let n = reg.errors[c].load(Ordering::Relaxed);
let _ = writeln!(out, "leleka_request_errors_total{{class=\"{class}\"}} {n}");
}
}
/// The engine lost, attached and restart-request counters.
fn render_engine_counters(&self, out: &mut String) {
let reg = self;
let counters = [
(
"leleka_engine_lost_total",
"Times the API lost the engine (it restarted, hung or stopped answering).",
&reg.engine_lost,
),
(
"leleka_engine_attached_total",
"Times the API attached to a loaded engine (the first start counts).",
&reg.engine_attached,
),
("leleka_requests_engine_restart_total", "Requests during which the engine was lost.", &reg.restarts),
];
for (name, help, value) in counters {
leleka_obs::hist::header(name, help, "counter", out);
let _ = writeln!(out, "{name} {}", value.load(Ordering::Relaxed));
}
}
/// The time, token and rate histograms of the requests.
fn render_histograms(&self, out: &mut String) {
self.render_time_histograms(out);
self.render_size_histograms(out);
}
/// The time histograms: first token, duration and queue wait.
fn render_time_histograms(&self, out: &mut String) {
let reg = self;
reg.ttft.render("leleka_request_ttft_seconds", "Time from arrival to the first generated token.", out);
reg.duration.render("leleka_request_duration_seconds", "Time from arrival to the end of the request.", out);
reg.queue.render("leleka_request_queue_wait_seconds", "Time a request waited before the engine took it.", out);
}
/// The token-count and token-rate histograms.
fn render_size_histograms(&self, out: &mut String) {
let reg = self;
reg.prompt_tokens.render("leleka_request_prompt_tokens", "Prompt tokens per request.", out);
reg.output_tokens.render("leleka_request_output_tokens", "Output tokens per request.", out);
reg.decode_tps.render("leleka_request_decode_tokens_per_second", "Decode rate per request.", out);
reg.prefill_tps.render(
"leleka_request_prefill_tokens_per_second",
"Prefill rate per request (uncached prompt tokens).",
out,
);
}
}
/// `leleka_request_errors_total` by error class.
fn render_errors(out: &mut String) {
let reg = &*REGISTRY;
leleka_obs::hist::header(
"leleka_request_errors_total",
"Failed or rejected requests by error class.",
"counter",
out,
);
for (c, class) in ERROR_CLASSES.iter().enumerate().skip(1) {
let n = reg.errors[c].load(Ordering::Relaxed);
let _ = writeln!(out, "leleka_request_errors_total{{class=\"{class}\"}} {n}");
}
}
/// The engine lost, attached and restart-request counters.
fn render_engine_counters(out: &mut String) {
let reg = &*REGISTRY;
let counters = [
(
"leleka_engine_lost_total",
"Times the API lost the engine (it restarted, hung or stopped answering).",
&reg.engine_lost,
),
(
"leleka_engine_attached_total",
"Times the API attached to a loaded engine (the first start counts).",
&reg.engine_attached,
),
("leleka_requests_engine_restart_total", "Requests during which the engine was lost.", &reg.restarts),
];
for (name, help, value) in counters {
leleka_obs::hist::header(name, help, "counter", out);
let _ = writeln!(out, "{name} {}", value.load(Ordering::Relaxed));
}
}
/// The time, token and rate histograms of the requests.
fn render_histograms(out: &mut String) {
render_time_histograms(out);
render_size_histograms(out);
}
/// The time histograms: first token, duration and queue wait.
fn render_time_histograms(out: &mut String) {
let reg = &*REGISTRY;
reg.ttft.render("leleka_request_ttft_seconds", "Time from arrival to the first generated token.", out);
reg.duration.render("leleka_request_duration_seconds", "Time from arrival to the end of the request.", out);
reg.queue.render("leleka_request_queue_wait_seconds", "Time a request waited before the engine took it.", out);
}
/// The token-count and token-rate histograms.
fn render_size_histograms(out: &mut String) {
let reg = &*REGISTRY;
reg.prompt_tokens.render("leleka_request_prompt_tokens", "Prompt tokens per request.", out);
reg.output_tokens.render("leleka_request_output_tokens", "Output tokens per request.", out);
reg.decode_tps.render("leleka_request_decode_tokens_per_second", "Decode rate per request.", out);
reg.prefill_tps.render(
"leleka_request_prefill_tokens_per_second",
"Prefill rate per request (uncached prompt tokens).",
out,
);
}
+12 -9
View File
@@ -3,7 +3,7 @@
use super::{
Arc, CURRENT, Done, ENDPOINTS, ERROR_CLASSES, HeaderValue, Instant, Live, Next, OUTCOMES, ObsHandle, Observe,
Ordering, REGISTRY, REQUEST_ID_HEADER, Record, Registry, ReqCtx, ReqIdentity, Request, Response, State, V,
Ordering, REQUEST_ID_HEADER, Record, ReqCtx, ReqIdentity, Request, RequestMetrics, Response, State, V,
class_of_status, endpoint_index, session_tag,
};
@@ -69,7 +69,8 @@ pub async fn observe(State(observe): State<Observe>, request: Request, next: Nex
sid: session_tag(request.headers()),
model: observe.model.clone(),
};
let ctx = Arc::new(ReqCtx::new(identity, Some(observe.memory.clone()), observe.clock.clone()));
let ctx =
Arc::new(ReqCtx::new(identity, Some(observe.memory.clone()), observe.clock.clone(), observe.metrics.clone()));
let id = ctx.id();
let mut response = CURRENT.scope(ctx.clone(), next.run(request)).await;
ctx.set_http_status(response.status().as_u16());
@@ -224,13 +225,13 @@ impl Record {
}
}
pub(super) fn publish(&self) {
REGISTRY.observe(self);
pub(super) fn publish(&self, metrics: &RequestMetrics) {
metrics.observe(self);
leleka_obs::record("api", "request", &self.fields());
}
}
impl Registry {
impl RequestMetrics {
pub(super) fn observe(&self, r: &Record) {
let outcome = OUTCOMES.iter().position(|o| *o == r.outcome).unwrap_or(OUTCOMES.len() - 1);
self.requests[r.endpoint * OUTCOMES.len() + outcome].fetch_add(1, Ordering::Relaxed);
@@ -268,8 +269,10 @@ impl Registry {
}
}
/// The worker lost the engine (a structured warning is logged; the count feeds `leleka_engine_lost_total`).
pub fn note_engine_lost(reason: &str) {
REGISTRY.engine_lost.fetch_add(1, Ordering::Relaxed);
leleka_obs::warn("api", "engine_lost", &[("reason", reason.into())]);
impl RequestMetrics {
/// The worker lost the engine (a structured warning is logged; the count feeds `leleka_engine_lost_total`).
pub fn note_engine_lost(&self, reason: &str) {
self.engine_lost.fetch_add(1, Ordering::Relaxed);
leleka_obs::warn("api", "engine_lost", &[("reason", reason.into())]);
}
}
@@ -2,7 +2,8 @@
//! the classifiers that keep free text out of the line: endpoint index, session tag by digest, error class.
use super::{
Arc, Digest, Done, DoneInfo, Finish, HeaderMap, Live, Mutex, ObsHandle, Record, ReqCtx, SESSION_HEADERS, Sha256,
Arc, Digest, Done, DoneInfo, Finish, HeaderMap, Live, Mutex, ObsHandle, Record, ReqCtx, RequestMetrics,
SESSION_HEADERS, Sha256,
};
pub fn endpoint_index(path: &str) -> usize {
@@ -76,6 +77,7 @@ impl ReqCtx {
identity: ReqIdentity,
memory: Option<Arc<crate::memory_view::MemoryView>>,
clock: crate::ports::SharedClock,
metrics: Arc<RequestMetrics>,
) -> Self {
Self {
state: Mutex::new(Live {
@@ -96,6 +98,7 @@ impl ReqCtx {
memory,
}),
clock,
metrics,
}
}
@@ -171,7 +174,7 @@ impl ReqCtx {
Some(Record::from_state(s, self.clock.now()))
});
if let Some(Some(record)) = record {
record.publish();
record.publish(&self.metrics);
}
}
}
@@ -186,7 +189,7 @@ impl Drop for ReqCtx {
_ => None,
};
if let Some(record) = record {
record.publish();
record.publish(&self.metrics);
}
}
}
+18 -14
View File
@@ -34,14 +34,14 @@ fn ctx() -> ReqCtx {
sid: Some("s-0123456789".into()),
model: Some("qwen-iq3".into()),
};
ReqCtx::new(identity, None, crate::adapters::SystemClock::shared())
ReqCtx::new(identity, None, crate::adapters::SystemClock::shared(), Arc::default())
}
#[test]
fn the_record_stamps_come_from_the_injected_clock() {
let clock = crate::ports::fakes::ManualClock::new(1_700_000_000);
let identity = ReqIdentity { id: "rid".into(), endpoint: 0, sid: None, model: None };
let c = ReqCtx::new(identity, None, clock.clone());
let c = ReqCtx::new(identity, None, clock.clone(), Arc::default());
clock.advance(std::time::Duration::from_millis(40));
c.engine_start();
clock.advance(std::time::Duration::from_millis(60));
@@ -189,19 +189,20 @@ fn the_session_header_is_hashed_not_copied() {
assert_eq!(session_tag(&headers).unwrap(), tag);
}
fn counted(endpoint: &str, outcome: &str) -> u64 {
fn counted(metrics: &RequestMetrics, endpoint: &str, outcome: &str) -> u64 {
let mut text = String::new();
render_prometheus(&mut text);
metrics.render_prometheus(&mut text);
let prefix = format!("leleka_requests_total{{endpoint=\"{endpoint}\",outcome=\"{outcome}\"}} ");
text.lines().find_map(|l| l.strip_prefix(prefix.as_str())).and_then(|n| n.parse().ok()).unwrap_or(0)
}
/// A router whose handler asserts it sees the request's record and answers 503, behind the `observe` middleware.
fn rejecting_router() -> axum::Router {
fn rejecting_router(metrics: Arc<RequestMetrics>) -> axum::Router {
let observe = Observe {
model: Some("m".into()),
memory: Arc::new(Default::default()),
clock: crate::adapters::SystemClock::shared(),
metrics,
};
axum::Router::new()
.route(
@@ -217,8 +218,10 @@ fn rejecting_router() -> axum::Router {
}
/// Serves `rejecting_router` on a free port; returns its URL and the server task.
async fn serve_rejecting_handler() -> (String, tokio::task::JoinHandle<std::io::Result<()>>) {
let app = rejecting_router();
async fn serve_rejecting_handler(
metrics: Arc<RequestMetrics>,
) -> (String, tokio::task::JoinHandle<std::io::Result<()>>) {
let app = rejecting_router(metrics);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}/v1/chat/completions", listener.local_addr().unwrap());
let server = tokio::spawn(async move { axum::serve(listener, app).await });
@@ -227,10 +230,10 @@ async fn serve_rejecting_handler() -> (String, tokio::task::JoinHandle<std::io::
/// The rejected-chat count once it rises above `before`. The record is written when the last reference to it is gone,
/// just after the response.
async fn counted_after(before: u64) -> u64 {
async fn counted_after(metrics: &RequestMetrics, before: u64) -> u64 {
let mut after = before;
for _ in 0..50 {
after = counted("chat", "rejected");
after = counted(metrics, "chat", "rejected");
if after > before {
break;
}
@@ -241,14 +244,15 @@ async fn counted_after(before: u64) -> u64 {
#[tokio::test]
async fn the_middleware_names_the_request_hands_it_to_the_handler_and_records_a_rejection() {
let (url, server) = serve_rejecting_handler().await;
let before = counted("chat", "rejected");
let metrics = Arc::<RequestMetrics>::default();
let (url, server) = serve_rejecting_handler(metrics.clone()).await;
let before = counted(&metrics, "chat", "rejected");
let response = reqwest::Client::new().post(url).header("session_id", "conv-4417").body("{}").send().await.unwrap();
assert_eq!(response.status(), 503);
let id = response.headers()[REQUEST_ID_HEADER].to_str().unwrap().to_owned();
assert!(uuid::Uuid::parse_str(&id).is_ok(), "{id}");
assert!(!id.contains("4417"));
let after = counted_after(before).await;
let after = counted_after(&metrics, before).await;
assert!(after > before, "the rejection must be counted: {before} -> {after}");
server.abort();
}
@@ -259,9 +263,9 @@ fn the_prometheus_text_has_fixed_labels_and_valid_lines() {
c.engine_start();
c.first_token();
c.done(&done("DONE 10 100 5.0 100.0 length"), false);
record_of(&c).publish();
record_of(&c).publish(&c.metrics);
let mut text = String::new();
render_prometheus(&mut text);
c.metrics.render_prometheus(&mut text);
assert!(text.contains("leleka_requests_total{endpoint=\"responses\",outcome=\"length\"}"), "{text}");
assert!(text.contains("# TYPE leleka_request_ttft_seconds histogram"));
for line in text.lines() {
+1
View File
@@ -51,6 +51,7 @@ pub(super) fn worker_config(
cancel_drain_timeout: Duration::from_secs(20),
prefix_view: Some(state.model.prefix_cache.clone()),
memory_view: Some(state.model.memory.clone()),
request_metrics: state.services.request_metrics.clone(),
}
}
@@ -102,6 +102,7 @@ fn default_worker_config(tokenizer: Arc<Tokenizer>) -> BackendWorkerConfig {
cancel_drain_timeout: Duration::from_secs(5),
prefix_view: None,
memory_view: None,
request_metrics: Default::default(),
}
}
@@ -32,6 +32,7 @@ fn worker_config(stack: &Stack) -> BackendWorkerConfig {
cancel_drain_timeout: Duration::from_secs(1),
prefix_view: None,
memory_view: None,
request_metrics: Default::default(),
}
}
@@ -54,6 +54,7 @@ fn worker_config(tokenizer: Arc<Tokenizer>, memory: &Arc<MemoryView>) -> Backend
cancel_drain_timeout: Duration::from_secs(5),
prefix_view: None,
memory_view: Some(memory.clone()),
request_metrics: Default::default(),
}
}
+6 -1
View File
@@ -54,6 +54,11 @@ impl Context<'_> {
}
Ok(CurrentGuard { context: self, active: true })
}
/// Print the allocation sites of this context that changed since the last report (nothing while
/// `LELEKA_VRAM_LEDGER` is off).
pub fn report_vram_ledger(&self, label: &str) {
vram_ledger::report(&self.retained.vram_ledger, label);
}
pub fn allocate(&self, bytes: usize) -> Result<DeviceBuffer<'_>> {
valid_size(bytes)?;
let total = self.allocated.get().checked_add(bytes).ok_or(Error::BudgetExceeded)?;
@@ -68,7 +73,7 @@ impl Context<'_> {
// A successful allocation whose pop fails stays charged. The poisoned
// context owns that allocation until destruction, so no unguarded free.
let handle = combine(allocation, guard.finish())?;
vram_ledger::note_alloc(handle.qwen_address(), bytes);
vram_ledger::note_alloc(&self.retained.vram_ledger, handle.qwen_address(), bytes);
Ok(DeviceBuffer { context: self, handle: Some(handle), bytes, _thread: PhantomData, borrowed: false })
}
/// Queue a buffer's release for after the chunk's expert stream (it stays charged until then); when the
+2 -2
View File
@@ -1,9 +1,9 @@
//! DeviceBuffer host/device copies (whole buffer and ranges, staged through a host Vec, synchronised) and its release
//! and Drop, plus the LELEKA_CHAIN 'mtp' selector chain_selects_mtp with its no-driver stubs.
use super::{DeviceBuffer, Error, Result, combine, compute_drain, vram_ledger};
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
use super::original_verify;
use super::{DeviceBuffer, Error, Result, combine, compute_drain, vram_ledger};
impl DeviceBuffer<'_> {
pub fn len(&self) -> usize {
@@ -153,7 +153,7 @@ impl DeviceBuffer<'_> {
if self.borrowed {
return Ok(());
}
vram_ledger::note_free(handle.qwen_address());
vram_ledger::note_free(&self.context.retained.vram_ledger, handle.qwen_address());
if compute_drain::background() != 0 && !self.context.poisoned.get() {
// a chunk expert stream is in flight: do not synchronize the device now
return self.context.defer_free(handle, self.bytes);
@@ -4,6 +4,7 @@
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
use super::original_verify;
use super::{Cell, Rc, RefCell, ffi};
use crate::vram_ledger::Ledger;
use leleka_cuda_model::serving_context::ServingContext;
/// State that lives and dies with the context: its serving context, the lists (empty at the start) and the KV window
@@ -20,6 +21,8 @@ pub(crate) struct Retained {
pub(crate) deferred_frees: RefCell<Vec<(ffi::BufferHandle, usize)>>,
/// The resident KV window of this context's streamed QSA owners, in cells; `None` keeps the default window.
pub(crate) kv_resident: Cell<Option<usize>>,
/// The device allocations of this context by call site (`LELEKA_VRAM_LEDGER=1`; empty while it is off).
pub(crate) vram_ledger: RefCell<Ledger>,
}
impl Retained {
pub(crate) fn new(serving: ServingContext) -> Self {
@@ -28,6 +31,7 @@ impl Retained {
window_modules: RefCell::default(),
deferred_frees: RefCell::default(),
kv_resident: Cell::new(None),
vram_ledger: RefCell::default(),
}
}
}
+8 -13
View File
@@ -7,8 +7,8 @@
//! estimated to reserve: on the WDDM laptop probe (`scripts/dev/alloc-granularity-probe.py`) an allocation above 1 MiB
//! is rounded up to a multiple of 2 MiB (3 MiB takes 4 MiB, 2.5 MiB takes 4 MiB) while smaller ones are packed; the
//! 5090 load ledger agrees (the 322.1 MiB token table takes 324 MiB). The estimate is the "granularity waste" column.
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
const MIB: f64 = 1_048_576.0;
const GRANULE: usize = 2 << 20;
@@ -33,7 +33,7 @@ struct Site {
reported_n: usize,
}
/// The accounting itself, free of the process-global state so that tests can drive it.
/// The accounting of one `Context`, driven by the tests as well.
#[derive(Default)]
pub(crate) struct Ledger {
sites: Vec<Site>,
@@ -176,38 +176,33 @@ fn strip_hash(symbol: &str) -> &str {
}
}
fn state() -> &'static Mutex<Ledger> {
static STATE: OnceLock<Mutex<Ledger>> = OnceLock::new();
STATE.get_or_init(|| Mutex::new(Ledger::default()))
}
/// `LELEKA_VRAM_LEDGER=1`.
pub fn enabled() -> bool {
crate::settings::VRAM_LEDGER.get()
}
pub(crate) fn note_alloc(address: u64, bytes: usize) {
pub(crate) fn note_alloc(ledger: &RefCell<Ledger>, address: u64, bytes: usize) {
if !enabled() {
return;
}
let trace = std::backtrace::Backtrace::force_capture().to_string();
let key = site_key(&trace);
state().lock().unwrap_or_else(|e| e.into_inner()).alloc(address, bytes, &key);
ledger.borrow_mut().alloc(address, bytes, &key);
}
pub(crate) fn note_free(address: u64) {
pub(crate) fn note_free(ledger: &RefCell<Ledger>, address: u64) {
if !enabled() {
return;
}
state().lock().unwrap_or_else(|e| e.into_inner()).free(address);
ledger.borrow_mut().free(address);
}
/// Print the sites that changed since the last report to stderr (nothing when the ledger is off).
pub fn report(label: &str) {
pub(crate) fn report(ledger: &RefCell<Ledger>, label: &str) {
if !enabled() {
return;
}
let text = state().lock().unwrap_or_else(|e| e.into_inner()).report(label);
let text = ledger.borrow_mut().report(label);
eprintln!("{text}");
}
@@ -104,6 +104,7 @@ pub(crate) struct ExpertTierConfig {
/// `--adapt-every` (4) and `--adapt-swaps` (96); either 0 turns the adaptive tier off.
pub(crate) adapt_every: u32,
pub(crate) adapt_swaps: u32,
pub(crate) adapt_tuning: AdaptTuning,
/// `!--no-prefill-borrow` (the loan is taken only with a profile, as in the Original).
pub(crate) prefill_borrow: bool,
/// `--resident-budget-gib` over the low-RAM file-mapped bank (0: off): see `pin_resident_complement`.
@@ -159,9 +160,6 @@ pub(in crate::qwen_forward) struct Swap {
pub(in crate::qwen_forward) outgoing: usize,
}
/// Default of `LELEKA_ADAPT_DECAY` (generate.cpp's constant).
const ADAPT_DECAY_DEFAULT: f32 = 0.7;
/// Counters of the tier (the Original's `R4 expert-cache hits` / `adaptive tier` report lines).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct ResidencyStats {
@@ -261,6 +259,7 @@ pub(in crate::qwen_forward) struct GpuExpertPool<'p, 'a, 'ctx> {
pub(in crate::qwen_forward) pcie_num: u32,
pub(in crate::qwen_forward) adapt_every: u32,
pub(in crate::qwen_forward) adapt_swaps: usize,
pub(in crate::qwen_forward) adapt_tuning: AdaptTuning,
/// The route tail skip rank of this decode phase (0 = off; `effective_tail_rank`).
pub(in crate::qwen_forward) tail_rank: u32,
/// `layer * 512 + expert` -> the expert's pages are page-locked (`MappedExpertBank::locked_experts`); empty =
@@ -282,10 +281,12 @@ pub(crate) use tail_skip_rank::set_tail_skip_arm;
pub(in crate::qwen_forward) use tail_skip_rank::split_group;
#[cfg(test)]
pub(in crate::qwen_forward) use tail_skip_rank::split_group_tail;
mod adapt_tuning;
mod split_group_pcie;
pub(crate) use adapt_tuning::AdaptTuning;
pub(in crate::qwen_forward) use adapt_tuning::SwapCap;
#[cfg(test)]
use split_group_pcie::adapt_decay;
use split_group_pcie::adapt_tuning;
use adapt_tuning::adapt_decay;
#[cfg(test)]
use split_group_pcie::choose_swaps_reference;
pub(in crate::qwen_forward) use split_group_pcie::pcie_locked_only;
@@ -0,0 +1,58 @@
//! The experiment knobs of the adaptive tier, parsed once into the tier configuration: the least routed count a
//! missing expert needs, the count lead over the victim, and the decay of the counts per adaptation.
use super::TieOrder;
use crate::settings::MemorySettings;
/// Default of `LELEKA_ADAPT_DECAY` (generate.cpp's constant).
const ADAPT_DECAY_DEFAULT: f32 = 0.7;
/// `LELEKA_ADAPT_MIN_COUNT` (2.0: the least routed count a missing expert needs to be swapped in),
/// `LELEKA_ADAPT_MARGIN` (1.5: the count lead over the victim), `LELEKA_ADAPT_DECAY` (0.7: counts decay per
/// adaptation). The defaults are generate.cpp's constants.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct AdaptTuning {
pub(crate) min_count: f32,
pub(crate) margin: f32,
pub(crate) decay: f32,
}
impl Default for AdaptTuning {
fn default() -> Self {
Self { min_count: 2.0, margin: 1.5, decay: ADAPT_DECAY_DEFAULT }
}
}
impl AdaptTuning {
/// The tuning the operator chose; an invalid decay is replaced by the default with one line on the operator log.
pub(crate) fn from_settings(memory: &MemorySettings) -> Self {
let (decay, line) = adapt_decay(memory.adapt_decay.as_deref());
if let Some(line) = line {
eprintln!("leleka-serve {line}");
}
Self { min_count: memory.adapt_min_count, margin: memory.adapt_margin, decay }
}
}
/// How many swaps one adaptation may make, in which order equal gains compete for them, and under which tuning.
#[derive(Clone, Copy)]
pub(in crate::qwen_forward) struct SwapCap {
pub(in crate::qwen_forward) max_swaps: usize,
pub(in crate::qwen_forward) ties: TieOrder,
pub(in crate::qwen_forward) tuning: AdaptTuning,
}
/// `LELEKA_ADAPT_DECAY` must lie in 0..=1 (upstream 4a7e373d): above 1 the usage counts grow without end (inf after a
/// few hundred adaptations) and the swap gains turn NaN, which breaks the swap sort; below 0 the counts flip sign.
/// Anything else (out of range, not a finite number) falls back to the default, with the line to log. Unset gives the
/// default silently.
pub(super) fn adapt_decay(raw: Option<&str>) -> (f32, Option<String>) {
let Some(text) = raw else { return (ADAPT_DECAY_DEFAULT, None) };
match text.trim().parse::<f32>() {
Ok(v) if v.is_finite() && (0.0..=1.0).contains(&v) => (v, None),
_ => (
ADAPT_DECAY_DEFAULT,
Some(format!("LELEKA_ADAPT_DECAY={text:?} is outside 0..1; using {ADAPT_DECAY_DEFAULT}")),
),
}
}
@@ -7,7 +7,7 @@
//! mass of the experts that are not resident, and the total gain of the swaps that would be made (a) inside each
//! layer (uncapped, the present rule) and (b) over all layers together (a slot may move to another layer). Nothing
//! here changes a swap; the profile prints the average per adaptation.
use super::{EXPERTS, LAYERS, adapt_tuning};
use super::{AdaptTuning, EXPERTS, LAYERS};
type Entry = (f32, usize);
@@ -37,12 +37,12 @@ fn pairing(mut cand: Vec<Entry>, mut vict: Vec<Entry>, margin: f32) -> (f64, usi
}
/// Adds the estimate of one adaptation; a no-op unless the profile and its tier-cross switch are on.
pub(super) fn record(usage: &[f32], resident: impl Fn(usize, usize) -> bool) {
pub(super) fn record(usage: &[f32], resident: impl Fn(usize, usize) -> bool, tuning: AdaptTuning) {
use super::super::original_serve_profile::{add, enabled};
if !enabled() || !crate::settings::process().diagnostics.profile_tier_cross || usage.len() != LAYERS * EXPERTS {
return;
}
let (min_count, margin, _) = adapt_tuning();
let AdaptTuning { min_count, margin, .. } = tuning;
let layers = split(usage, &resident, min_count);
let (mut within, mut n_within) = (0.0, 0);
for (cand, vict) in &layers {
@@ -5,8 +5,7 @@ use super::{
CpuExpertPool, EXPERTS, Error, GpuExpertPool, GroupSplit, LAYERS, MappedExpertBank, ModelBinding, MoeWeightCache,
OriginalGpuStream, OriginalServePool, OriginalVerifyCpuRows, OriginalVerifyCpuSink, OriginalVerifyPcieSource,
PcieAuto, PcieLag, PcieSplitPolicy, Rc, ResidentExpertBankSpan, Result, RoutedGroup, SpanCache, StrataPcieAuto,
Swap, SwapSources, TOP_K, TieOrder, adapt_tuning, choose_swaps_by, driver_error, span_cache_enabled,
split_group_pcie,
Swap, SwapCap, SwapSources, TOP_K, TieOrder, choose_swaps_by, driver_error, span_cache_enabled, split_group_pcie,
};
/// The source spans of `experts` of `layer`, in order: from the cache when seen before, else through the CPU
@@ -131,7 +130,7 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> {
self.cache.arm_swaps().map_err(|e| driver_error(&e))?;
drop(p);
let _p = super::super::original_serve_profile::span("adapt.decay");
let decay = adapt_tuning().2;
let decay = self.adapt_tuning.decay;
for value in &mut self.state.usage {
*value *= decay;
}
@@ -291,10 +290,11 @@ impl<'ctx> GpuExpertPool<'_, '_, 'ctx> {
let cache = &*self.cache;
let p = super::super::original_serve_profile::span("adapt.choose");
let ties = self.tie_order();
let swaps =
choose_swaps_by(&self.state.usage, |l, e| cache.resident_slot(l, e).is_some(), (self.adapt_swaps, ties));
let cap = SwapCap { max_swaps: self.adapt_swaps, ties, tuning: self.adapt_tuning };
let swaps = choose_swaps_by(&self.state.usage, |l, e| cache.resident_slot(l, e).is_some(), cap);
drop(p);
super::cross_layer_potential::record(&self.state.usage, |l, e| cache.resident_slot(l, e).is_some());
let resident = |l, e| cache.resident_slot(l, e).is_some();
super::cross_layer_potential::record(&self.state.usage, resident, self.adapt_tuning);
let p = super::super::original_serve_profile::span("adapt.queue");
for swap in &swaps {
let slot = self.cache.resident_slot(swap.layer, swap.outgoing).ok_or(Error::IdentityMismatch)?;
@@ -3,8 +3,8 @@
//! Pure planning over ids and residency; it touches no device and no source.
use super::{
ADAPT_DECAY_DEFAULT, EXPERTS, Error, GroupSplit, LAYERS, MAX_WINDOW_ENTRIES, ORIGINAL_VERIFY_MAX_PCIE_FETCHES,
OriginalVerifyGpuPlan, ResidencyStats, Result, Swap, TieOrder,
AdaptTuning, EXPERTS, Error, GroupSplit, LAYERS, MAX_WINDOW_ENTRIES, ORIGINAL_VERIFY_MAX_PCIE_FETCHES,
OriginalVerifyGpuPlan, ResidencyStats, Result, Swap, SwapCap, TieOrder,
};
/// `split_group_tail` with a say in which misses may take the PCIe share: only an expert `pcie_ok` accepts is staged,
@@ -203,38 +203,6 @@ pub(in crate::qwen_forward) fn pcie_locked_only() -> bool {
crate::settings::process().memory.pcie_locked_only
}
/// Experiment knobs of the adaptive tier (claude/decode-parity; the defaults are generate.cpp's constants):
/// `LELEKA_ADAPT_MIN_COUNT` (2.0: the least routed count a missing expert needs to be swapped in),
/// `LELEKA_ADAPT_MARGIN` (1.5: the count lead over the victim), `LELEKA_ADAPT_DECAY` (0.7: counts decay per
/// adaptation).
pub(super) fn adapt_tuning() -> (f32, f32, f32) {
static TUNING: std::sync::OnceLock<(f32, f32, f32)> = std::sync::OnceLock::new();
*TUNING.get_or_init(|| {
let memory = &crate::settings::process().memory;
let decay = adapt_decay(memory.adapt_decay.as_deref());
if let Some(line) = decay.1 {
eprintln!("leleka-serve {line}");
}
(memory.adapt_min_count, memory.adapt_margin, decay.0)
})
}
/// `LELEKA_ADAPT_DECAY` must lie in 0..=1 (upstream 4a7e373d): above 1 the usage counts grow without end (inf after a
/// few hundred
/// adaptations) and the swap gains turn NaN, which breaks the swap sort; below 0 the counts flip sign. Anything else
/// (out of range,
/// not a finite number) falls back to the default, with the line to log. Unset gives the default silently.
pub(super) fn adapt_decay(raw: Option<&str>) -> (f32, Option<String>) {
let Some(text) = raw else { return (ADAPT_DECAY_DEFAULT, None) };
match text.trim().parse::<f32>() {
Ok(v) if v.is_finite() && (0.0..=1.0).contains(&v) => (v, None),
_ => (
ADAPT_DECAY_DEFAULT,
Some(format!("LELEKA_ADAPT_DECAY={text:?} is outside 0..1; using {ADAPT_DECAY_DEFAULT}")),
),
}
}
/// generate.cpp `adapt`'s ranking over `usage[l * 512 + e]`: per layer the non-resident experts routed at
/// least twice (most first) against the resident ones (least first), pairwise while
/// `cand >= vict + 1.5`; all layers' swaps by gain, the best `max_swaps`. Ties keep ascending expert / layer
@@ -243,17 +211,17 @@ pub(in crate::qwen_forward) fn choose_swaps(
usage: &[f32],
resident: impl Fn(usize, usize) -> bool,
max_swaps: usize,
tuning: AdaptTuning,
) -> Vec<Swap> {
choose_swaps_by(usage, resident, (max_swaps, TieOrder::LowLayerFirst))
choose_swaps_by(usage, resident, SwapCap { max_swaps, ties: TieOrder::LowLayerFirst, tuning })
}
/// `choose_swaps` with the order in which equal-gain swaps compete for the `max_swaps` cap (`cap`.1).
/// `choose_swaps` with the order in which equal-gain swaps compete for the `max_swaps` cap (`cap.ties`).
pub(in crate::qwen_forward) fn choose_swaps_by(
usage: &[f32],
resident: impl Fn(usize, usize) -> bool,
cap: (usize, TieOrder),
cap: SwapCap,
) -> Vec<Swap> {
let (max_swaps, ties) = cap;
let (min_count, margin, _) = adapt_tuning();
let SwapCap { max_swaps, ties, tuning: AdaptTuning { min_count, margin, .. } } = cap;
let mut swaps = Vec::new();
if usage.len() != LAYERS * EXPERTS {
return swaps;
@@ -323,8 +291,9 @@ pub(super) fn choose_swaps_reference(
usage: &[f32],
resident: impl Fn(usize, usize) -> bool,
max_swaps: usize,
tuning: AdaptTuning,
) -> Vec<Swap> {
let (min_count, margin, _) = adapt_tuning();
let AdaptTuning { min_count, margin, .. } = tuning;
let mut swaps = Vec::new();
if usage.len() != LAYERS * EXPERTS {
return swaps;
@@ -2,10 +2,11 @@
//! defaults, validation, `LELEKA_ORIGINAL_SERVE_*` switches) and the route tail-skip rank of a decode phase.
use super::{
AtomicU32, EXPERTS, EnvSource, Error, ExpertTierConfig, GroupSplit, LAYERS, Ordering, OriginalExpertCache, PathBuf,
PcieMode, PcieSplitPolicy, Result, RoutedGroup, TAIL_SKIP_RANK, TAIL_UNRESOLVED, TOP_K, VERIFIER_ASSEMBLY_MIB,
split_group_pcie, strata_pcie_auto,
AdaptTuning, AtomicU32, EXPERTS, EnvSource, Error, ExpertTierConfig, GroupSplit, LAYERS, Ordering,
OriginalExpertCache, PathBuf, PcieMode, PcieSplitPolicy, Result, RoutedGroup, TAIL_SKIP_RANK, TAIL_UNRESOLVED,
TOP_K, VERIFIER_ASSEMBLY_MIB, split_group_pcie, strata_pcie_auto,
};
use crate::settings::MemorySettings;
/// The tail-skip rank in force (0 = off): the environment, read once, unless a replay arm set it.
pub(crate) fn tail_skip_rank() -> u32 {
@@ -77,21 +78,14 @@ impl ExpertTierConfig {
per_layer: false,
profile: None,
reserve_mib: 700,
// measured (jobs 989/990/988): the per-request verifier needs ~450 MiB, so 1024 left ~550 MiB idle
// (180k smoke included); 300 gives the auto-sized cache ~+330 slots. 5090, 5 x 245k session
// (speedtrain-ab): with 300 the card never had less than 563 MiB free (vanilla runs down to 315), so
// 130 would be safe on the card (E: +87 slots), but the first slots-footprint A/B showed the Context
// BUDGET is a second ceiling the planner now respects (`usable_room`); 130 stays an opt-in
// (`LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB=130`) until its own arm measures it.
decode_reserve_mib: 300,
// the PCIe share that equalises the legs when the CPU pool and the DMA share the host's memory ceiling
// (P/(P+C) = 0.45, job 987-b/909; 0.45 vs 0.55: +0.5 % / +4.7 % at auto-sized cache, equal at 2048 slots)
pcie_frac: 0.45,
pcie_frac_set: false,
pcie_mode: PcieMode::Auto,
strata_pcie_auto: None,
adapt_every: 4,
adapt_swaps: 96,
adapt_tuning: AdaptTuning::default(),
prefill_borrow: true,
resident_budget_gib: 0.0,
seed_swaps: 0,
@@ -212,6 +206,7 @@ impl ExpertTierConfig {
if let Some(v) = serve_var(env, "ADAPT_SWAPS") {
self.adapt_swaps = v.parse().map_err(|_| Error::InvalidDimension)?;
}
self.adapt_tuning = AdaptTuning::from_settings(&MemorySettings::from_source(env));
if let Some(v) = serve_var(env, "PREFILL_BORROW") {
self.prefill_borrow = !matches!(v.as_str(), "no" | "0" | "off");
}
@@ -2,8 +2,9 @@
//! (residents, PCIe share, tail skip, invalid ids), the lag controller, the PCIe mode and the off-by-default config.
use super::{
EXPERTS, ExpertTierConfig, GroupSplit, LAYERS, PcieLag, PcieMode, PcieSplitPolicy, ResidencyState, RoutedGroup,
VANILLA_FREE_FLOOR_MIB, VERIFIER_ASSEMBLY_MIB, adapt_decay, choose_swaps, split_group_pcie, split_group_tail,
AdaptTuning, EXPERTS, ExpertTierConfig, GroupSplit, LAYERS, PcieLag, PcieMode, PcieSplitPolicy, ResidencyState,
RoutedGroup, VANILLA_FREE_FLOOR_MIB, VERIFIER_ASSEMBLY_MIB, adapt_decay, choose_swaps, split_group_pcie,
split_group_tail,
};
#[cfg(test)]
use super::{choose_swaps_reference, split_group};
@@ -71,8 +72,8 @@ fn the_selection_based_ranking_picks_the_reference_swaps_in_the_same_order() {
let resident_bits: Vec<bool> = (0..LAYERS * EXPERTS).map(|_| next() % (2 + (case % 4) as u64) != 0).collect();
let resident = |l: usize, e: usize| resident_bits[l * EXPERTS + e];
for max_swaps in [1usize, 5, 96, 4096] {
let fast = choose_swaps(&usage, resident, max_swaps);
let slow = choose_swaps_reference(&usage, resident, max_swaps);
let fast = choose_swaps(&usage, resident, max_swaps, AdaptTuning::default());
let slow = choose_swaps_reference(&usage, resident, max_swaps, AdaptTuning::default());
assert_eq!(fast.len(), slow.len(), "case {case} max {max_swaps}");
for (a, b) in fast.iter().zip(&slow) {
assert_eq!(
@@ -108,8 +109,8 @@ fn choose_swaps_timing() {
}
(t.elapsed().as_secs_f64() * 1e6 / 200.0, n)
};
let (fast, a) = time(&|| choose_swaps(&usage, resident, 96).len());
let (slow, b) = time(&|| choose_swaps_reference(&usage, resident, 96).len());
let (fast, a) = time(&|| choose_swaps(&usage, resident, 96, AdaptTuning::default()).len());
let (slow, b) = time(&|| choose_swaps_reference(&usage, resident, 96, AdaptTuning::default()).len());
eprintln!("choose_swaps: new {fast:.0} us, reference {slow:.0} us per call ({a} {b})");
}
@@ -280,14 +281,14 @@ fn swaps_take_the_most_routed_misses_over_the_least_routed_residents() {
// layer 7: resident 4 (0.0), candidate 30 (2.0: the least count a candidate may have)
usage[7 * EXPERTS + 30] = 2.0;
let resident = |l: usize, e: usize| (l == 2 && e < 3) || (l == 7 && e == 4);
let swaps = choose_swaps(&usage, resident, 96);
let swaps = choose_swaps(&usage, resident, 96, AdaptTuning::default());
// layer 2 pairs: (10, 1) gain 8.5; (11, 2): 2.5 < 3.0 + 1.5 stops; layer 7: (30, 4) gain 2.0
assert_eq!(swaps.len(), 2);
assert_eq!((swaps[0].layer, swaps[0].incoming, swaps[0].outgoing), (2, 10, 1));
assert_eq!((swaps[1].layer, swaps[1].incoming, swaps[1].outgoing), (7, 30, 4));
assert_eq!(choose_swaps(&usage, resident, 1).len(), 1);
assert_eq!(choose_swaps(&usage, resident, 1, AdaptTuning::default()).len(), 1);
// no resident in a layer: no swap there (a native pack's cache only changes through its profile)
assert!(choose_swaps(&usage, |_, _| false, 96).is_empty());
assert!(choose_swaps(&usage, |_, _| false, 96, AdaptTuning::default()).is_empty());
}
#[test]
@@ -1,6 +1,6 @@
//! Golden cases of `ExpertTierConfig::from_source`, the strict parser of the `LELEKA_ORIGINAL_SERVE_*` tier
//! switches: a value that does not parse (or fails `validate`) is refused, never ignored.
use super::{ExpertTierConfig, PathBuf, PcieMode, ResidencyState, Result};
use super::{AdaptTuning, ExpertTierConfig, PathBuf, PcieMode, ResidencyState, Result};
use crate::settings::MapEnv;
const P: &str = "LELEKA_ORIGINAL_SERVE_";
@@ -142,3 +142,16 @@ fn the_controller_exists_only_for_the_switch_and_the_fixed_share_is_untouched()
assert_eq!(ResidencyState::new(&on).strata_pcie_link_gbps, Some(30.0));
assert_eq!(on.pcie_num(), off.pcie_num(), "the start share is the configured one");
}
#[test]
fn the_adaptive_tuning_travels_with_the_tier_config() {
let tuned = MapEnv::new()
.with("LELEKA_ADAPT_MIN_COUNT", "3")
.with("LELEKA_ADAPT_MARGIN", "0.5")
.with("LELEKA_ADAPT_DECAY", "0.9");
let tier = ExpertTierConfig::from_source(&tuned).unwrap();
assert_eq!(tier.adapt_tuning, AdaptTuning { min_count: 3.0, margin: 0.5, decay: 0.9 });
assert_eq!(read(&[]).map(|c| c.adapt_tuning), Ok(AdaptTuning::default()));
let outside = MapEnv::new().with("LELEKA_ADAPT_DECAY", "1.5");
assert_eq!(ExpertTierConfig::from_source(&outside).map(|c| c.adapt_tuning.decay), Ok(0.7));
}
@@ -18,7 +18,7 @@ use super::{
contract::{Error, Result},
moe_weight_cache::MoeWeightCache,
original_serve_pool::CpuExpertPool,
original_serve_residency::{SpanCache, Swap, choose_swaps, source_spans},
original_serve_residency::{AdaptTuning, SpanCache, Swap, choose_swaps, source_spans},
original_serve_verifier::driver_error,
};
use crate::model_binding::weight_binding::ModelBinding;
@@ -53,7 +53,12 @@ pub(crate) struct SeedReport {
/// The seed's swaps: `counts[layer * 512 + expert]` are the prompt's routed rows per expert, `keep` a credit for every
/// resident expert (the blend with the profile's placement).
pub(super) fn plan(counts: &[f32], cache: &OriginalExpertCache<'_>, max_swaps: usize, keep: f32) -> Vec<Swap> {
pub(super) fn plan(
counts: &[f32],
cache: &OriginalExpertCache<'_>,
(max_swaps, keep): (usize, f32),
tuning: AdaptTuning,
) -> Vec<Swap> {
let mut usage: Vec<f32> = counts.to_vec();
if keep > 0.0 {
for layer in 0..LAYERS {
@@ -64,7 +69,7 @@ pub(super) fn plan(counts: &[f32], cache: &OriginalExpertCache<'_>, max_swaps: u
}
}
}
choose_swaps(&usage, |layer, expert| cache.resident_slot(layer, expert).is_some(), max_swaps)
choose_swaps(&usage, |layer, expert| cache.resident_slot(layer, expert).is_some(), max_swaps, tuning)
}
/// Where the source spans of the incoming experts come from: the binding, the weight cache, the CPU tier and the span
@@ -204,7 +209,7 @@ mod tests {
usage[3 * EXPERTS + e] = u;
}
let resident = |l: usize, e: usize| l == 3 && e < 2;
let swaps = choose_swaps(&usage, resident, DEFAULT_SEED_SWAPS);
let swaps = choose_swaps(&usage, resident, DEFAULT_SEED_SWAPS, AdaptTuning::default());
// (20 over 0): gain 9; (21 over 1): 2 < 6 + 1.5 stops
assert_eq!(swaps.len(), 1);
assert_eq!((swaps[0].layer, swaps[0].incoming, swaps[0].outgoing), (3, 20, 0));
@@ -50,7 +50,7 @@ fn forward_outcome<P>(pending: Result<P>, cancel: &mut impl FnMut() -> bool) ->
pub(super) fn vram_note(context: &Context<'_>, label: &str) {
// LELEKA_VRAM_LEDGER=1: the device allocations that appeared since the previous note, per call site (nothing when
// off)
leleka_cuda_driver::vram_ledger::report(label);
context.report_vram_ledger(label);
if profile::enabled() {
if let Ok((free, total)) = context.memory_info() {
// the low-water mark of the card's free VRAM over every note of this process: the number the reserve must
@@ -222,6 +222,7 @@ pub(super) fn gpu_expert_pool<'p, 'a, 'ctx>(
pcie_num,
adapt_every: tier.adapt_every,
adapt_swaps: tier.adapt_swaps as usize,
adapt_tuning: tier.adapt_tuning,
tail_rank,
pcie_locked,
})
@@ -106,7 +106,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
if seed_rows_capped(tier.seed_max_rows, counts) {
return Ok(());
}
let swaps = original_serve_seed::plan(counts, cache, max, keep);
let swaps = original_serve_seed::plan(counts, cache, (max, keep), tier.adapt_tuning);
let planned = self.config.clock.since(started);
let mut report = original_serve_seed::summarize(counts, &swaps);
let mut sources = original_serve_seed::SwapSources {
@@ -65,7 +65,7 @@ pub(crate) struct CpuPoolSettings {
}
impl MemorySettings {
pub(super) fn from_source(env: &impl EnvSource) -> Self {
pub(crate) fn from_source(env: &impl EnvSource) -> Self {
let tuning = |key: &str, default: f32| number::<f32>(env, key).filter(|v| v.is_finite()).unwrap_or(default);
Self {
route_tail_skip: trimmed_number::<u32>(env, "LELEKA_ROUTE_TAIL_SKIP"),
@@ -198,6 +198,7 @@ fn worker_config(
cancel_drain_timeout: Duration::from_secs(5),
prefix_view: Some(prefix_view),
memory_view: None,
request_metrics: Default::default(),
}
}