Merge branch 'claude/debt-hot-low' into HEAD

# Conflicts:
#	architecture-baseline.json
#	architecture.json
#	docs/architecture/tech-debt.md
This commit is contained in:
Pavlo Ratushnyi
2026-11-23 01:27:17 +01:00
60 changed files with 441 additions and 263 deletions
+1 -8
View File
@@ -3,18 +3,11 @@
"violations": [],
"oversize": {},
"source": {
"dyn-trait:leleka-cuda-driver": 45,
"dyn-trait:leleka-engine-qwen35-cuda": 9,
"env-read:leleka-control-plane": 3,
"glob-super-import:leleka-cuda-driver": 2,
"instant-now:leleka-control-plane": 15,
"instant-now:leleka-cuda-driver": 25,
"instant-now:leleka-engine-host": 4,
"instant-now:leleka-native-cpu-expert": 27,
"path-include:leleka-cuda-driver": 1,
"process-global:leleka-control-plane": 2,
"process-global:leleka-cuda-driver": 96,
"process-global:leleka-native-cpu-expert": 27
"process-global:leleka-control-plane": 2
},
"mechanical_names": []
}
+72 -3
View File
@@ -63,8 +63,8 @@
{"crate": "leleka-gptoss", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: it returns the operator's switches as typed values"},
{"crate": "leleka-model-format", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: it returns the operator's switches as typed values"},
{"crate": "leleka-obs", "file": "src/level.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: LELEKA_LOG* parsed once into Settings, and the request-log path"},
{"crate": "leleka-cuda-driver", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate; call sites still parse the text they ask for (typed switches: EnvSwitch in leleka-cuda-model, in progress on claude/debt-hot-low)"},
{"crate": "leleka-native-cpu-expert", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate; call sites still parse the text they ask for (CPU expert pool: hot path, in progress on claude/debt-hot-low)"},
{"crate": "leleka-cuda-driver", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: the 22 on/off switches are EnvSwitch entries of its catalogue (leleka_cuda_model::env_switch); the option parsers (stager, stream-all, chain flags, sm120 switches) still call the pass-through var/var_os with their own parsing, which a typed Settings value of the driver would replace"},
{"crate": "leleka-native-cpu-expert", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate (CPU expert pool, a hot path): call sites still parse the text they ask for with the pass-through var/var_os; a typed Settings value captured when the pool starts would replace them"},
{"crate": "leleka-cpu-kernels", "file": "src/dispatch.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: ISA_ENV is parsed by Isa::from_request into the selected instruction set"},
{"crate": "leleka-libc-shim", "file": "src/cuda_trace/trace_state.rs", "ratchet": "env-read", "reason": "Windows interposer (FFI): the CUDA call tracer reads its own LELEKA_BRINGUP_TRACE switches and must not depend on other crates"},
{"crate": "leleka-libc-shim", "file": "src/lib.rs", "ratchet": "env-read", "reason": "Windows interposer (FFI): the DLL search directories come from the process environment before any other crate can load"},
@@ -215,7 +215,76 @@
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session/chunk/qwen_chunk_txn/qwen_chunk_txn_begin.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session/chunk/verify/qwen_chunk_txn/qwen_chunk_txn_begin_verification.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session/chunk/verify/verified_target_prefix.rs", "ratchet": "process-global", "reason": "reads the serving context (cells) that the engine configures once at start-up (leleka-cuda-model::serving_context, an immutable bound afterwards); threading it through every position check is the S13/S14 injection"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session/qwen_session.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"}
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session/qwen_session.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"},
{"crate": "leleka-cuda-driver", "file": "src/compute_drain.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: stall span of one timed drain, reported by the prefill stall trace"},
{"crate": "leleka-cuda-driver", "file": "src/mmq/resident/original_group/copy_ring/chunk_stream/chunk_issuing.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: span of one chunk issue, summed into the copy-ring profile"},
{"crate": "leleka-cuda-driver", "file": "src/mmq/resident/original_group/copy_ring/original_mmq_copy_schedule/stream_start.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: start of the copy-ring stream, read once per stream for the profile"},
{"crate": "leleka-cuda-driver", "file": "src/native_prompt_device/original_prompt_device/run_phases.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: span of one prompt phase, reported by the prefill profile"},
{"crate": "leleka-cuda-driver", "file": "src/original_file_expert_source/original_file_expert_source_operations/file_expert_source_prefetch.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: span of one expert-file prefetch, summed into the stager profile"},
{"crate": "leleka-cuda-driver", "file": "src/original_file_expert_source/original_file_expert_source_operations/file_expert_source_blobs.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: spans of the expert-file stages, summed into the stager profile"},
{"crate": "leleka-cuda-driver", "file": "src/original_gpu_schedule/original_gpu_graph.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: span of one graph launch, reported by the graph profile"},
{"crate": "leleka-cuda-driver", "file": "src/original_gpu_schedule/original_gpu_stream.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: span of one stream synchronisation, reported by the stream profile"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/diag.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: wait loop of the live-verifier release diagnostic, bounded by its own timeout"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/schedule/verifier_commit_window_lifecycle.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: span of one commit window, reported by the verifier profile"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/schedule/verifier_logits_diagnostics_close.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: span of one logits readout, reported by the verifier profile"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/schedule/window_phases.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: spans of the window phases, reported by the verifier profile"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/share_window_modules/physical.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: span of the physical bank open, reported by the verifier profile"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_prompt_index/prompt_device/resident_device/original_qsa_prompt_device.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: timestamp of the last prompt-device use, read by the idle-trim policy of the device"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_prompt_index/resident_program/qsa_prompt_index_workspace.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: span of one resident index program run, reported by the prefill profile"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_prompt_kv/mapped_journal/original_qsa_mapped_prefix/qsa_mapped_journal_arena.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: spans of the mapped-journal append and resolve, reported by the prefill profile"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_dispatch/gdn_native_batch/prompt_device/original_gdn_prompt_device/original_gdn_prompt_device_drain.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: spans of the GDN prompt drain, reported by the prefill profile"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_bench_frontend/cpu_blob.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: benchmark harness timers around the blob kernels, printed by the bench"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_general_pool/epoch_scheduling.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: per-epoch timers of the CPU expert pool (hot loop), summed into the pool trace; one reading per phase"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_general_pool/expert_pool.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: per-call phase timers of the CPU expert pool (hot loop), summed into the pool trace; one reading per phase"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_general_pool/expert_pool_split_multi_run.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: per-run phase timers of the split multi-expert run (hot loop), summed into the pool trace"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_general_pool/phase_handoff.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: wait and quantize lap timers of the pool (hot loop), summed into the pool trace"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_pool/epoch_scheduling.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: the pool's one monotonic reading, wrapped so every epoch timestamp comes from it (hot loop)"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_pool/native_pool.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: per-thread start stamps of the native pool for its timing mode (hot loop)"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_pool/trace.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: origin of the pool trace timeline, read once when tracing starts"},
{"crate": "leleka-cuda-driver", "file": "src/mmq/resident/original_group.rs", "ratchet": "dyn-trait", "reason": "the group borrows its arena view (GroupArena) from the caller for one run; a test seam with a mock arena"},
{"crate": "leleka-cuda-driver", "file": "src/mmq/resident/original_group/copy_ring.rs", "ratchet": "dyn-trait", "reason": "the copy ring borrows its arena view (RingArena) from the caller for one run; a test seam with a mock arena"},
{"crate": "leleka-cuda-driver", "file": "src/mtp_dense_kv/original_int8/prefill/scalar/full_forward/full_round/put.rs", "ratchet": "dyn-trait", "reason": "the put step takes the copy and the fence of one round as callbacks, so the same code runs over the real streams and a recording test double"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/diag.rs", "ratchet": "dyn-trait", "reason": "the live-verifier release diagnostic writes an optional note to any writer (stderr, a file or a buffer in the tests)"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/gr.rs", "ratchet": "dyn-trait", "reason": "the window planner reads weight addresses through the ArenaMap seam (the device arena in production, an in-memory table in the tests); the planner structs keep it for one window plan, which is built at capture time, not per token"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/moe/plan_expert_groups.rs", "ratchet": "dyn-trait", "reason": "the window planner reads weight addresses through the ArenaMap seam (the device arena in production, an in-memory table in the tests); the planner structs keep it for one window plan, which is built at capture time, not per token"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/moe/plan_f32_to_bf16.rs", "ratchet": "dyn-trait", "reason": "the window planner reads weight addresses through the ArenaMap seam (the device arena in production, an in-memory table in the tests); the planner structs keep it for one window plan, which is built at capture time, not per token"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/planner.rs", "ratchet": "dyn-trait", "reason": "the window planner reads weight addresses through the ArenaMap seam (the device arena in production, an in-memory table in the tests); the planner structs keep it for one window plan, which is built at capture time, not per token"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/qsa.rs", "ratchet": "dyn-trait", "reason": "the window planner reads weight addresses through the ArenaMap seam (the device arena in production, an in-memory table in the tests); the planner structs keep it for one window plan, which is built at capture time, not per token"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/qsa/qsa_window/qsa_window_query_key_paths.rs", "ratchet": "dyn-trait", "reason": "the window planner reads weight addresses through the ArenaMap seam (the device arena in production, an in-memory table in the tests); the planner structs keep it for one window plan, which is built at capture time, not per token"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_dispatch/gdn_native_batch.rs", "ratchet": "dyn-trait", "reason": "the batch owner holds its GEMM provider (cuBLAS-backed in production, a host stand-in in the tests) as a trait object for the life of one batch; it is a port, chosen when the owner is opened"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_dispatch/gdn_native_batch/context.rs", "ratchet": "dyn-trait", "reason": "the batch owner holds its GEMM provider (cuBLAS-backed in production, a host stand-in in the tests) as a trait object for the life of one batch; it is a port, chosen when the owner is opened"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_dispatch/moe_prefill_batch.rs", "ratchet": "dyn-trait", "reason": "the batch owner holds its GEMM provider (cuBLAS-backed in production, a host stand-in in the tests) as a trait object for the life of one batch; it is a port, chosen when the owner is opened"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_dispatch/moe_prefill_batch/moe_prefill_batch_lifecycle.rs", "ratchet": "dyn-trait", "reason": "the batch owner holds its GEMM provider (cuBLAS-backed in production, a host stand-in in the tests) as a trait object for the life of one batch; it is a port, chosen when the owner is opened"},
{"crate": "leleka-cuda-driver", "file": "src/arch_ptx/stream_k_off.rs", "ratchet": "process-global", "reason": "marker-file polls of the A/B controls (LELEKA_MMQ_NO_STREAMK_FILE, LELEKA_CHUNK_DRAIN_FILE): the paths are operator setting parsed once from the environment and cached for the process, the poll instants are rate-limit state"},
{"crate": "leleka-cuda-driver", "file": "src/context.rs", "ratchet": "process-global", "reason": "LELEKA_PREFILL_DEFER_FREE_MIB: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-cuda-driver", "file": "src/mmq/asset.rs", "ratchet": "process-global", "reason": "the verdict of the immutable MMQ artifact check, computed once"},
{"crate": "leleka-cuda-driver", "file": "src/mmq/resident/original_group/copy_ring/host_stage/verify_enabled.rs", "ratchet": "process-global", "reason": "LELEKA_STAGE_PRIORITY: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-cuda-driver", "file": "src/mmq/resident/original_group/copy_ring/skip_expert_dma.rs", "ratchet": "process-global", "reason": "marker-file polls of the ring A/B controls: the paths are operator setting parsed once from the environment and cached for the process, the start instant is rate-limit state"},
{"crate": "leleka-cuda-driver", "file": "src/original_gpu_schedule/abi/platform/library_drop.rs", "ratchet": "process-global", "reason": "LELEKA_CB_WARMUP: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-cuda-driver", "file": "src/original_gpu_schedule/transport.rs", "ratchet": "process-global", "reason": "LELEKA_TEST_WINDOW_INSTANTIATE_OOM_AT, a test hook: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/chain.rs", "ratchet": "process-global", "reason": "the chain switches parsed by ChainFlags::parse: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/gpu_plan/cpu_sink_publish_gpu_plan.rs", "ratchet": "process-global", "reason": "the DMA options of the CPU sink: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/moe/pcie_fast_kernel.rs", "ratchet": "process-global", "reason": "LELEKA_PCIE_KERNEL and LELEKA_PCIE_GRID: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-cuda-driver", "file": "src/prefill_stage.rs", "ratchet": "process-global", "reason": "the usability of the kh recurrence on this device: immutable result of a probe or proof of a sealed image, computed once and cached"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_index_ffi.rs", "ratchet": "process-global", "reason": "the RoPE ABI of the loaded index module: immutable result of a probe or proof of a sealed image, computed once and cached"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_prompt_attention/qsa_prompt_attention_drop.rs", "ratchet": "process-global", "reason": "LELEKA_PREFILL_GUARD_GRID: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_prompt_kv/resident_transport.rs", "ratchet": "process-global", "reason": "LELEKA_PREFILL_QSA_PREFETCH: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_prompt_resolver.rs", "ratchet": "process-global", "reason": "the resolver ABI of the loaded module: immutable result of a probe or proof of a sealed image, computed once and cached"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_ffi/asset_admission.rs", "ratchet": "process-global", "reason": "per-operation memo of the PTX proof: immutable result of a probe or proof of a sealed image, computed once and cached"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_ffi/n_types.rs", "ratchet": "process-global", "reason": "the table of PTX proof memos, one cell per operation: immutable result of a probe or proof of a sealed image, computed once and cached"},
{"crate": "leleka-cuda-driver", "file": "src/vram_ledger.rs", "ratchet": "process-global", "reason": "the process-wide VRAM ledger (LELEKA_VRAM_LEDGER): a diagnostic singleton fed by every allocation site"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_bench_frontend.rs", "ratchet": "process-global", "reason": "FFI: `static mut stdout` is libc's C stream, declared in an extern block"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_expert_layout.rs", "ratchet": "process-global", "reason": "the process-wide expert layout the pool threads read; it is set at load time by the engine"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_general_pool/job_default.rs", "ratchet": "process-global", "reason": "the origin instant of the pool's job timestamps"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_general_pool.rs", "ratchet": "process-global", "reason": "the hook that releases the GPU waits, installed once by the engine (a function pointer)"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_ggml_native.rs", "ratchet": "process-global", "reason": "the admission verdict of the native ggml kernels on this CPU, computed once"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_iq/dot_multi512.rs", "ratchet": "process-global", "reason": "LELEKA_IQ_SINGLE: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_iq/u16.rs", "ratchet": "process-global", "reason": "LELEKA_IQ_MULTI: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_legacy/set_oracle_q8_zero.rs", "ratchet": "process-global", "reason": "STRATA_CPU_YMM: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_native_general/group_dot_bytes_policy.rs", "ratchet": "process-global", "reason": "STRATA_KQ256: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_pool/epoch_scheduling.rs", "ratchet": "process-global", "reason": "LELEKA_POOL_TASKS_PER_THREAD: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_quant.rs", "ratchet": "process-global", "reason": "LELEKA_Q8K: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_simd.rs", "ratchet": "process-global", "reason": "the CPU feature dispatch and the STRATA_* switches parsed from it: operator setting parsed once from the environment and cached for the process"}
],
"source_patterns": [
{"id": "env-read", "regex": "\\benv::var(_os)?\\(", "why": "configuration must be parsed once into a Settings struct (S13), not read all over the code"},
@@ -14,9 +14,8 @@ use super::imp;
/// exactly the one of the sealed code.
pub(crate) fn stream_k_off() -> bool {
use std::sync::atomic::Ordering::Relaxed;
static FIXED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
static PATHS: std::sync::OnceLock<[Option<std::path::PathBuf>; 2]> = std::sync::OnceLock::new();
let fixed = *FIXED.get_or_init(|| crate::settings::var_os("LELEKA_MMQ_NO_STREAMK").is_some_and(|v| v != "0"));
let fixed = crate::settings::MMQ_NO_STREAMK.get();
let paths = PATHS.get_or_init(|| {
["LELEKA_MMQ_NO_STREAMK_FILE", "LELEKA_MMQ_STREAMK_FILE"]
.map(|name| crate::settings::var_os(name).map(std::path::PathBuf::from))
@@ -69,12 +68,11 @@ pub(crate) fn forced_sms(real: u32) -> u32 {
/// decode before it) can overlap the next.
pub(crate) fn chunk_drain() -> bool {
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed};
static FIXED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
static PATH: std::sync::OnceLock<Option<std::path::PathBuf>> = std::sync::OnceLock::new();
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
static LAST_MS: AtomicU64 = AtomicU64::new(u64::MAX);
static PRESENT: AtomicBool = AtomicBool::new(false);
if *FIXED.get_or_init(|| crate::settings::var_os("LELEKA_CHUNK_DRAIN").is_some_and(|v| v != "0")) {
if crate::settings::CHUNK_DRAIN.get() {
return true;
}
let Some(path) =
+4 -6
View File
@@ -96,9 +96,8 @@ pub(crate) fn note_alloc(what: &str, bytes: usize) {
if background() == 0 {
return;
}
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
static SEEN: AtomicUsize = AtomicUsize::new(0);
if !*ON.get_or_init(|| crate::settings::var_os("LELEKA_PREFILL_ALLOC_TRACE").is_some_and(|v| v == "1")) {
if !crate::settings::PREFILL_ALLOC_TRACE.get() {
return;
}
if SEEN.fetch_add(1, Ordering::Relaxed) < 64 {
@@ -123,6 +122,7 @@ pub(crate) fn timed<T>(kind: usize, f: impl FnOnce() -> T) -> T {
if background() == 0 {
return f();
}
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let started = std::time::Instant::now();
let out = f();
let took = started.elapsed();
@@ -141,8 +141,7 @@ pub(crate) fn timed<T>(kind: usize, f: impl FnOnce() -> T) -> T {
/// LELEKA_PREFILL_STALL_TRACE=1: every blocking call over 2 ms (first 40 per chunk) with its callers, and a
/// per-call-site histogram of the host-to-device / device-to-host / memset / device-to-device calls
fn stall_trace() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| crate::settings::var_os("LELEKA_PREFILL_STALL_TRACE").is_some_and(|v| v == "1"))
crate::settings::PREFILL_STALL_TRACE.get()
}
/// The driver and runtime frames of a backtrace taken in `timed`, past `timed` itself.
fn stall_frames(trace: &str) -> String {
@@ -190,12 +189,11 @@ pub fn set_zero_memset(on: bool) {
/// Whether all-zero host-to-device uploads become device memsets while a chunk stream is in flight (the upload is a
/// copy-engine transfer that waits behind the expert copies; the memset is not).
pub(crate) fn zero_memset() -> bool {
static ENV: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
background() != 0
&& match ZERO_MEMSET.load(Ordering::Relaxed) {
0 => false,
1 => true,
_ => *ENV.get_or_init(|| crate::settings::var_os("LELEKA_PREFILL_ZERO_MEMSET").is_none_or(|v| v != "0")),
_ => crate::settings::PREFILL_ZERO_MEMSET.get(),
}
}
+1 -2
View File
@@ -59,8 +59,7 @@ fn refuse_if_set(row: &[u8], stage: usize, labels: &[&'static str]) -> Result<()
/// Read once: the switch. Off by default (experimental mode).
pub(crate) fn enabled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| crate::settings::var("LELEKA_PREFILL_DEFER_GUARDS").map_or(true, |v| v != "0"))
crate::settings::PREFILL_DEFER_GUARDS.get()
}
/// One deferred check: the status words (`bytes` of them at `status`), their `stride`, the streams to order after the
+2
View File
@@ -240,6 +240,8 @@ mod native_parity_ffi;
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
mod native_head;
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
mod native_head_dispatch;
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
mod original_file_expert_source;
@@ -158,6 +158,5 @@ impl MappedExpertBank<'_> {
}
/// `LELEKA_PREFILL_ALIGNED_COPY=0` turns the page-aligned expert copies off (the A/B switch; default on).
pub(crate) fn aligned_copy_enabled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| crate::settings::var("LELEKA_PREFILL_ALIGNED_COPY").map_or(true, |v| v != "0"))
crate::settings::PREFILL_ALIGNED_COPY.get()
}
@@ -146,6 +146,7 @@ use kind::kind;
use kind::layout;
use kind::shared;
mod copy_ring_layer;
mod copy_ring_projection;
mod mmq_workspace;
mod original_mmq_layer;
mod original_mmq_output;
@@ -36,6 +36,7 @@ impl Core {
if self.depth == 0 {
return self.issue_until(k + 1);
}
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let started = Instant::now();
while self.issued.load(Ordering::Acquire) <= k {
if self.failed.load(Ordering::Acquire) || started.elapsed() > Duration::from_secs(60) {
@@ -7,8 +7,7 @@ use super::{Arc, Job, NON_FINITE, NORMAL_PRIORITY, Ordering, Shared, thread};
/// Bring-up: `LELEKA_BRINGUP_TRACE` and `LELEKA_STAGE_VERIFY` compare every staged buffer with its source when its DMA
/// is released.
pub(super) fn verify_enabled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| crate::bringup_trace_enabled() && crate::settings::var_os("LELEKA_STAGE_VERIFY").is_some())
crate::bringup_trace_enabled() && crate::settings::STAGE_VERIFY.get()
}
/// Memory priority for the page-cache pages of the experts a layer's helpers read (Windows only,
@@ -163,6 +163,7 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> {
) {
// from here the compute path's drains stop waiting for the copy stream (end_prompt_stream restores them)
crate::compute_drain::set_background(copy);
// Measurement timer, not decision logic (instant-now exception in architecture.json).
self.stream_started = Some(std::time::Instant::now());
self.stream = Some(stream);
self.stream_bank = Some(Rc::clone(bank));
@@ -9,8 +9,7 @@ use super::{
/// `LELEKA_PREFILL_DIAG_SKIP_EXPERT_DMA=1` (EXPERIMENTAL, diagnostic, wrong outputs): the copy ring issues no
/// expert copies, so a profile shows the ring's compute alone. Never set in serving.
pub(super) fn skip_expert_dma() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| crate::settings::var_os("LELEKA_PREFILL_DIAG_SKIP_EXPERT_DMA").is_some_and(|v| v == "1"))
crate::settings::PREFILL_DIAG_SKIP_EXPERT_DMA.get()
}
#[cfg(not(all(
feature = "cuda-driver",
@@ -62,12 +61,11 @@ impl RingArena for crate::OriginalDeviceGrRead<'_, '_, '_> {
}
pub(super) fn serialize_ring(which: Drain) -> bool {
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed};
static FIXED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
static PATHS: std::sync::OnceLock<[Option<std::path::PathBuf>; 3]> = std::sync::OnceLock::new();
static LAST_MS: AtomicU64 = AtomicU64::new(u64::MAX);
static PRESENT: [AtomicBool; 3] = [const { AtomicBool::new(false) }; 3];
if *FIXED.get_or_init(|| crate::settings::var_os("LELEKA_RING_SERIALIZE").is_some_and(|v| v != "0")) {
if crate::settings::RING_SERIALIZE.get() {
return true;
}
let paths = PATHS.get_or_init(|| {
@@ -1,6 +1,11 @@
//! Copy-ring execution of an `OriginalMmqLayer`: stage, gather, enqueue, drain (a glob import: at the line limit).
//! Copy-ring execution of an `OriginalMmqLayer`: preflight, stage-ahead, gather and the enqueue of each group's
//! kernels while the ring streams the experts in (projection launches and status words: `copy_ring_projection`).
use super::*;
use crate::combine;
use super::{
D, GU, Error, GatherDest, GroupArena, H, HQ, MmqFormat, OriginalMmqCopySchedule, OriginalMmqLayer,
ProjectSlots, ProjectSpec, Result, RingExperts, TMP, WD, WG, XQ, copy_ring, ffi, layout,
};
impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> {
/// Execute the actual ascending expert layer through Original's copy ring.
@@ -256,144 +261,4 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> {
ffi::MmqResidentArguments::finite(q, q_flag, 1, (ql.payload / 144) as u32, (128 * 144) as u32),
))
}
/// Maps the finite/Q8 witness words of every group to the first refusal.
fn check_ring_statuses(flags: &[u8]) -> Result<()> {
for group in flags.chunks_exact(16) {
let words = group.as_chunks::<4>().0;
Self::check_group_status([0, 1, 2, 3].map(|i| u32::from_le_bytes(words[i])))?;
}
Ok(())
}
fn check_group_status([gu, h, q, down]: [u32; 4]) -> Result<()> {
Self::check_gate_up_status(gu, h)?;
Self::check_q8_down_status(q, down)
}
fn check_gate_up_status(gu: u32, h: u32) -> Result<()> {
match gu {
0 => {}
1 | 3 => return Err(Error::NonFiniteMmqOutput("Gate")),
2 => return Err(Error::NonFiniteMmqOutput("Up")),
_ => return Err(Error::InvalidDriverValue("Original GU finite witness")),
}
match h {
0 => {}
1 => return Err(Error::NonFiniteMmqOutput("SwiGLU")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
Ok(())
}
fn check_q8_down_status(q: u32, down: u32) -> Result<()> {
match q {
0 => {}
1 | 3 => return Err(Error::InvalidQ8Activation),
2 => return Err(Error::InvalidDriverValue("Original grouped Q8 tail")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
match down {
0 => {}
1 => return Err(Error::NonFiniteMmqOutput("Down")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
Ok(())
}
pub(super) fn enqueue_ring_project(
&self,
ring: &mut copy_ring::Ring<'_, 'ctx>,
spec: ProjectSpec,
slots: ProjectSlots,
) -> Result<()> {
let ProjectSpec { format, down, width } = spec;
let ProjectSlots { weights, packed, out } = slots;
let b = self.bank()?;
let experts = self.staged as u32;
let nr = self.bounds[self.next + self.staged] - self.bounds[self.next];
let rows = if down { 2560 } else { 1280 };
let tokens = if down { nr } else { self.total };
let l = layout(format, rows, tokens, width)?;
let functions = Self::ring_project_functions(b, format, width)?;
let maxr = self.counts[self.next..self.next + self.staged].iter().copied().max();
let maxr = maxr.ok_or(Error::InvalidProjectionShape)?;
let (grid, needs_fix) = self.ring_project_grid(&l, rows, (experts, maxr, width))?;
let hs = self.ring_project_handles(&l, (weights, packed, out), (down, tokens, experts))?;
let tmp = self.ring_project_tmp(needs_fix, grid, width)?;
Self::ring_project_commands(
ring,
functions,
(l, grid),
(hs, tmp),
ffi::MmqGroupShape { experts, max_rows: maxr, width },
)
}
/// The projection and fixup function of `format` at tile `width`.
fn ring_project_functions(
b: &OriginalGroupBank<'ctx>,
format: MmqFormat,
width: u32,
) -> Result<(ffi::FunctionHandle, ffi::FunctionHandle)> {
let fi = format_index(format)?;
let ti = WIDTHS.iter().position(|j| *j == width).ok_or(Error::UnsupportedProjection)?;
let f = b.functions[fi][ti].ok_or(Error::UnsupportedProjection)?;
Ok((f, b.fixups[fi][ti].ok_or(Error::UnsupportedProjection)?))
}
/// `(grid, needs fixup)`: complete tiles, or the stream-k grid when the tile count fills the SMs poorly.
fn ring_project_grid(&self, l: &Layout, rows: u32, (experts, maxr, width): (u32, u32, u32)) -> Result<(u32, bool)> {
let ntx = maxr.div_ceil(width);
let tiles =
(rows / 128).checked_mul(ntx).and_then(|n| n.checked_mul(experts)).ok_or(Error::InvalidProjectionShape)?;
if tiles.checked_mul(l.columns / l.qk).is_none_or(|n| n >= 1 << 30) {
return Err(Error::InvalidProjectionShape);
}
let sms = self.workspace.experiment.as_ref().ok_or(Error::ContextPoisoned)?.sms;
let efficiency = 100 * tiles / (sms * tiles.div_ceil(sms));
let grid = if efficiency >= 90 || crate::arch_ptx::stream_k_off() { tiles } else { sms };
Ok((grid, !tiles.is_multiple_of(grid)))
}
/// `[weights, packed, output, ids, bounds]` handles of one projection.
fn ring_project_handles(
&self,
l: &Layout,
(weights, packed, out): (usize, usize, usize),
(down, tokens, experts): (bool, u32, u32),
) -> Result<[ffi::BufferHandle; 5]> {
let wh = self.handle(weights, 0, l.raw_weight * experts as usize + 4096, 4)?;
let ph = self.handle(packed, 0, l.packed, 16)?;
let oh = self.handle(out, 0, l.output, 4)?;
let ids = self.handle(IDENTITY, 0, tokens as usize * 4, 4)?;
let offset = if down { self.counts.len() + 1 + (self.next / 16) * 17 } else { self.next };
let bounds = self.handle(BOUNDS, offset * 4, (experts as usize + 1) * 4, 4)?;
Ok([wh, ph, oh, ids, bounds])
}
/// The stream-k fixup scratch when the grid does not divide the tile count.
fn ring_project_tmp(&self, needs_fix: bool, grid: u32, width: u32) -> Result<Option<ffi::BufferHandle>> {
if !needs_fix {
return Ok(None);
}
Ok(Some(self.handle(TMP, 0, grid as usize * width as usize * 128 * 4, 4)?))
}
fn ring_project_commands(
ring: &mut copy_ring::Ring<'_, 'ctx>,
(f, fix): (ffi::FunctionHandle, ffi::FunctionHandle),
(l, grid): (Layout, u32),
([wh, ph, oh, ids, bounds], tmp): ([ffi::BufferHandle; 5], Option<ffi::BufferHandle>),
shape: ffi::MmqGroupShape,
) -> Result<()> {
use crate::ffi::original_enqueue::Command;
let routing = ffi::MmqGroupRouting { ids, bounds };
let buffers = ffi::MmqGroupBuffers { weights: wh, packed: ph, output: oh, tmp };
ring.enqueue(Command::Project(f, l, grid, ffi::MmqArguments::original_group(buffers, routing, l, shape)))?;
if let Some(tmp) = tmp {
let args = ffi::MmqFixupArguments::original_group(routing, oh, tmp, l, shape);
ring.enqueue(Command::Fixup(fix, grid, args))?;
}
Ok(())
}
}
@@ -0,0 +1,149 @@
//! The projection launches of the copy ring (MMQ over the staged group) and the status words they publish: the
//! launch geometry of one projection, and the mapping of the finite and Q8 witness words to the first refusal.
use super::{
BOUNDS, Error, IDENTITY, Layout, MmqFormat, OriginalGroupBank, OriginalMmqLayer, ProjectSlots, ProjectSpec,
Result, TMP, WIDTHS, copy_ring, ffi, format_index, layout,
};
impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> {
/// Maps the finite/Q8 witness words of every group to the first refusal.
pub(super) fn check_ring_statuses(flags: &[u8]) -> Result<()> {
for group in flags.chunks_exact(16) {
let words = group.as_chunks::<4>().0;
Self::check_group_status([0, 1, 2, 3].map(|i| u32::from_le_bytes(words[i])))?;
}
Ok(())
}
fn check_group_status([gu, h, q, down]: [u32; 4]) -> Result<()> {
Self::check_gate_up_status(gu, h)?;
Self::check_q8_down_status(q, down)
}
fn check_gate_up_status(gu: u32, h: u32) -> Result<()> {
match gu {
0 => {}
1 | 3 => return Err(Error::NonFiniteMmqOutput("Gate")),
2 => return Err(Error::NonFiniteMmqOutput("Up")),
_ => return Err(Error::InvalidDriverValue("Original GU finite witness")),
}
match h {
0 => {}
1 => return Err(Error::NonFiniteMmqOutput("SwiGLU")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
Ok(())
}
fn check_q8_down_status(q: u32, down: u32) -> Result<()> {
match q {
0 => {}
1 | 3 => return Err(Error::InvalidQ8Activation),
2 => return Err(Error::InvalidDriverValue("Original grouped Q8 tail")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
match down {
0 => {}
1 => return Err(Error::NonFiniteMmqOutput("Down")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
Ok(())
}
pub(super) fn enqueue_ring_project(
&self,
ring: &mut copy_ring::Ring<'_, 'ctx>,
spec: ProjectSpec,
slots: ProjectSlots,
) -> Result<()> {
let ProjectSpec { format, down, width } = spec;
let ProjectSlots { weights, packed, out } = slots;
let b = self.bank()?;
let experts = self.staged as u32;
let nr = self.bounds[self.next + self.staged] - self.bounds[self.next];
let rows = if down { 2560 } else { 1280 };
let tokens = if down { nr } else { self.total };
let l = layout(format, rows, tokens, width)?;
let functions = Self::ring_project_functions(b, format, width)?;
let maxr = self.counts[self.next..self.next + self.staged].iter().copied().max();
let maxr = maxr.ok_or(Error::InvalidProjectionShape)?;
let (grid, needs_fix) = self.ring_project_grid(&l, rows, (experts, maxr, width))?;
let hs = self.ring_project_handles(&l, (weights, packed, out), (down, tokens, experts))?;
let tmp = self.ring_project_tmp(needs_fix, grid, width)?;
Self::ring_project_commands(
ring,
functions,
(l, grid),
(hs, tmp),
ffi::MmqGroupShape { experts, max_rows: maxr, width },
)
}
/// The projection and fixup function of `format` at tile `width`.
fn ring_project_functions(
b: &OriginalGroupBank<'ctx>,
format: MmqFormat,
width: u32,
) -> Result<(ffi::FunctionHandle, ffi::FunctionHandle)> {
let fi = format_index(format)?;
let ti = WIDTHS.iter().position(|j| *j == width).ok_or(Error::UnsupportedProjection)?;
let f = b.functions[fi][ti].ok_or(Error::UnsupportedProjection)?;
Ok((f, b.fixups[fi][ti].ok_or(Error::UnsupportedProjection)?))
}
/// `(grid, needs fixup)`: complete tiles, or the stream-k grid when the tile count fills the SMs poorly.
fn ring_project_grid(&self, l: &Layout, rows: u32, (experts, maxr, width): (u32, u32, u32)) -> Result<(u32, bool)> {
let ntx = maxr.div_ceil(width);
let tiles =
(rows / 128).checked_mul(ntx).and_then(|n| n.checked_mul(experts)).ok_or(Error::InvalidProjectionShape)?;
if tiles.checked_mul(l.columns / l.qk).is_none_or(|n| n >= 1 << 30) {
return Err(Error::InvalidProjectionShape);
}
let sms = self.workspace.experiment.as_ref().ok_or(Error::ContextPoisoned)?.sms;
let efficiency = 100 * tiles / (sms * tiles.div_ceil(sms));
let grid = if efficiency >= 90 || crate::arch_ptx::stream_k_off() { tiles } else { sms };
Ok((grid, !tiles.is_multiple_of(grid)))
}
/// `[weights, packed, output, ids, bounds]` handles of one projection.
fn ring_project_handles(
&self,
l: &Layout,
(weights, packed, out): (usize, usize, usize),
(down, tokens, experts): (bool, u32, u32),
) -> Result<[ffi::BufferHandle; 5]> {
let wh = self.handle(weights, 0, l.raw_weight * experts as usize + 4096, 4)?;
let ph = self.handle(packed, 0, l.packed, 16)?;
let oh = self.handle(out, 0, l.output, 4)?;
let ids = self.handle(IDENTITY, 0, tokens as usize * 4, 4)?;
let offset = if down { self.counts.len() + 1 + (self.next / 16) * 17 } else { self.next };
let bounds = self.handle(BOUNDS, offset * 4, (experts as usize + 1) * 4, 4)?;
Ok([wh, ph, oh, ids, bounds])
}
/// The stream-k fixup scratch when the grid does not divide the tile count.
fn ring_project_tmp(&self, needs_fix: bool, grid: u32, width: u32) -> Result<Option<ffi::BufferHandle>> {
if !needs_fix {
return Ok(None);
}
Ok(Some(self.handle(TMP, 0, grid as usize * width as usize * 128 * 4, 4)?))
}
fn ring_project_commands(
ring: &mut copy_ring::Ring<'_, 'ctx>,
(f, fix): (ffi::FunctionHandle, ffi::FunctionHandle),
(l, grid): (Layout, u32),
([wh, ph, oh, ids, bounds], tmp): ([ffi::BufferHandle; 5], Option<ffi::BufferHandle>),
shape: ffi::MmqGroupShape,
) -> Result<()> {
use crate::ffi::original_enqueue::Command;
let routing = ffi::MmqGroupRouting { ids, bounds };
let buffers = ffi::MmqGroupBuffers { weights: wh, packed: ph, output: oh, tmp };
ring.enqueue(Command::Project(f, l, grid, ffi::MmqArguments::original_group(buffers, routing, l, shape)))?;
if let Some(tmp) = tmp {
let args = ffi::MmqFixupArguments::original_group(routing, oh, tmp, l, shape);
ring.enqueue(Command::Fixup(fix, grid, args))?;
}
Ok(())
}
}
@@ -15,8 +15,7 @@ impl MtpInt8OwnerId {
/// `LELEKA_MTP_SNAPSHOT_MEMO=off`: scan every page of a snapshot on each `validate_snapshot` (the earlier behaviour;
/// the A/B control).
pub(super) fn snapshot_memo() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| !crate::settings::var("LELEKA_MTP_SNAPSHOT_MEMO").is_ok_and(|v| v == "off" || v == "0"))
crate::settings::MTP_SNAPSHOT_MEMO.get()
}
impl Pages {
pub(super) fn empty() -> Self {
@@ -17,7 +17,6 @@ mod full_abi;
use full_abi::{Arg as F, Arguments as FA, Module as FM};
#[allow(unsafe_code)]
mod full_mapped;
mod head_dispatch;
mod symbols;
use crate::mtp_dense_kv::original_int8::abi::LaunchShape;
use crate::native_head::OriginalMtpNativeEmbedding;
@@ -4,7 +4,7 @@
use super::{
CHUNKS, DeviceBuffer, DraftKvPolicy, Error, F, ForwardPrefix, FullCommand, LaunchShape, NativeHeadDispatch,
OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, Result, SCRATCH_FLOATS, SamplerParams,
TAIL_FLAGS, daily_mtp, fixed_entry, head_dispatch, mmvf_block, push, symbols, validate_scalar_prefix,
TAIL_FLAGS, daily_mtp, fixed_entry, mmvf_block, push, symbols, validate_scalar_prefix,
};
/// Device addresses of one matrix-vector product launch: the weight matrix, the input vector and the output vector.
@@ -1,10 +1,11 @@
//! Small command builders of the draft step tail: finiteness and Q8 flag checks, input quantization, the
//! quantized and float matrix-vector launches, and the fused MLP GR kernel launch with its 114 by-value words.
use crate::native_head_dispatch::head_dispatch;
use super::{
Error, F, ForwardPrefix, FullCommand, LaunchShape, MatVecBuffers, MatVecShape, NativeHeadDispatch,
OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, Result, TAIL_FLAGS, fixed_entry,
head_dispatch, mmvf_block, push,
mmvf_block, push,
};
impl OriginalMtpFullForward<'_> {
@@ -49,7 +50,7 @@ impl OriginalMtpFullForward<'_> {
) -> Result<()> {
let MatVecBuffers { weights: w, input: q, output: y } = buffers;
let MatVecShape { columns: n, rows: out } = shape;
let (name, grid, block, _) = head_dispatch::head_dispatch(8, n, out, 1, NativeHeadDispatch::default())?;
let (name, grid, block, _) = head_dispatch(8, n, out, 1, NativeHeadDispatch::default())?;
push(
v,
13,
@@ -1,9 +1,10 @@
//! The MoE and tail blocks of `OriginalMtpFullForward::plan` (STRA-338), recorded in the order of the former single
//! function: router, experts, shared expert and combine; then the final GR, the head and the sampler.
use crate::native_head_dispatch::head_dispatch;
use super::{
DeviceBuffer, Error, F, ForwardPrefix, FullCommand, LaunchShape, MatVecBuffers, MatVecShape,
OriginalMtpFullForward, OriginalMtpFullPolicy, Result, SamplerParams, fixed_entry, head_dispatch, push, symbols,
OriginalMtpFullForward, OriginalMtpFullPolicy, Result, SamplerParams, fixed_entry, push, symbols,
};
/// What the coupled sampler needs besides the logits.
@@ -242,7 +243,7 @@ impl OriginalMtpFullForward<'_> {
}
fn plan_head(&self, v: &mut Vec<FullCommand>, p: &ForwardPrefix<'_, '_>) -> Result<()> {
let w = &self.inner.weights;
let (name, grid, block, iq) = head_dispatch::head_dispatch(w.head_kind, 2560, w.vocab, 1, w.dispatch)?;
let (name, grid, block, iq) = head_dispatch(w.head_kind, 2560, w.vocab, 1, w.dispatch)?;
let asset = if iq { 14 } else { 13 };
let index = fixed_entry(asset, name)?;
push(v, asset, index, LaunchShape::new(grid, block, 0), self.head_args(p.q, iq)?)?;
@@ -42,8 +42,7 @@ pub(super) fn push(
/// byte-identical to the Original's by the probe) instead of the Original's chunk kernel and
/// `chain_qsa_decode_merge_n`. sm_120 only.
pub(super) fn daily_mtp() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| crate::settings::var("LELEKA_SM120_ATTN_DAILY_MTP").is_ok_and(|v| v == "1"))
crate::settings::SM120_ATTN_DAILY_MTP.get()
}
/// `LELEKA_CHAIN` selects a group that launches from the chain module inside the MTP draft program.
pub(super) fn chain_mtp_assets() -> bool {
@@ -1,5 +1,7 @@
use super::*;
use crate::NativeHeadDispatch;
//! Kernel names and launch geometry of the native and IQ head projections of the MTP draft and of the window verifier:
//! one table shared by the two (it used to be compiled twice, once under each of them).
use crate::{Error, NativeHeadDispatch, Result};
/// Kernel names of the IQ head kernels: `[old, c1, c2, c4, c8]` (kind 7 has the old kernel only).
const IQ_NAMES: [(u32, &[&str]); 7] = [
@@ -344,7 +346,7 @@ fn native_head_rows(small: bool, upstream: bool) -> usize {
}
}
pub(super) fn head_dispatch(
pub(crate) fn head_dispatch(
kind: u32,
n: usize,
v: usize,
@@ -100,6 +100,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
if op.is_err() {
break;
}
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let started = std::time::Instant::now();
let (launched, label) = self.launch_one(blas, cmd, timed)?;
op = launched;
@@ -76,6 +76,7 @@ impl<'ctx> OriginalFileExpertSource<'ctx> {
Ok(v)
}
pub(in super::super) fn fill_stage(&mut self, v: usize, k: usize) -> Result<()> {
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let t = Instant::now();
let operation = (|| {
let parts = self.parts(k / EXPERTS, k % EXPERTS)?;
@@ -178,6 +178,7 @@ fn fetch_worker(jobs: &[abi::Copy], next: &AtomicUsize, result: &[Mutex<Option<(
if i >= jobs.len() {
break;
}
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let t = Instant::now();
let r = jobs[i].run();
if let Ok(mut out) = result[i].lock() {
@@ -201,6 +201,7 @@ impl<R: OriginalGraphResources> OriginalGraphFlight<'_, '_, R> {
/// Registry's wait polls actual driver completion on a real monotonic deadline,
/// with64 pauses between polls. Timeout keeps the graph pending; it never means ready.
pub fn wait_ms(mut self, timeout: Duration) -> Result<OriginalWait> {
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let start = Instant::now();
loop {
if self.query()? {
@@ -95,6 +95,7 @@ impl<'ctx> OriginalGpuStream<'ctx> {
resources: R,
body: impl FnOnce(&mut OriginalCapture<'_, 'ctx>, &mut R) -> Result<()>,
) -> Result<OriginalGpuGraph<'ctx, R>> {
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let started = std::time::Instant::now();
let (h, mut g) = self.open_graph(policy, resources)?;
if let Err(primary) = self.record_graph(h, &mut g, policy, body) {
@@ -134,8 +134,7 @@ pub(crate) fn with_flags<R>(flags: ChainFlags, f: impl FnOnce() -> R) -> R {
/// The hyper-connection up projection with 8 columns per block (320 blocks, 5.7 us at 4 rows against 7.7 us for 16
/// columns and 8.9 us for the Original's, job 9c1); `LELEKA_CHAIN_UP8=0` selects the 16-column shape.
pub(crate) fn up8() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| crate::settings::var("LELEKA_CHAIN_UP8").map_or(true, |v| v != "0"))
crate::settings::CHAIN_UP8.get()
}
/// The hyper-connection down projection tiled over rows AND tokens (8 rows x 2 tokens per block, `ceil(T / 2)` x 41
@@ -148,8 +147,7 @@ pub(crate) fn down_tiled() -> bool {
1 => return true,
_ => {}
}
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| crate::settings::var("LELEKA_CHAIN_DOWN").map_or(true, |v| v != "w8"))
crate::settings::CHAIN_DOWN.get()
}
/// Per-arm override of the down-projection shape for paired A/B arms inside one process (-1: none, 0: the 8-row x
@@ -70,7 +70,7 @@ pub struct OriginalVerifyDiag {
}
impl OriginalVerifyDiag {
/// Same line as `Verifier::diag` (#31).
pub fn write_to(&self, f: &mut dyn Write) -> std::io::Result<()> {
pub fn write_to(&self, f: &mut (impl Write + ?Sized)) -> std::io::Result<()> {
writeln!(
f,
" verify window{}: {} tokens at position {}, host at layer step {}; the GPU rang {}; \
@@ -158,7 +158,7 @@ pub fn original_verify_diagnostics() -> Vec<OriginalVerifyDiag> {
registry().iter().map(|s| snapshot(s)).collect()
}
/// `diag_active_verifier` for all live verifiers.
pub fn write_original_verify_diagnostics(f: &mut dyn Write) -> std::io::Result<()> {
pub fn write_original_verify_diagnostics(f: &mut (impl Write + ?Sized)) -> std::io::Result<()> {
for d in original_verify_diagnostics() {
d.write_to(f)?;
}
@@ -175,6 +175,7 @@ pub fn original_verify_live_count() -> usize {
/// from the serve watchdog thread while the owner thread is blocked in a sync.
pub fn original_verify_release_live(timeout: Duration, note: Option<&mut dyn Write>) -> bool {
let live = raise_all_released();
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let start = Instant::now();
let drained = wait_drained(&live, start, timeout);
if let Some(f) = note {
@@ -210,7 +211,7 @@ fn wait_drained(live: &[Arc<Shared>], start: Instant, timeout: Duration) -> bool
drained
}
fn note_released(f: &mut dyn Write, drained: bool, start: Instant, timeout: Duration) {
fn note_released(f: &mut (impl Write + ?Sized), drained: bool, start: Instant, timeout: Duration) {
let _ = if drained {
writeln!(
f,
@@ -39,8 +39,7 @@ pub(crate) static DRAFT_COMMIT_QSA: AssetSpec = AssetSpec {
/// `LELEKA_DRAFT_FUSED_COMMIT=on|1`: record the commit graph with the fused kernels. Read once per process (it
/// decides which kernels the commit graph records).
pub(crate) fn fused_commit() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| fused_commit_from(crate::settings::var("LELEKA_DRAFT_FUSED_COMMIT").ok().as_deref()))
crate::settings::DRAFT_FUSED_COMMIT.get()
}
pub(crate) fn fused_commit_from(value: Option<&str>) -> bool {
value.is_some_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "on" | "1" | "yes" | "true"))
@@ -137,7 +137,7 @@ pub(super) fn check_rows(geo: &OriginalVerifyGeometry, rows: Rows) -> Result<()>
}
Ok(())
}
pub(super) fn row_span(arena: &dyn ArenaMap, name: &str, row: usize, row_bytes: usize) -> Result<u64> {
pub(super) fn row_span(arena: &(impl ArenaMap + ?Sized), name: &str, row: usize, row_bytes: usize) -> Result<u64> {
arena.span(name, row * row_bytes, row_bytes)
}
pub(super) fn refuse(producer: &'static str) -> Error {
@@ -47,7 +47,7 @@ pub(super) fn hc_read_of_rows(
/// The per-row argument spans of the window rows; the attention half reads `inj2` and writes `inj`, the FFN the
/// reverse.
pub(super) fn hc_read_rows(arena: &dyn ArenaMap, half: HcHalf, rows: Rows) -> Result<Vec<RowArgs>> {
pub(super) fn hc_read_rows(arena: &(impl ArenaMap + ?Sized), half: HcHalf, rows: Rows) -> Result<Vec<RowArgs>> {
let (inj_prev_name, inj_out_name) = match half {
HcHalf::Attention => ("inj2", "inj"),
HcHalf::Ffn => ("inj", "inj2"),
@@ -184,7 +184,12 @@ pub(super) fn hc_read_up(chain_gr: bool, full: Vec<u64>) -> Result<Launch> {
// ------------------------------------------------------------------------------------------------
/// `gr_write(Rt(t), bo_ + t*N, inj2_ + t*HC, gs, Rt(t), cs)` for one window row: `native_gr_post`.
pub(super) fn write_row(arena: &dyn ArenaMap, cfg: &GrConfig, row: usize, producer: &'static str) -> Result<Launch> {
pub(super) fn write_row(
arena: &(impl ArenaMap + ?Sized),
cfg: &GrConfig,
row: usize,
producer: &'static str,
) -> Result<Launch> {
if !cfg.native_mmvf {
return Err(refuse(producer));
}
@@ -201,7 +206,7 @@ pub(super) fn write_row(arena: &dyn ArenaMap, cfg: &GrConfig, row: usize, produc
/// `for t in [tb, te): gr_write(Rt(t), bo_+t*N, inj2_+t*HC, gs, Rt(t), cs)` of the last layer.
pub(crate) fn plan_final_write(
arena: &dyn ArenaMap,
arena: &(impl ArenaMap + ?Sized),
geo: &OriginalVerifyGeometry,
cfg: &GrConfig,
rows: Rows,
@@ -253,7 +258,7 @@ pub(crate) fn plan_head_mix(
/// The five launches of one head row `t`: norm, down gemv, down-silu, up gemv, final pre-mix.
fn head_mix_row(
arena: &dyn ArenaMap,
arena: &(impl ArenaMap + ?Sized),
geo: &OriginalVerifyGeometry,
w: &HeadAddrs,
mixed_base: u64,
@@ -91,7 +91,13 @@ impl PleScratch {
}
/// key = ple_key @ emb (BF16 MMVF, or q8_1 quantize + MMVQ for a native key).
fn plan_ple_key(arena: &dyn ArenaMap, ple: &PleConfig, a: &PleAddrs, emb: u64, out: &mut Vec<Launch>) -> Result<()> {
fn plan_ple_key(
arena: &(impl ArenaMap + ?Sized),
ple: &PleConfig,
a: &PleAddrs,
emb: u64,
out: &mut Vec<Launch>,
) -> Result<()> {
let key = PleScratch::at(a.scratch).key;
match a.key {
PleKey::Bf16(w) => out.push(plan_bf16_gemv(
@@ -123,7 +123,7 @@ pub fn top_k(row: &[f32], k: usize) -> Vec<(i32, f64)> {
/// One tab-separated line, same columns as Original:
/// `pos target logprob top top_logprob hit extra_logprob target_without_extra [id:logprob ...]`.
pub fn write_row_line(out: &mut dyn Write, r: &RowLogprob, topk: &[(i32, f64)]) -> std::io::Result<()> {
pub fn write_row_line(out: &mut (impl Write + ?Sized), r: &RowLogprob, topk: &[(i32, f64)]) -> std::io::Result<()> {
write!(
out,
"{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}",
@@ -159,7 +159,7 @@ pub struct LogprobReadout {
/// The whole readout over `rows` consecutive logit rows of width `vocab`.
pub fn write_window_logprobs(
out: &mut dyn Write,
out: &mut (impl Write + ?Sized),
rows: LogitRows<'_>,
targets: &[i32],
first_position: i64,
@@ -52,8 +52,7 @@ mod enabled {
/// runs over a whole verify group's CPU output (rows x top-10 x hidden floats) once per layer on the decode
/// critical path. `LELEKA_SINK_SCAN=legacy` (A/B arm) keeps the element-wise `any` scan.
pub(crate) fn all_finite(rows: &[f32]) -> bool {
static LEGACY: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if *LEGACY.get_or_init(|| crate::settings::var("LELEKA_SINK_SCAN").as_deref() == Ok("legacy")) {
if crate::settings::SINK_SCAN_LEGACY.get() {
return !rows.iter().any(|v| !v.is_finite());
}
let mut bad = 0u32;
@@ -234,14 +234,25 @@ pub(super) fn check_rows(g: &OriginalVerifyGeometry, rows: Rows) -> Result<usize
Ok(rows.len())
}
/// `n_elems` consecutive `elem`-byte items of a span starting at item `first`.
pub(super) fn items(arena: &dyn ArenaMap, name: &str, first: usize, count: usize, elem: usize) -> Result<u64> {
pub(super) fn items(
arena: &(impl ArenaMap + ?Sized),
name: &str,
first: usize,
count: usize,
elem: usize,
) -> Result<u64> {
arena.span(name, first * elem, count * elem)
}
pub(super) fn f32s(arena: &dyn ArenaMap, name: &str, first: usize, count: usize) -> Result<u64> {
pub(super) fn f32s(arena: &(impl ArenaMap + ?Sized), name: &str, first: usize, count: usize) -> Result<u64> {
items(arena, name, first, count, 4)
}
/// Word `word` of group `group`'s device plan copy (`plan_ + group * (plan_i32_ + 16)`).
pub(super) fn plan_word(arena: &dyn ArenaMap, g: &OriginalVerifyGeometry, group: usize, word: usize) -> Result<u64> {
pub(super) fn plan_word(
arena: &(impl ArenaMap + ?Sized),
g: &OriginalVerifyGeometry,
group: usize,
word: usize,
) -> Result<u64> {
let layout = PlanLayout::new(g.max_t * g.k);
if group > 1 || word >= layout.words {
return Err(Error::InvalidQwenShape);
@@ -18,8 +18,6 @@ use crate::native_head::native_head_row_bytes;
use crate::{Context, DeviceRef};
use crate::{Error, NativeHeadDispatch, Result};
#[path = "../mtp_dense_kv/original_int8/prefill/scalar/full_forward/head_dispatch.rs"]
mod head_dispatch;
#[cfg(test)]
#[path = "../original_verify_window_proj/tests.rs"]
@@ -4,7 +4,7 @@
use super::{
A, ArenaMap, AssetSpec, BF16, BF16_ENTRIES, Error, GdnProjectionAddrs, HEAD_IQ, HEAD_NATIVE, Launch, LaunchExtent,
NativeHeadDispatch, NativeWeight, OriginalVerifyGeometry, Projection, QsaProjectionAddrs, QuantSource, Result,
Rows, gdn_index, head_dispatch, native_head_row_bytes, qsa_index,
Rows, gdn_index, native_head_row_bytes, qsa_index,
};
/// Bytes of one q8_1-quantized activation row of `n_in` elements (`n_in/32` blocks of 36).
@@ -102,7 +102,7 @@ pub(crate) fn plan_mmvq(
) -> Result<Launch> {
let MmvqExtents { n_in, n_out, rows } = extents;
let (n_in32, n_out32) = mmvq_extents(n_in, n_out, rows)?;
let (entry, grid, block, iq) = head_dispatch::head_dispatch(w.ty, n_in, n_out, rows, dispatch)?;
let (entry, grid, block, iq) = crate::native_head_dispatch::head_dispatch(w.ty, n_in, n_out, rows, dispatch)?;
let mut args = vec![A::P(w.data)];
if iq {
args.push(A::U64(native_head_row_bytes(w.ty, n_in)? as u64));
@@ -196,7 +196,7 @@ pub(crate) fn quant_source_width(geo: &OriginalVerifyGeometry, source: QuantSour
/// `native_quantize_q8_1(src + tb*width, xq_, width, n)`: the group's rows are quantized into the
/// START of `xq_` (every group overwrites it; the MMVQs that follow read it from row 0).
pub(crate) fn plan_window_quantize(
arena: &dyn ArenaMap,
arena: &(impl ArenaMap + ?Sized),
geo: &OriginalVerifyGeometry,
source: QuantSource,
rows: Rows,
@@ -272,7 +272,7 @@ pub(super) fn projection_first_row(
/// `native_mmvq(type, w, xq_, y + tb*rows_stride, n_in, n_out, n)`: the weight reads the q8_1 rows the
/// preceding `plan_window_quantize` left at the start of `xq_`.
pub(crate) fn plan_window_mmvq(
arena: &dyn ArenaMap,
arena: &(impl ArenaMap + ?Sized),
geo: &OriginalVerifyGeometry,
site: WindowProjectionSite,
weight: &NativeWeight,
@@ -9,8 +9,7 @@ use super::{
/// `STRATA_COMMIT_SYNC`, read once (it sat on the per-round commit path).
pub(super) fn commit_sync_forced() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| crate::settings::var_os("STRATA_COMMIT_SYNC").is_some())
crate::settings::STRATA_COMMIT_SYNC.get()
}
impl OriginalVerifyCpuSink<'_, '_> {
pub fn with_output<R>(&mut self, produce: impl FnOnce(&mut [f32]) -> Result<R>) -> Result<R> {
@@ -163,7 +163,7 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
pub fn diag(&self) -> Option<OriginalVerifyDiag> {
self.registration.as_ref().map(diag::Registration::snapshot)
}
pub fn write_diag(&self, f: &mut dyn Write) -> std::io::Result<()> {
pub fn write_diag(&self, f: &mut (impl Write + ?Sized)) -> std::io::Result<()> {
match self.diag() {
Some(d) => d.write_to(f),
None => Ok(()),
@@ -184,6 +184,7 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
r.mark_released()
}
let mut result = self.bank.as_mut().map_or(Ok(()), OriginalVerifyBank::release_gpu_waits);
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let start = Instant::now();
let mut drained = true;
for stream in [self.compute.as_ref(), self.copy.as_ref()].into_iter().flatten() {
@@ -75,10 +75,16 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
}
/// `Verifier::window_logprobs` with `STRATA_LOGPOS_TOPK` from the environment: one line per row of
/// the last completed window. `targets[t]` is the token at `first_position + t + 1`.
pub fn window_logprobs(&self, targets: &[i32], extra_id: i32, out: &mut dyn Write) -> Result<()> {
pub fn window_logprobs(&self, targets: &[i32], extra_id: i32, out: &mut (impl Write + ?Sized)) -> Result<()> {
self.window_logprobs_topk(targets, extra_id, logpos_topk_from_environment(), out)
}
pub fn window_logprobs_topk(&self, targets: &[i32], extra_id: i32, topk: usize, out: &mut dyn Write) -> Result<()> {
pub fn window_logprobs_topk(
&self,
targets: &[i32],
extra_id: i32,
topk: usize,
out: &mut (impl Write + ?Sized),
) -> Result<()> {
self.with_completed_logits(|logits, rows, vocabulary, first| {
if targets.is_empty() || targets.len() > rows {
return Err(Error::InvalidQwenShape);
@@ -131,6 +137,7 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
r.mark_released()
}
let mut result = self.bank.as_mut().map_or(Ok(()), OriginalVerifyBank::release_gpu_waits);
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let start = Instant::now();
// Original #267 bounded release: no blocking wait on a spin kernel forever.
for s in [self.compute.as_ref(), self.copy.as_ref()].into_iter().flatten() {
@@ -117,6 +117,7 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
let layer = k / groups;
let group = k % groups;
let want = window_plan::ring(layer, groups, group);
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let start = Instant::now();
if let Some(r) = &self.registration {
r.layer_step(want)
@@ -30,6 +30,7 @@ impl Physical<'_> {
/// unioned). Every sealed module is loaded; the first unsealed one fails closed AFTER that, by name.
pub(in super::super) fn ensure_window_assets(&self, specs: &[&'static kernels::AssetSpec]) -> Result<()> {
self.validate(self.context)?;
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let started = std::time::Instant::now();
let (ready, unsealed) = self.select_ready(group_specs(specs))?;
if ready.is_empty() {
@@ -9,8 +9,7 @@ use super::{
/// `LELEKA_WINDOW_MODULE_CACHE=off`: every verifier bank loads its window modules again (A/B control).
pub(in super::super) fn share_window_modules() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| !crate::settings::var("LELEKA_WINDOW_MODULE_CACHE").is_ok_and(|v| v == "off" || v == "0"))
crate::settings::WINDOW_MODULE_CACHE.get()
}
pub(in super::super) fn admission(c: &Context<'_>, n: usize) -> Result<()> {
let need = n.checked_add(RESERVE).ok_or(Error::InvalidSize)?;
+5 -17
View File
@@ -41,13 +41,9 @@ pub(crate) const GDN_REC: usize = 16;
pub(crate) const GDN_REC_KH: usize = 17;
pub(crate) const GDN_OUT_NORM_Y16: usize = 18;
fn switch(name: &'static str, cell: &'static std::sync::OnceLock<bool>) -> bool {
*cell.get_or_init(|| crate::settings::var(name).map_or(true, |v| v != "0"))
}
/// `LELEKA_PREFILL_FUSED_SCANS=0`: the separate finite-guard kernels of the GR read/inject and the GDN chain (A/B arm).
pub(crate) fn fused_scans() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
switch("LELEKA_PREFILL_FUSED_SCANS", &ON)
crate::settings::PREFILL_FUSED_SCANS.get()
}
/// `LELEKA_PREFILL_FAST_REC=1` (EXPERIMENTAL, off by default): the two-barrier recurrence kernel. Bit-identical to the
/// original on the 3080 probe but not faster there, so it is not the default until a 5090 A/B shows a gain.
@@ -57,8 +53,7 @@ pub(crate) fn fast_rec() -> bool {
2 => return true,
_ => {}
}
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| crate::settings::var("LELEKA_PREFILL_FAST_REC").is_ok_and(|v| v == "1"))
crate::settings::PREFILL_FAST_REC.get()
}
/// Per-arm override of the prompt recurrence for paired A/B passes in one process (-1: none, 0: the sealed Original
/// kernel, 1: the kh kernel, 2: the two-barrier kernel).
@@ -75,8 +70,7 @@ pub(crate) fn gdn_nostore() -> bool {
1 => return true,
_ => {}
}
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| crate::settings::var("LELEKA_PREFILL_GDN_NOSTORE").map_or(GDN_NOSTORE_DEFAULT, |v| v != "0"))
crate::settings::PREFILL_GDN_NOSTORE.get()
}
/// Default of `LELEKA_PREFILL_GDN_NOSTORE` (flipped after its identity gate).
pub(crate) const GDN_NOSTORE_DEFAULT: bool = true;
@@ -95,12 +89,7 @@ pub(crate) fn gdn_kh_requested() -> bool {
0 | 2 => return false,
_ => {}
}
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| match crate::settings::var("LELEKA_PREFILL_GDN_KH").ok().as_deref() {
Some("1") => true,
Some(_) => false,
None => GDN_KH_DEFAULT,
})
crate::settings::PREFILL_GDN_KH.get()
}
/// Default of `LELEKA_PREFILL_GDN_KH` (flipped only after its gates, see the plan).
pub(crate) const GDN_KH_DEFAULT: bool = false;
@@ -129,8 +118,7 @@ pub(crate) fn gdn_kh_usable(context: &crate::Context<'_>) -> bool {
}
/// `LELEKA_PREFILL_FAST_DEQUANT=0`: the original one-thread-per-32-values GDN weight dequantization (A/B arm).
pub(crate) fn fast_dequant() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
switch("LELEKA_PREFILL_FAST_DEQUANT", &ON)
crate::settings::PREFILL_FAST_DEQUANT.get()
}
/// Frozen by `scripts/gpu-bringup/seal_pins.py` after `compile_assets.py` (extra-seal-plan.json, group prefill-stage).
pub(crate) const PIN: PtxPin = PtxPin {
+2 -8
View File
@@ -44,8 +44,7 @@ pub(crate) fn enabled() -> bool {
1 => return true,
_ => {}
}
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| crate::settings::var("LELEKA_QSA_LATE").map_or(true, |v| v != "0"))
crate::settings::QSA_LATE.get()
}
/// Row 2.5: which top-k kernel a prompt tile of `tile_reach` indexer blocks takes. `LELEKA_QSA_TOPK=fast` keeps
/// `leleka_qsa_topk_fast` (256 threads); `wide` takes the 1,024-thread kernel from `TOPK_WIDE_MIN_BLOCKS` on (Strata
@@ -60,15 +59,10 @@ pub fn set_topk_override(value: i8) {
/// Default of `LELEKA_QSA_TOPK` (flipped after its R gate).
pub(crate) const TOPK_DEFAULT_WIDE: bool = true;
pub(crate) fn topk_entry(tile_reach: usize) -> (usize, u32) {
static WIDE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let wide = match TOPK_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
0 => false,
1 => true,
_ => *WIDE.get_or_init(|| match crate::settings::var("LELEKA_QSA_TOPK").ok().as_deref() {
Some("wide") => true,
Some(_) => false,
None => TOPK_DEFAULT_WIDE,
}),
_ => crate::settings::QSA_TOPK_WIDE.get(),
};
static SAID: std::sync::Once = std::sync::Once::new();
SAID.call_once(|| {
@@ -35,6 +35,7 @@ struct ResidentRollback<'a, 'ctx> {
pub(super) fn lap(mark: &mut Option<std::time::Instant>, index: usize, label: &'static str) {
if let Some(at) = mark {
crate::command_profile::add("qsa", index, label, at.elapsed());
// Measurement timer, not decision logic (instant-now exception in architecture.json).
*at = std::time::Instant::now();
}
}
@@ -124,6 +124,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
let mut late = LateQueue { launches: &mut plan.late, next: 0 };
for (i, (shape, args)) in plan.commands.iter_mut().enumerate() {
self.run_late(blas, &mut late, i, timed)?;
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let started = std::time::Instant::now();
module.launch(*shape, blas.stream(), args)?;
if timed {
@@ -19,6 +19,7 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> {
) -> Result<OriginalQsaMappedAppend> {
let (plan, table) = self.arena_plan(workspace, stage, prior, inputs)?;
let timed = crate::command_profile::enabled();
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let started = std::time::Instant::now();
self.run_append(workspace, stage, &plan)?;
if timed {
@@ -104,6 +104,7 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
let ((commands, host), (hd, t)) = (buffers, run);
let timed = crate::command_profile::enabled();
let mut operation = self.submit(blas, commands, (&host.history_bytes, hd.hin, t), timed);
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let started = std::time::Instant::now();
let sync = blas.synchronize();
if operation.is_ok() && sync.is_ok() {
+67
View File
@@ -1,6 +1,7 @@
//! The only place of this crate that reads the process environment (`env-read` ratchet of `architecture.json`).
//! The reads keep their call sites and their parsing; a later step replaces these functions by a parsed settings value.
use leleka_cuda_model::env_switch::{EnvSwitch, rules};
use std::env::{self, VarError};
use std::ffi::{OsStr, OsString};
@@ -15,3 +16,69 @@ pub(crate) fn var<K: AsRef<OsStr>>(key: K) -> Result<String, VarError> {
pub(crate) fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> {
env::var_os(key)
}
// The operator's on/off switches: each is read from its variable on first use and cached
// (`leleka_cuda_model::env_switch`).
pub(crate) static CHAIN_UP8: EnvSwitch = EnvSwitch::new("LELEKA_CHAIN_UP8", rules::is_unset_or_not_zero);
pub(crate) static CHUNK_DRAIN: EnvSwitch = EnvSwitch::new("LELEKA_CHUNK_DRAIN", rules::is_set_and_not_zero);
pub(crate) static MMQ_NO_STREAMK: EnvSwitch = EnvSwitch::new("LELEKA_MMQ_NO_STREAMK", rules::is_set_and_not_zero);
pub(crate) static MTP_SNAPSHOT_MEMO: EnvSwitch = EnvSwitch::new("LELEKA_MTP_SNAPSHOT_MEMO", rules::is_unset_or_not_off);
pub(crate) static PREFILL_ALIGNED_COPY: EnvSwitch =
EnvSwitch::new("LELEKA_PREFILL_ALIGNED_COPY", rules::is_unset_or_not_zero);
pub(crate) static PREFILL_ALLOC_TRACE: EnvSwitch = EnvSwitch::new("LELEKA_PREFILL_ALLOC_TRACE", rules::is_one);
pub(crate) static PREFILL_DEFER_GUARDS: EnvSwitch =
EnvSwitch::new("LELEKA_PREFILL_DEFER_GUARDS", rules::is_unset_or_not_zero);
pub(crate) static PREFILL_DIAG_SKIP_EXPERT_DMA: EnvSwitch =
EnvSwitch::new("LELEKA_PREFILL_DIAG_SKIP_EXPERT_DMA", rules::is_one);
pub(crate) static PREFILL_FAST_REC: EnvSwitch = EnvSwitch::new("LELEKA_PREFILL_FAST_REC", rules::is_one);
pub(crate) static PREFILL_STALL_TRACE: EnvSwitch = EnvSwitch::new("LELEKA_PREFILL_STALL_TRACE", rules::is_one);
pub(crate) static PREFILL_ZERO_MEMSET: EnvSwitch =
EnvSwitch::new("LELEKA_PREFILL_ZERO_MEMSET", rules::is_unset_or_not_zero);
pub(crate) static QSA_LATE: EnvSwitch = EnvSwitch::new("LELEKA_QSA_LATE", rules::is_unset_or_not_zero);
pub(crate) static RING_SERIALIZE: EnvSwitch = EnvSwitch::new("LELEKA_RING_SERIALIZE", rules::is_set_and_not_zero);
pub(crate) static SM120_ATTN_DAILY_MTP: EnvSwitch = EnvSwitch::new("LELEKA_SM120_ATTN_DAILY_MTP", rules::is_one);
pub(crate) static STRATA_COMMIT_SYNC: EnvSwitch = EnvSwitch::new("STRATA_COMMIT_SYNC", rules::is_set);
pub(crate) static VRAM_LEDGER: EnvSwitch = EnvSwitch::new("LELEKA_VRAM_LEDGER", rules::is_one);
pub(crate) static WINDOW_MODULE_CACHE: EnvSwitch =
EnvSwitch::new("LELEKA_WINDOW_MODULE_CACHE", rules::is_unset_or_not_off);
// Switches whose rule is not one of the plain ones: the default is a named constant of the module that uses the switch.
pub(crate) static PREFILL_FUSED_SCANS: EnvSwitch =
EnvSwitch::new("LELEKA_PREFILL_FUSED_SCANS", rules::is_unset_or_not_zero);
pub(crate) static PREFILL_FAST_DEQUANT: EnvSwitch =
EnvSwitch::new("LELEKA_PREFILL_FAST_DEQUANT", rules::is_unset_or_not_zero);
pub(crate) static STAGE_VERIFY: EnvSwitch = EnvSwitch::new("LELEKA_STAGE_VERIFY", rules::is_set);
pub(crate) static CHAIN_DOWN: EnvSwitch = EnvSwitch::new("LELEKA_CHAIN_DOWN", chain_down);
pub(crate) static DRAFT_FUSED_COMMIT: EnvSwitch = EnvSwitch::new("LELEKA_DRAFT_FUSED_COMMIT", draft_fused_commit);
pub(crate) static SINK_SCAN_LEGACY: EnvSwitch = EnvSwitch::new("LELEKA_SINK_SCAN", is_legacy);
pub(crate) static PREFILL_GDN_NOSTORE: EnvSwitch = EnvSwitch::new("LELEKA_PREFILL_GDN_NOSTORE", gdn_nostore);
pub(crate) static PREFILL_GDN_KH: EnvSwitch = EnvSwitch::new("LELEKA_PREFILL_GDN_KH", gdn_kh);
pub(crate) static QSA_TOPK_WIDE: EnvSwitch = EnvSwitch::new("LELEKA_QSA_TOPK", qsa_topk_wide);
fn text(value: Option<&OsStr>) -> Option<&str> {
value.and_then(OsStr::to_str)
}
fn draft_fused_commit(value: Option<&OsStr>) -> bool {
crate::original_verify::draft::fused_commit_from(text(value))
}
fn chain_down(value: Option<&OsStr>) -> bool {
text(value).is_none_or(|v| v != "w8")
}
fn is_legacy(value: Option<&OsStr>) -> bool {
text(value) == Some("legacy")
}
fn gdn_nostore(value: Option<&OsStr>) -> bool {
text(value).map_or(crate::prefill_stage::GDN_NOSTORE_DEFAULT, |v| v != "0")
}
fn gdn_kh(value: Option<&OsStr>) -> bool {
text(value).map_or(crate::prefill_stage::GDN_KH_DEFAULT, |v| v == "1")
}
fn qsa_topk_wide(value: Option<&OsStr>) -> bool {
text(value).map_or(crate::qsa_late::TOPK_DEFAULT_WIDE, |v| v == "wide")
}
+1 -2
View File
@@ -183,8 +183,7 @@ fn state() -> &'static Mutex<Ledger> {
/// `LELEKA_VRAM_LEDGER=1`.
pub fn enabled() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| crate::settings::var_os("LELEKA_VRAM_LEDGER").is_some_and(|v| v == "1"))
crate::settings::VRAM_LEDGER.get()
}
pub(crate) fn note_alloc(address: u64, bytes: usize) {
@@ -85,6 +85,7 @@ fn iq_gate_up(c: &mut Case) -> Fail<usize> {
fn time_ggml_gu(c: &Case) -> Fail<f64> {
let (f, a) = (c.f, &c.act[0]);
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let start = Instant::now();
for _ in 0..50 {
for r in 0..FF {
@@ -63,6 +63,7 @@ impl Shared {
}
/// Spin (then sleep) until the epoch moves past `seen`; false when the pool is stopping.
fn await_epoch(&self, id: usize, seen: u32) -> bool {
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let at = Instant::now();
let mut spins = 0u32;
while self.epoch.0.load(Ordering::Acquire) == seen {
@@ -183,6 +183,7 @@ impl ExpertPool {
if jobs.len() > 65535 {
return Err(Error::Shape);
}
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let a = Instant::now();
self.load(jobs, None)?;
if self.shared.n == 1 {
@@ -11,6 +11,7 @@ impl ExpertPool {
if jobs.len() > 16 || self.shared.n == 1 || super::super::rust_legacy::oracle_q8_zero_enabled() {
return self.whole(jobs);
}
// Measurement timer, not decision logic (instant-now exception in architecture.json).
self.split_run(jobs, Instant::now())
}
/// The two-phase (gate/up, requantize, down) single-activation split path; `t` is when the caller started timing.
@@ -8,6 +8,7 @@ impl Shared {
self.state(self.n, -12);
let mut spins = 0u32;
let mut seen = 0;
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let mut t = Instant::now();
loop {
let d = self.done.0.load(Ordering::Acquire);
@@ -5,6 +5,7 @@ use super::{Duration, Instant, Ordering, Shared, trace};
/// The clock of the park/stall deadlines (one site for the three waits).
fn stall_clock() -> Instant {
// Measurement timer, not decision logic (instant-now exception in architecture.json).
Instant::now()
}
@@ -89,7 +89,8 @@ impl NativePool {
pub(super) fn phase(&mut self, mode: u32, rows: usize) {
self.phase_timed(mode, rows, 0)
}
/// `at`: first of the five timing stages of this phase (ignored when timing is off).
/// `at`: first of the five timing stages of this phase (ignored when timing is off). The stage laps are measurement
/// timers, not decision logic (instant-now exception in architecture.json).
pub(super) fn phase_timed(&mut self, mode: u32, rows: usize, at: usize) {
let on = self.timing.is_some();
let mut t = [None; 6];
@@ -56,6 +56,7 @@ impl TraceState {
/// `n` workers and the host.
pub(super) fn new(n: usize) -> Self {
Self {
// Measurement timer, not decision logic (instant-now exception in architecture.json).
start: Instant::now(),
slots: (0..=n).map(|_| Slot::default()).collect(),
task_ns: (0..TASK_TABLE).map(|_| AtomicU32::new(0)).collect(),
+29 -14
View File
@@ -210,23 +210,33 @@ their doc comment now says by which phase), `ConversationManager` (a domain type
The order: every ratchet of `architecture-baseline.json` goes to zero in the code, or to a named entry of the `exceptions` list of `architecture.json`
(crate, file, ratchet, reason; the gate reads it, an entry that excuses nothing or has no reason is an error). Numbers are production code of the
low-level crates (`cuda-driver`, `cuda-model`, `model-format`, `native-cpu-expert`, `leleka-memory`, `memory-os`, `libc-shim`, `cpu-sys`, the gpt-oss
workers and the small libraries), before -> after, from `scripts/check-architecture.py`.
workers and the small libraries), before -> after, from `scripts/check-architecture.py`. After the pass **no low-level crate has a number left in the
baseline**; what stays is the exceptions list (151 entries for these crates).
| Ratchet | Before | After | How |
|---|---|---|---|
| `allow-unused-imports` | 552 | 0 | `scripts/dev/prune_unused_imports.py`: strips the allow, compiles with one job per feature set (`cuda-driver`, `sm86`, all features), deletes the imports the compiler reports in every compilation unit, puts `#[cfg(test)]` on the ones only the library's unit tests use. Most of the 410 `cuda-driver` allows sat on `pub use` re-exports that needed no allow at all |
| `glob-super-import` | 3 | 2 (`cuda-driver`: `head_dispatch` and `copy_ring_layer`, on `claude/debt-hot-low`) | `root_exports.rs` names its paths (`crate::x`, `leleka_cuda_model::serving_context`) |
| `path-include` | 132 | 0 counted (1 in `cuda-driver`: the shared `head_dispatch`, on `claude/debt-hot-low`) | `scripts/dev/path_to_layout.py`: walks the module tree (a file loaded by `#[path]` resolves its children next to itself, a default file in a directory of its name), moves the module files to `<parent>/<name>.rs` with `git mv`, drops the attribute, rewrites `include_*!` paths and the paths scripts quote (`scripts/dev/update_path_refs.py`). 502 files moved (`cuda-driver` 472, `model-format` 27, `native-cpu-expert` 3); module paths did not change. The gate now treats `#[cfg(test)] #[path = "../tests/x.rs"] mod x;` as test code |
| `env-read` | 30 | 0 outside the named exceptions | one reader per crate: new typed `settings.rs` in `cpu-worker`, `tokenizer`, `gptoss-npu`, `gpu-npu-worker`, `igpu`, `npu-service`, `leleka-memory`, `gptoss`, `model-format` (functions named after the variable, returning parsed values); `obs` parses `LELEKA_LOG*` in `level.rs`; `cuda-model` has `env_switch::EnvSwitch` (the name, a typed rule, the answer cached on first read). Exceptions: the readers above, `cpu-kernels` (parses the ISA request), `libc-shim` and `memory-os` (platform adapters), the `npu-worker` and `native-parity-bench` roots |
| `dyn-trait` | 52 outside `cuda-driver` | 0 outside the named exceptions | callbacks and probes became generics (`&mut (impl FnMut(..) + ?Sized)`, `&(impl ProcSource + ?Sized)`); what stays is a port boundary (`MemoryPressure`, `ProcSource`, `PageLocking`, `ModelBytes`, `PageSource`, `PrefillAccelerator`, `LayerCache`, the GPU probe closure), a trait method that must be dyn-compatible, `Box<dyn Error>` of a library boundary, or the type-erased job of the worker pool |
| `instant-now` | 54 outside the driver and the CPU pool | 0 outside the named exceptions | the clock adapter (`obs/time/clock.rs`) and measurement timers (stage laps and wall times printed in the workers' timing lines, load reports); each carries a comment that says so. `leleka-memory` reads `SystemClock` |
| `process-global` | 50 outside the driver and the CPU pool | 0 outside the named exceptions | immutable tables (regex, half table), operator settings read once, the process-wide logger, the process singletons the S13/S14 injection is for (`Governor::global()`, `Inventory`, the serving context, the verify stamps) |
| Ratchet | Before | After | Exceptions | How |
|---|---|---|---|---|
| `allow-unused-imports` | 552 | 0 | 0 | `scripts/dev/prune_unused_imports.py` strips the allow, compiles with one job per feature set (`cuda-driver`, `sm86`, all features), deletes the imports the compiler reports in every compilation unit and puts `#[cfg(test)]` on the ones only the library's unit tests use. Most of the 410 `cuda-driver` allows sat on `pub use` re-exports that needed no allow at all |
| `glob-super-import` | 3 | 0 | 0 | `root_exports.rs` names its paths; `head_dispatch` was compiled twice (declared by two parents with `#[path]`, so its glob meant two things): it is the one module `native_head_dispatch.rs` now; `copy_ring_layer.rs` (400 lines) is split into `copy_ring_layer` (execution) and `copy_ring_projection` (projection launches, status words) with explicit imports |
| `path-include` | 132 | 0 | 0 | `scripts/dev/path_to_layout.py` walks the module tree (a file loaded by `#[path]` resolves its children next to itself, a default file in a directory of its name), moves each module file to `<parent>/<name>.rs` with `git mv`, drops the attribute and rewrites `include_*!` and the paths that scripts quote (`scripts/dev/update_path_refs.py`). 502 files moved (`cuda-driver` 472, `model-format` 27, `native-cpu-expert` 3); module paths did not change. The gate treats `#[cfg(test)] #[path = "../tests/x.rs"] mod x;` as test code |
| `env-read` | 30 | 0 | 19 | one reader per crate: typed `settings.rs` in `cpu-worker`, `tokenizer`, `gptoss-npu`, `gpu-npu-worker`, `igpu`, `leleka-memory`, `gptoss`, `model-format` (functions named after the variable, returning parsed values); `obs` parses `LELEKA_LOG*` in `level.rs`; `cuda-model` has `env_switch::EnvSwitch` (variable name, typed rule, answer cached on the first read), and the 26 on/off switches of `cuda-driver` are entries of its `settings.rs` catalogue. Exceptions: those readers, `cpu-kernels` (parses the ISA request), `libc-shim` and `memory-os` (platform adapters), the `npu-worker` and `native-parity-bench` roots. `cuda-driver` and `native-cpu-expert` keep a pass-through `var`/`var_os` for the option parsers (stager, stream-all, chain flags, sm120 switches, the pool's `STRATA_*`): their typed `Settings` value is the one open item of this ratchet |
| `dyn-trait` | 97 | 0 | 38 | callbacks and probes became generics (`&mut (impl FnMut(..) + ?Sized)`, `&(impl ProcSource + ?Sized)`, `&(impl ArenaMap + ?Sized)`, `&mut (impl Write + ?Sized)`); what stays is a port boundary (`MemoryPressure`, `ProcSource`, `PageLocking`, `ModelBytes`, `PageSource`, `PrefillAccelerator`, `LayerCache`, the GPU probe closure, the GEMM provider and the arena views of the verifier and the copy ring), a trait method that must be dyn-compatible, `Box<dyn Error>` of a library boundary, or the type-erased job of the worker pool |
| `instant-now` | 106 | 0 | 48 | the clock adapter (`obs/time/clock.rs`) and measurement timers (stage laps and wall times printed in the workers' timing lines, load reports, the driver's launch-path spans and the CPU expert pool's phase timers); each carries a comment that says so. `leleka-memory` reads `SystemClock`. Replacing a timer by the `Clock` port would add a field or a generic to every launch owner and pool |
| `process-global` | 173 | 0 | 46 | `cuda-driver`: 96 -> 18 files left (the switches moved to `EnvSwitch`; what stays are parsed operator settings, probe and proof memos, the VRAM ledger); immutable tables (regex, half table), the process-wide logger, the process singletons the S13/S14 injection is for (`Governor::global()`, `Inventory`, the serving context, the verify stamps) |
The test run (`cargo test`, slim profile) of `cuda-model`, `obs`, `leleka-memory`, `tokenizer`, `model-format`, `gptoss`, `cpu-worker`, `igpu`,
`memory-os`, `experimental-ref` and `npu-service`: all green except the three known `qwen_artifact_binding` tests of `model-format`
(`cargo check --workspace --all-targets` is clean). The `dyn-trait`, `instant-now` and `process-global` rows exclude `cuda-driver` and `native-cpu-expert`: their changes and exceptions are on `claude/debt-hot-low`, which waits for the identity gate; the final table replaces this one when it is merged.
**Names.** 52 modules called after two things (`*_and_*`) are named after their responsibility, with the `*_and_*` names of test sentences left on purpose
(5): `cpu-sys` `avx2_and_avxvnni` -> `x86_dot_kernels`, `igpu` `error_and_kind` -> `gpu_error`, `cuda-driver` `projection_grids_and_bounds` ->
`projection_geometry`, `matrix_vector_buffers_and_shape` -> `matrix_vector_planning`, `original_expert_cache_open_and_slots` -> `original_expert_cache_slots`,
`gptoss` `state_and_cache` -> `decode_state`, `openvino` `compile_and_infer` -> `inference_runtime` (the full list is in the commit). **Docs.** The 604 generated
headers of these crates (`Methods of ...`, `Functions: ...`, `Split out of ...`) are real descriptions (what the file holds and why it is a file of its own);
the agents that wrote them reported about 80 files whose name does not match their content (for example `cuda-driver` `bringup_trace_enabled.rs` holds the
driver bring-up core, `qsa_prompt_kv_drop.rs` the `QsaPromptStage` owner): those renames are the next naming pass.
### (e) Stage 10 pass: control-plane, desktop-core, deploy and the small crates (owner order 2026-11-14, branch `claude/debt-control`)
**Verification.** `cargo check --workspace --all-targets` is clean after the pass; `cuda-driver` also with `sm86`. Tests (`cargo test`, slim profile, GPU modules
skipped): `cuda-model`, `obs`, `leleka-memory`, `tokenizer`, `model-format`, `gptoss`, `cpu-worker`, `igpu`, `memory-os`, `experimental-ref`, `npu-service` green except the three known
`qwen_artifact_binding` tests of `model-format` (NTFS). **Identity.** Imports, moves, renames, doc headers, the settings readers and the exceptions do not change generated
code. The commits that touch the driver wrappers and the CPU expert pool (EnvSwitch in 26 decode and prefill switches, the `ArenaMap`/`Write` generics, the single
`head_dispatch`, the `copy_ring_layer` split, the timer comments) are on `claude/debt-hot-low`, which stays out of `main` until the two-binary identity gate has passed
on them (`scripts/laptop/identity-gate.sh`; not run: it needs the memory the containers hold).
Crates: `leleka-control-plane`, `leleka-engine-host`, `leleka-deploy`, `leleka-gateway-domain`, `leleka-gateway-text`, `leleka-backend-api`, `leleka-runtime-client`, `leleka-npu-service`. Numbers are from `scripts/check-architecture.py`; a site that must stay is a named entry of `exceptions` in `architecture.json` (crate, file, ratchet, reason), not a baseline number.
@@ -256,6 +266,11 @@ Crates: `leleka-control-plane`, `leleka-engine-host`, `leleka-deploy`, `leleka-g
| Windows-only files (`key_init/windows.rs`, `facts/windows.rs`, `winfront/*`, `winservice/*`) | edited by hand (names read from the code); no Windows `cargo check` could run because `leleka-memory` and `leleka-model-format` do not compile for Windows at this commit (`governor/operations.rs`, `qwen4exp_*`: unresolved imports under `cfg(windows)`) | a Windows `cargo check -p leleka-deploy -p leleka-control-plane` once those two crates compile there |
| deploy end-to-end tests `dry_run_*` and `reconfigure_flow::*` | need free VRAM and a quiet GPU (host checks read `nvidia-smi`); they fail on the busy laptop with "GPU memory: ... free but the engine needs ..." | run on the 5090 |
**Left.** (1) the typed `Settings` value of `cuda-driver` and the CPU expert pool (above); (2) injecting a `Clock` into the driver launch owners and the pool instead of the
measurement-timer exceptions, and the S13/S14 injection of the process singletons: both need the engine crate; (3) the file names whose content differs from their
name; (4) the Windows-only code (`libc-shim`, 9 platform-cfg files of `cuda-driver`) was edited without a native Windows `cargo check`; (5) `cargo check -p leleka-cuda-driver` without
`--features cuda-driver` has never compiled (379 errors at the base commit too); the product always builds with the feature.
### (f) Stage 9: the historical Strata names in our own code (owner decision 2026-11-14, branch `claude/debt-rename`)
| Old | New | Where |