perf(startup): phase timing lines (leleka-load-time) and leleka-inference --verify-only

Always-on one-line phase timings for a model load and a CPU-only verification mode that
runs the load-time source verification (shards, KAR archive) with no CUDA. Baseline for
the startup work: no behaviour change.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-24 01:14:06 +02:00
co-authored by Claude Sonnet 5.5
parent cfe0a02312
commit cceb4b4032
6 changed files with 101 additions and 2 deletions
+26
View File
@@ -274,6 +274,25 @@ pub fn spawn_backend_experimental_optimized_windowed256_streamed_spill(
}), }),
}) })
} }
/// `leleka-inference --verify-only`: the load-time verification of the sources (both shards, the KAR archive)
/// and nothing else: no CUDA, no GPU, no model state. Prints the `leleka-load-time` lines and returns.
/// It uses exactly the functions of `serve_load`, so what it measures is what a start spends.
pub fn verify_sources_only(config: NativeBackendConfig) -> Result<(), BackendError> {
crate::load_clock::begin();
VerifiedGgufFile::open(&config.shard0, SHARD0)
.map_err(|_| invalid("pinned shard 0 verification failed"))?;
crate::load_clock::lap("shard0_sha256_and_index");
VerifiedGgufFile::open(&config.shard1, SHARD1)
.map_err(|_| invalid("pinned shard 1 verification failed"))?;
crate::load_clock::lap("shard1_sha256_and_index");
if let Some(archive) = config.kar_ple_inherited.as_ref() {
crate::model_binding::qwen4exp_kar_ple::load_pinned_inherited_archive(archive)
.map_err(|_| invalid("pinned KAR archive verification failed"))?;
crate::load_clock::lap("kar_inspect_verify");
}
Ok(())
}
/// The path an operator configuration resolves to for `mode` (see `OriginalServeMode`): pure over the /// The path an operator configuration resolves to for `mode` (see `OriginalServeMode`): pure over the
/// configuration and the build's asset probe. `Auto` picks the Original path only when it can start; /// configuration and the build's asset probe. `Auto` picks the Original path only when it can start;
/// `Original` returns a precise refusal instead of falling back; `Preview` never starts it. The caller /// `Original` returns a precise refusal instead of falling back; `Preview` never starts it. The caller
@@ -1005,6 +1024,7 @@ fn serve_load(
) -> Result<(), BackendError> { ) -> Result<(), BackendError> {
let (instance, serial, observer, execution, optimized, original) = identity_and_observer; let (instance, serial, observer, execution, optimized, original) = identity_and_observer;
let identity = (instance, serial); let identity = (instance, serial);
crate::load_clock::begin();
validate_load(&model, &requested).map_err(|e| load_failure(LoadPhase::Config, e))?; validate_load(&model, &requested).map_err(|e| load_failure(LoadPhase::Config, e))?;
// Only the single-token step consults the KAR expert source. The MTP flow // Only the single-token step consults the KAR expert source. The MTP flow
// prefills prompt tiles and verifies draft windows through chunked/grouped // prefills prompt tiles and verifies draft windows through chunked/grouped
@@ -1128,12 +1148,14 @@ fn serve_load(
} else { } else {
VerifiedGgufFile::open(&config.shard0, SHARD0).map(|shard| (shard, None)) VerifiedGgufFile::open(&config.shard0, SHARD0).map(|shard| (shard, None))
}).map_err(|_| load_failure(LoadPhase::Shard0, invalid("pinned shard 0 verification failed")))?; }).map_err(|_| load_failure(LoadPhase::Shard0, invalid("pinned shard 0 verification failed")))?;
crate::load_clock::lap("shard0_sha256_and_index");
let shard1 = VerifiedGgufFile::open(&config.shard1, SHARD1).map_err(|_| { let shard1 = VerifiedGgufFile::open(&config.shard1, SHARD1).map_err(|_| {
load_failure( load_failure(
LoadPhase::Shard1, LoadPhase::Shard1,
invalid("pinned shard 1 verification failed"), invalid("pinned shard 1 verification failed"),
) )
})?; })?;
crate::load_clock::lap("shard1_sha256_and_index");
let artifact = Qwen4ExpArtifact::bind(shard0, shard1) let artifact = Qwen4ExpArtifact::bind(shard0, shard1)
.map_err(|_| load_failure(LoadPhase::Artifact, invalid("pinned model binding failed")))?; .map_err(|_| load_failure(LoadPhase::Artifact, invalid("pinned model binding failed")))?;
let metadata = artifact.tokenizer(); let metadata = artifact.tokenizer();
@@ -1154,6 +1176,7 @@ fn serve_load(
.special_ids .special_ids
.get("tokenizer.ggml.eos_token_id") .get("tokenizer.ggml.eos_token_id")
.ok_or_else(|| load_failure(LoadPhase::Eos, invalid("verified EOS is absent")))?; .ok_or_else(|| load_failure(LoadPhase::Eos, invalid("verified EOS is absent")))?;
crate::load_clock::lap("artifact_bind_and_tokenizer");
// The Original-literal MTP drafter bank (mapped host image, page table, ring) is frozen at the trained // The Original-literal MTP drafter bank (mapped host image, page table, ring) is frozen at the trained
// 262144-cell geometry (`MTP_ORIGINAL_MAX_CELLS`); it is refused, not resized, past it. // 262144-cell geometry (`MTP_ORIGINAL_MAX_CELLS`); it is refused, not resized, past it.
if matches!(requested.inference_mode, InferenceMode::ExperimentalMtp { .. }) if matches!(requested.inference_mode, InferenceMode::ExperimentalMtp { .. })
@@ -1207,6 +1230,7 @@ fn serve_load(
_ => return Err(unsupported("experimental mode is not supported")), _ => return Err(unsupported("experimental mode is not supported")),
} }
.map_err(selected_binding_failure)?; .map_err(selected_binding_failure)?;
crate::load_clock::lap("binding_kar_and_mtp_total");
// Routed experts from a pinned KAR archive: verified whole (SHA-256 and // Routed experts from a pinned KAR archive: verified whole (SHA-256 and
// every payload CRC), mapped completely, and bound before publication. // every payload CRC), mapped completely, and bound before publication.
if let Some(kar_config) = config.kar_expert_source.as_ref() { if let Some(kar_config) = config.kar_expert_source.as_ref() {
@@ -1324,6 +1348,7 @@ fn serve_load(
if original.is_some_and(|options| options.expert_source == original_serve::ExpertSource::Resident) { if original.is_some_and(|options| options.expert_source == original_serve::ExpertSource::Resident) {
crate::memory_governor::drop_file_cache(&[config.shard0.as_path(), config.shard1.as_path()]); crate::memory_governor::drop_file_cache(&[config.shard0.as_path(), config.shard1.as_path()]);
} }
crate::load_clock::lap("expert_bank_admission");
if shared.shutdown.load(Ordering::Acquire) { if shared.shutdown.load(Ordering::Acquire) {
return Err(load_failure( return Err(load_failure(
LoadPhase::Cancellation, LoadPhase::Cancellation,
@@ -1346,6 +1371,7 @@ fn serve_load(
) )
})?, })?,
); );
crate::load_clock::lap("cuda_driver_and_context");
#[cfg(all(target_os = "linux", target_arch = "x86_64"))] #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
if let Some(g) = memory_governor { if let Some(g) = memory_governor {
crate::memory_governor::check_vram(g, context.as_ref(), config.gpu_budget_bytes).map_err(|e| load_failure(LoadPhase::Context, e))?; crate::memory_governor::check_vram(g, context.as_ref(), config.gpu_budget_bytes).map_err(|e| load_failure(LoadPhase::Context, e))?;
@@ -567,6 +567,7 @@ mod runner {
load_failure(LoadPhase::OriginalStack, open_error(&failure)) load_failure(LoadPhase::OriginalStack, open_error(&failure))
})?; })?;
publish_prefix_summary(&stack, shared); publish_prefix_summary(&stack, shared);
crate::load_clock::lap("serve_stack_open_total");
let mut stack = Some(stack); let mut stack = Some(stack);
if shared.shutdown.load(Ordering::Acquire) { if shared.shutdown.load(Ordering::Acquire) {
if let Some(stack) = stack.take() { if let Some(stack) = stack.take() {
@@ -575,6 +576,7 @@ mod runner {
return Err(load_failure(LoadPhase::Cancellation, unavailable("native load cancelled"))); return Err(load_failure(LoadPhase::Cancellation, unavailable("native load cancelled")));
} }
shared.ready.store(true, Ordering::Release); shared.ready.store(true, Ordering::Release);
crate::load_clock::lap("ready_published");
if reply.send(Ok(loaded.clone())).is_err() { if reply.send(Ok(loaded.clone())).is_err() {
shared.ready.store(false, Ordering::Release); shared.ready.store(false, Ordering::Release);
if let Some(stack) = stack.take() { if let Some(stack) = stack.take() {
+1
View File
@@ -16,6 +16,7 @@ macro_rules! bringup_trace {
} }
pub(crate) use bringup_trace; pub(crate) use bringup_trace;
pub(crate) mod load_clock;
pub mod backend; pub mod backend;
pub use leleka_context::{context_policy, memory_plan, rope_scaling}; pub use leleka_context::{context_policy, memory_plan, rope_scaling};
pub mod conversation; pub mod conversation;
+58
View File
@@ -0,0 +1,58 @@
//! Wall-clock phases of a model load, printed on stderr as one line each:
//! `leleka-load-time phase=NAME seconds=S total=T`. Always on (a handful of lines per load, no secrets,
//! no paths); `leleka` and the holder jobs read them to find where a cold start goes.
//!
//! `lap` times a phase of the loading thread since the previous lap; `span` times a phase that ran on
//! another thread (the parallel verifications), so overlapping phases can be told apart in the log.
use std::{
io::Write,
sync::Mutex,
time::{Duration, Instant},
};
struct Clock {
start: Instant,
last: Instant,
}
static CLOCK: Mutex<Option<Clock>> = Mutex::new(None);
fn emit(phase: &str, seconds: Duration, total: Duration) {
let _ = writeln!(
std::io::stderr().lock(),
"leleka-load-time phase={phase} seconds={:.2} total={:.2}",
seconds.as_secs_f64(),
total.as_secs_f64()
);
}
/// Start the clock of one load.
pub(crate) fn begin() {
let now = Instant::now();
if let Ok(mut clock) = CLOCK.lock() {
*clock = Some(Clock { start: now, last: now });
}
}
/// The phase of the calling thread that ended now, started at the previous lap.
pub(crate) fn lap(phase: &str) {
let now = Instant::now();
if let Ok(mut guard) = CLOCK.lock()
&& let Some(clock) = guard.as_mut()
{
let seconds = now.duration_since(clock.last);
let total = now.duration_since(clock.start);
clock.last = now;
emit(phase, seconds, total);
}
}
/// A phase that started at `started` (possibly on another thread) and ended now. Does not move the lap mark.
pub(crate) fn span(phase: &str, started: Instant) {
let now = Instant::now();
if let Ok(guard) = CLOCK.lock()
&& let Some(clock) = guard.as_ref()
{
emit(phase, now.duration_since(started), now.duration_since(clock.start));
}
}
@@ -331,9 +331,11 @@ impl ModelBinding {
mtp_root: &std::path::Path, mtp_root: &std::path::Path,
) -> InputResult<Self> { ) -> InputResult<Self> {
let mut binding = Self::from_artifact_with_inherited_kar_ple(artifact, source)?; let mut binding = Self::from_artifact_with_inherited_kar_ple(artifact, source)?;
crate::load_clock::lap("kar_inspect_verify_and_bind");
let weights = MtpWeights::load_pinned(&binding, mtp_source, mtp_root)?; let weights = MtpWeights::load_pinned(&binding, mtp_source, mtp_root)?;
weights.validate_binding(&binding)?; weights.validate_binding(&binding)?;
binding.mtp = Some(weights); binding.mtp = Some(weights);
crate::load_clock::lap("mtp_pack_verify_and_bind");
Ok(binding) Ok(binding)
} }
pub(crate) fn expert_used_count(&self) -> u32 { pub(crate) fn expert_used_count(&self) -> u32 {
+12 -2
View File
@@ -2,6 +2,7 @@
use leleka_runtime::backend::{ use leleka_runtime::backend::{
InheritedKarArchive, NativeBackendConfig, OriginalServeChoice, OriginalServeMode, InheritedKarArchive, NativeBackendConfig, OriginalServeChoice, OriginalServeMode,
OriginalServeOptions, RankedExpertProfileSource, original_serve_choice, spawn_backend, OriginalServeOptions, RankedExpertProfileSource, original_serve_choice, spawn_backend,
verify_sources_only,
spawn_backend_experimental_native_integer_iq3_windowed256_retained_gr, spawn_backend_experimental_native_integer_iq3_windowed256_retained_gr,
spawn_backend_experimental_optimized_windowed256, spawn_backend_experimental_optimized_windowed256,
spawn_backend_experimental_optimized_windowed256_adaptive_slots, spawn_backend_experimental_optimized_windowed256_adaptive_slots,
@@ -50,10 +51,13 @@ const EXECUTION_FLAGS: [&str; 7] = [
#[tokio::main(flavor = "current_thread")] #[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> { async fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = std::env::args().skip(1).collect(); let mut args: Vec<String> = std::env::args().skip(1).collect();
// `--verify-only`: run the load-time source verification (shards, KAR archive) and exit; no CUDA is touched.
let verify_only = args.iter().any(|arg| arg == "--verify-only");
args.retain(|arg| arg != "--verify-only");
if args.as_slice() == ["--help"] { if args.as_slice() == ["--help"] {
println!( println!(
"leleka-inference --listen IP:PORT --token-env NAME --shard0 PATH --shard1 PATH --gpu ORDINAL --gpu-budget BYTES --context-tokens COUNT [--kar-archive PATH --kar-staging PATH | --kar-archive-fd N --kar-provenance PATH | --kar-archive-file PATH --kar-provenance PATH (read-only regular file, no write bits, owned by the caller: the low-RAM form of the pinned archive)] [--mtp-pack PATH --mtp-staging PATH] [--experimental-native-integer-iq3-windowed256-retained-gr | --experimental-optimized-windowed256-mtp [--ranked-expert-profile PATH --expert-profile-sha256 DIGEST] | --experimental-optimized-windowed256-mtp-queued-owners --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-streamed-spill --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-retained-scratch --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-strata-adaptive-slots --ranked-expert-profile PATH --expert-profile-sha256 DIGEST] [--public-evaluation-output /PRIVATE/measurements.jsonl (adaptive slots only; LELEKA_PUBLIC_EVALUATION=yes and LELEKA_EVALUATION_NONCE required)] [--backend-mode auto|original|preview (default auto; an --experimental-* flag selects preview unless the mode is given)] [--original-prefill-capacity 256..8192] [--mtp-rt-dir PATH] [--spec-min-p 0..1] [--kv int8 (fp16|q4_0|k8v4 are refused)] [--kv-resident CELLS (default 32768, min 20480, 0 = all in VRAM)] [--prompt-cache N (conversation checkpoints, default 6 as in the Original, 0 = off)] [--prompt-cache-every N] [--prompt-cache-root N] [--turn-token ID (negative = none)] [--prefix-cache-mib auto|N|0 (cross-session prefix cache in host RAM, replaces the conversation cache; auto = a share of the memory available at start; default off)] [--prefix-cache-block TOKENS (block and chunk-grid size, a multiple of 256; default the prefill capacity)] [--expert-source resident|mapped (default resident: a ~50 GB RAM copy of the routed experts; mapped: read-only mappings of shard 0, the low-RAM laptop form)]" "leleka-inference --listen IP:PORT --token-env NAME --shard0 PATH --shard1 PATH --gpu ORDINAL --gpu-budget BYTES --context-tokens COUNT [--kar-archive PATH --kar-staging PATH | --kar-archive-fd N --kar-provenance PATH | --kar-archive-file PATH --kar-provenance PATH (read-only regular file, no write bits, owned by the caller: the low-RAM form of the pinned archive)] [--mtp-pack PATH --mtp-staging PATH] [--experimental-native-integer-iq3-windowed256-retained-gr | --experimental-optimized-windowed256-mtp [--ranked-expert-profile PATH --expert-profile-sha256 DIGEST] | --experimental-optimized-windowed256-mtp-queued-owners --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-streamed-spill --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-retained-scratch --ranked-expert-profile PATH --expert-profile-sha256 DIGEST | --experimental-optimized-windowed256-mtp-strata-adaptive-slots --ranked-expert-profile PATH --expert-profile-sha256 DIGEST] [--public-evaluation-output /PRIVATE/measurements.jsonl (adaptive slots only; LELEKA_PUBLIC_EVALUATION=yes and LELEKA_EVALUATION_NONCE required)] [--backend-mode auto|original|preview (default auto; an --experimental-* flag selects preview unless the mode is given)] [--original-prefill-capacity 256..8192] [--mtp-rt-dir PATH] [--spec-min-p 0..1] [--kv int8 (fp16|q4_0|k8v4 are refused)] [--kv-resident CELLS (default 32768, min 20480, 0 = all in VRAM)] [--prompt-cache N (conversation checkpoints, default 6 as in the Original, 0 = off)] [--prompt-cache-every N] [--prompt-cache-root N] [--turn-token ID (negative = none)] [--prefix-cache-mib auto|N|0 (cross-session prefix cache in host RAM, replaces the conversation cache; auto = a share of the memory available at start; default off)] [--prefix-cache-block TOKENS (block and chunk-grid size, a multiple of 256; default the prefill capacity)] [--verify-only (verify shards and archive, print timings, exit)] [--expert-source resident|mapped (default resident: a ~50 GB RAM copy of the routed experts; mapped: read-only mappings of shard 0, the low-RAM laptop form)]"
); );
return Ok(()); return Ok(());
} }
@@ -140,6 +144,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
kar_expert_source: None, kar_expert_source: None,
experimental: Default::default(), experimental: Default::default(),
}; };
if verify_only {
return verify_sources_only(config).map_err(|error| {
eprintln!("leleka-inference: {}", error.message);
"source_verification_failed".into()
});
}
let observer = public_evaluation_output let observer = public_evaluation_output
.map(evaluation_measurement::observer_adaptive_slots) .map(evaluation_measurement::observer_adaptive_slots)
.transpose()?; .transpose()?;