diff --git a/crates/leleka-runtime/src/backend.rs b/crates/leleka-runtime/src/backend.rs index 74461cc2..93b8efbb 100644 --- a/crates/leleka-runtime/src/backend.rs +++ b/crates/leleka-runtime/src/backend.rs @@ -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 /// 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 @@ -1005,6 +1024,7 @@ fn serve_load( ) -> Result<(), BackendError> { let (instance, serial, observer, execution, optimized, original) = identity_and_observer; let identity = (instance, serial); + crate::load_clock::begin(); 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 // prefills prompt tiles and verifies draft windows through chunked/grouped @@ -1128,12 +1148,14 @@ fn serve_load( } else { VerifiedGgufFile::open(&config.shard0, SHARD0).map(|shard| (shard, None)) }).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(|_| { load_failure( LoadPhase::Shard1, invalid("pinned shard 1 verification failed"), ) })?; + crate::load_clock::lap("shard1_sha256_and_index"); let artifact = Qwen4ExpArtifact::bind(shard0, shard1) .map_err(|_| load_failure(LoadPhase::Artifact, invalid("pinned model binding failed")))?; let metadata = artifact.tokenizer(); @@ -1154,6 +1176,7 @@ fn serve_load( .special_ids .get("tokenizer.ggml.eos_token_id") .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 // 262144-cell geometry (`MTP_ORIGINAL_MAX_CELLS`); it is refused, not resized, past it. if matches!(requested.inference_mode, InferenceMode::ExperimentalMtp { .. }) @@ -1207,6 +1230,7 @@ fn serve_load( _ => return Err(unsupported("experimental mode is not supported")), } .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 // every payload CRC), mapped completely, and bound before publication. 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) { 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) { return Err(load_failure( 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"))] 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))?; diff --git a/crates/leleka-runtime/src/backend_original_serve.rs b/crates/leleka-runtime/src/backend_original_serve.rs index ed6c9647..ba6757f2 100644 --- a/crates/leleka-runtime/src/backend_original_serve.rs +++ b/crates/leleka-runtime/src/backend_original_serve.rs @@ -567,6 +567,7 @@ mod runner { load_failure(LoadPhase::OriginalStack, open_error(&failure)) })?; publish_prefix_summary(&stack, shared); + crate::load_clock::lap("serve_stack_open_total"); let mut stack = Some(stack); if shared.shutdown.load(Ordering::Acquire) { if let Some(stack) = stack.take() { @@ -575,6 +576,7 @@ mod runner { return Err(load_failure(LoadPhase::Cancellation, unavailable("native load cancelled"))); } shared.ready.store(true, Ordering::Release); + crate::load_clock::lap("ready_published"); if reply.send(Ok(loaded.clone())).is_err() { shared.ready.store(false, Ordering::Release); if let Some(stack) = stack.take() { diff --git a/crates/leleka-runtime/src/lib.rs b/crates/leleka-runtime/src/lib.rs index cb9a9138..9d10765f 100644 --- a/crates/leleka-runtime/src/lib.rs +++ b/crates/leleka-runtime/src/lib.rs @@ -16,6 +16,7 @@ macro_rules! bringup_trace { } pub(crate) use bringup_trace; +pub(crate) mod load_clock; pub mod backend; pub use leleka_context::{context_policy, memory_plan, rope_scaling}; pub mod conversation; diff --git a/crates/leleka-runtime/src/load_clock.rs b/crates/leleka-runtime/src/load_clock.rs new file mode 100644 index 00000000..45fc6554 --- /dev/null +++ b/crates/leleka-runtime/src/load_clock.rs @@ -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> = 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)); + } +} diff --git a/crates/leleka-runtime/src/model_binding/qwen4exp_input.rs b/crates/leleka-runtime/src/model_binding/qwen4exp_input.rs index 4cbb51b5..d905e840 100644 --- a/crates/leleka-runtime/src/model_binding/qwen4exp_input.rs +++ b/crates/leleka-runtime/src/model_binding/qwen4exp_input.rs @@ -331,9 +331,11 @@ impl ModelBinding { mtp_root: &std::path::Path, ) -> InputResult { 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)?; weights.validate_binding(&binding)?; binding.mtp = Some(weights); + crate::load_clock::lap("mtp_pack_verify_and_bind"); Ok(binding) } pub(crate) fn expert_used_count(&self) -> u32 { diff --git a/desktop-core/src/bin/leleka-inference.rs b/desktop-core/src/bin/leleka-inference.rs index fcbaa54a..363fefd2 100644 --- a/desktop-core/src/bin/leleka-inference.rs +++ b/desktop-core/src/bin/leleka-inference.rs @@ -2,6 +2,7 @@ use leleka_runtime::backend::{ InheritedKarArchive, NativeBackendConfig, OriginalServeChoice, OriginalServeMode, OriginalServeOptions, RankedExpertProfileSource, original_serve_choice, spawn_backend, + verify_sources_only, spawn_backend_experimental_native_integer_iq3_windowed256_retained_gr, spawn_backend_experimental_optimized_windowed256, spawn_backend_experimental_optimized_windowed256_adaptive_slots, @@ -50,10 +51,13 @@ const EXECUTION_FLAGS: [&str; 7] = [ #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), Box> { - let args: Vec = std::env::args().skip(1).collect(); + let mut args: Vec = 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"] { 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(()); } @@ -140,6 +144,12 @@ async fn main() -> Result<(), Box> { kar_expert_source: None, 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 .map(evaluation_measurement::observer_adaptive_slots) .transpose()?;