From 44c65e3ce076d75dcb6d3eaa5bcbc9d838531a61 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 23 Nov 2026 16:43:07 +0100 Subject: [PATCH] cuda-driver: operator settings and marker files live in the settings catalogue, not in ad-hoc OnceLock cells Eleven call sites cached their own parse of an environment variable in a function-local OnceLock; they now ask settings.rs for a named cell (same variable, same default, same parse, read on first use). The three copies of the 250 ms marker-file poll become one MarkerFiles type. Eleven process-global exceptions are deleted; STRA-338 --- architecture.json | 14 +--- .../cuda-driver/src/arch_ptx/stream_k_off.rs | 48 +----------- crates/cuda-driver/src/context.rs | 9 +-- crates/cuda-driver/src/lib.rs | 1 + crates/cuda-driver/src/marker_files.rs | 73 ++++++++++++++++++ .../copy_ring/host_stage/verify_enabled.rs | 11 +-- .../copy_ring/skip_expert_dma.rs | 25 ++----- .../abi/platform/library_drop.rs | 3 +- .../src/original_gpu_schedule/transport.rs | 8 +- crates/cuda-driver/src/original_verify.rs | 1 + .../cuda-driver/src/original_verify/chain.rs | 8 +- .../src/original_verify/gpu_plan.rs | 1 + .../gpu_plan/cpu_sink_publish_gpu_plan.rs | 14 ++-- crates/cuda-driver/src/original_verify/moe.rs | 2 +- .../original_verify/moe/pcie_fast_kernel.rs | 19 +++-- .../qsa_prompt_attention_drop.rs | 5 +- crates/cuda-driver/src/qsa_prompt_kv.rs | 1 + .../src/qsa_prompt_kv/resident_transport.rs | 9 ++- crates/cuda-driver/src/settings.rs | 74 ++++++++++++++++++- 19 files changed, 195 insertions(+), 131 deletions(-) create mode 100644 crates/cuda-driver/src/marker_files.rs diff --git a/architecture.json b/architecture.json index 04c45b08..75f89738 100644 --- a/architecture.json +++ b/architecture.json @@ -63,7 +63,7 @@ {"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: 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-cuda-driver", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: its catalogue holds the operator settings as named cells (EnvSwitch, EnvSetting, LazySetting from leleka_cuda_model::env_switch, MarkerFiles) read on first use; the option parsers that take several variables (stager, stream-all, chain flags, sm120 switches) call the pass-through var/var_os from their own parse functions"}, {"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"}, @@ -243,24 +243,14 @@ {"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-cuda-driver", "file": "src/marker_files.rs", "ratchet": "process-global", "reason": "the marker files of the A/B controls: the paths named by the operator are read once and the time of the first look is kept (OnceLock), so a hot path looks at the disk at most every 250 ms; one type serves the three controls"}, {"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"}, diff --git a/crates/cuda-driver/src/arch_ptx/stream_k_off.rs b/crates/cuda-driver/src/arch_ptx/stream_k_off.rs index 08c022aa..4d7f5ecb 100644 --- a/crates/cuda-driver/src/arch_ptx/stream_k_off.rs +++ b/crates/cuda-driver/src/arch_ptx/stream_k_off.rs @@ -14,14 +14,9 @@ use super::imp; /// exactly the one of the sealed code. pub(crate) fn stream_k_off() -> bool { use std::sync::atomic::Ordering::Relaxed; - static PATHS: std::sync::OnceLock<[Option; 2]> = std::sync::OnceLock::new(); 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)) - }); - if paths.iter().any(Option::is_some) { - let [no_streamk, streamk] = marker_files_present(paths); + if crate::settings::STREAM_K_MARKERS.any_named() { + let [no_streamk, streamk] = crate::settings::STREAM_K_MARKERS.all_present(); // the file of `LELEKA_MMQ_STREAMK_FILE` forces the stream-K grid back on (an A/B control inside one engine) if streamk { return false; @@ -33,24 +28,6 @@ pub(crate) fn stream_k_off() -> bool { fixed || STREAM_K_AVOIDED.load(Relaxed) } -/// Presence of the two marker files (`LELEKA_MMQ_NO_STREAMK_FILE`, `LELEKA_MMQ_STREAMK_FILE`), looked at most every -/// 250 ms. -fn marker_files_present(paths: &[Option; 2]) -> [bool; 2] { - use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; - static CHECKED: std::sync::OnceLock = std::sync::OnceLock::new(); - static LAST_MS: AtomicU64 = AtomicU64::new(u64::MAX); - static PRESENT: [AtomicBool; 2] = [const { AtomicBool::new(false) }; 2]; - let now = CHECKED.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64; - let last = LAST_MS.load(Relaxed); - if last == u64::MAX || now.saturating_sub(last) >= 250 { - LAST_MS.store(now, Relaxed); - for (path, present) in paths.iter().zip(&PRESENT) { - present.store(path.as_ref().is_some_and(|p| p.exists()), Relaxed); - } - } - [PRESENT[0].load(Relaxed), PRESENT[1].load(Relaxed)] -} - /// EXPERIMENTAL diagnostic (STRA-235): `LELEKA_FORCE_SMS=N` makes the MMQ and MTP-prefill owners plan their stream-K /// grids (and size their fixup workspaces) for N SMs instead of the device's count, e.g. 48 on a 5090 to run the /// laptop's decomposition there. @@ -67,26 +44,7 @@ pub(crate) fn forced_sms(real: u32) -> u32 { /// its tail to a prompt chunk and again when the chunk's arena is released: nothing of one chunk (or of the refill / /// decode before it) can overlap the next. pub(crate) fn chunk_drain() -> bool { - use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; - static PATH: std::sync::OnceLock> = std::sync::OnceLock::new(); - static START: std::sync::OnceLock = std::sync::OnceLock::new(); - static LAST_MS: AtomicU64 = AtomicU64::new(u64::MAX); - static PRESENT: AtomicBool = AtomicBool::new(false); - if crate::settings::CHUNK_DRAIN.get() { - return true; - } - let Some(path) = - PATH.get_or_init(|| crate::settings::var_os("LELEKA_CHUNK_DRAIN_FILE").map(std::path::PathBuf::from)).as_ref() - else { - return false; - }; - let now = START.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64; - let last = LAST_MS.load(Relaxed); - if last == u64::MAX || now.saturating_sub(last) >= 250 { - LAST_MS.store(now, Relaxed); - PRESENT.store(path.exists(), Relaxed); - } - PRESENT.load(Relaxed) + crate::settings::CHUNK_DRAIN.get() || crate::settings::CHUNK_DRAIN_MARKER.present(0) } /// Decide the default of [`stream_k_off`] for the device that is current on this thread (needs a current context). diff --git a/crates/cuda-driver/src/context.rs b/crates/cuda-driver/src/context.rs index f73096b9..c339ba0e 100644 --- a/crates/cuda-driver/src/context.rs +++ b/crates/cuda-driver/src/context.rs @@ -79,14 +79,7 @@ impl Context<'_> { list.push((handle, bytes)); list.iter().map(|b| b.1).sum::() }; - static LIMIT: std::sync::OnceLock = std::sync::OnceLock::new(); - let limit = *LIMIT.get_or_init(|| { - crate::settings::var("LELEKA_PREFILL_DEFER_FREE_MIB") - .ok() - .and_then(|v| v.trim().parse::().ok()) - .unwrap_or(512) - << 20 - }); + let limit = crate::settings::PREFILL_DEFER_FREE_LIMIT.get(); if pending > limit { self.flush_deferred_frees() } else { Ok(()) } } /// Free every deferred buffer (one device synchronization). diff --git a/crates/cuda-driver/src/lib.rs b/crates/cuda-driver/src/lib.rs index fa50fe35..de0cd116 100644 --- a/crates/cuda-driver/src/lib.rs +++ b/crates/cuda-driver/src/lib.rs @@ -42,6 +42,7 @@ mod root_exports; pub use root_exports::*; // STRA-338: the only reader of the process environment (`env-read` ratchet). +mod marker_files; mod settings; pub mod compute_drain; diff --git a/crates/cuda-driver/src/marker_files.rs b/crates/cuda-driver/src/marker_files.rs new file mode 100644 index 00000000..b8963369 --- /dev/null +++ b/crates/cuda-driver/src/marker_files.rs @@ -0,0 +1,73 @@ +//! Marker files that an operator creates to switch a diagnostic A/B arm inside a running engine. +//! +//! The paths come from environment variables read once (through `settings`); the existence of each file is looked at +//! most every 250 ms, so a hot path pays one clock read and some atomic loads. + +use std::ffi::OsString; +use std::path::PathBuf; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; +use std::time::Instant; + +const POLL_INTERVAL_MS: u64 = 250; + +/// The marker files named by `N` environment variables, and the last look at whether each exists. +pub(crate) struct MarkerFiles { + variables: [&'static str; N], + paths: OnceLock<[Option; N]>, + started: OnceLock, + last_look_ms: AtomicU64, + present: [AtomicBool; N], +} + +impl MarkerFiles { + /// Marker files named by the variables `variables`; nothing is read until the first use. + pub(crate) const fn new(variables: [&'static str; N]) -> Self { + Self { + variables, + paths: OnceLock::new(), + started: OnceLock::new(), + last_look_ms: AtomicU64::new(u64::MAX), + present: [const { AtomicBool::new(false) }; N], + } + } + + fn paths(&self) -> &[Option; N] { + self.paths.get_or_init(|| self.variables.map(|name| crate::settings::var_os(name).map(path_of))) + } + + /// Whether any of the variables names a file at all (when none does, no file is ever looked at). + pub(crate) fn any_named(&self) -> bool { + self.paths().iter().any(Option::is_some) + } + + /// Whether the file of the variable number `index` existed at the last look (a look is at most every 250 ms). + pub(crate) fn present(&self, index: usize) -> bool { + self.look_if_due(); + self.present[index].load(Relaxed) + } + + /// The existence of every file at the last look. + pub(crate) fn all_present(&self) -> [bool; N] { + self.look_if_due(); + std::array::from_fn(|index| self.present[index].load(Relaxed)) + } + + fn look_if_due(&self) { + if !self.any_named() { + return; + } + let now = self.started.get_or_init(Instant::now).elapsed().as_millis() as u64; + let last = self.last_look_ms.load(Relaxed); + if last == u64::MAX || now.saturating_sub(last) >= POLL_INTERVAL_MS { + self.last_look_ms.store(now, Relaxed); + for (path, present) in self.paths().iter().zip(&self.present) { + present.store(path.as_ref().is_some_and(|p| p.exists()), Relaxed); + } + } + } +} + +fn path_of(value: OsString) -> PathBuf { + PathBuf::from(value) +} diff --git a/crates/cuda-driver/src/mmq/resident/original_group/copy_ring/host_stage/verify_enabled.rs b/crates/cuda-driver/src/mmq/resident/original_group/copy_ring/host_stage/verify_enabled.rs index 760b4521..dcd0385f 100644 --- a/crates/cuda-driver/src/mmq/resident/original_group/copy_ring/host_stage/verify_enabled.rs +++ b/crates/cuda-driver/src/mmq/resident/original_group/copy_ring/host_stage/verify_enabled.rs @@ -26,16 +26,7 @@ pub(super) fn verify_enabled() -> bool { pub(in super::super) fn layer_priority(layer: usize, per_layer_bytes: usize) -> u8 { #[cfg(windows)] { - use std::sync::OnceLock; - static MODE: OnceLock>> = OnceLock::new(); - let mode = *MODE.get_or_init(|| match crate::settings::var("LELEKA_STAGE_PRIORITY").ok().as_deref() { - Some("on") | Some("auto") | Some("1") => Some(None), - Some(other) => { - other.parse::().ok().filter(|g| *g > 0.0).map(|g| Some((g * (1u64 << 30) as f64) as u64)) - } - None => None, - }); - let Some(fixed) = mode else { return 0 }; + let Some(fixed) = crate::settings::STAGE_PRIORITY.get() else { return 0 }; let budget = match fixed { Some(bytes) => bytes, None => match libc::physical_memory() { diff --git a/crates/cuda-driver/src/mmq/resident/original_group/copy_ring/skip_expert_dma.rs b/crates/cuda-driver/src/mmq/resident/original_group/copy_ring/skip_expert_dma.rs index f996ed01..74cb2031 100644 --- a/crates/cuda-driver/src/mmq/resident/original_group/copy_ring/skip_expert_dma.rs +++ b/crates/cuda-driver/src/mmq/resident/original_group/copy_ring/skip_expert_dma.rs @@ -60,31 +60,16 @@ impl RingArena for crate::OriginalDeviceGrRead<'_, '_, '_> { } } pub(super) fn serialize_ring(which: Drain) -> bool { - use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; - static START: std::sync::OnceLock = std::sync::OnceLock::new(); - static PATHS: std::sync::OnceLock<[Option; 3]> = std::sync::OnceLock::new(); - static LAST_MS: AtomicU64 = AtomicU64::new(u64::MAX); - static PRESENT: [AtomicBool; 3] = [const { AtomicBool::new(false) }; 3]; if crate::settings::RING_SERIALIZE.get() { return true; } - let paths = PATHS.get_or_init(|| { - ["LELEKA_RING_SERIALIZE_FILE", "LELEKA_RING_SERIALIZE_COPY_FILE", "LELEKA_RING_SERIALIZE_CMD_FILE"] - .map(|name| crate::settings::var_os(name).map(std::path::PathBuf::from)) - }); - if paths.iter().all(Option::is_none) { + let markers = &crate::settings::RING_SERIALIZE_MARKERS; + if !markers.any_named() { return false; } - let now = START.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64; - let last = LAST_MS.load(Relaxed); - if last == u64::MAX || now.saturating_sub(last) >= 250 { - LAST_MS.store(now, Relaxed); - for (path, present) in paths.iter().zip(&PRESENT) { - present.store(path.as_ref().is_some_and(|p| p.exists()), Relaxed); - } - } - let both = PRESENT[0].load(Relaxed); - both || PRESENT[which.index()].load(Relaxed) + let present = markers.all_present(); + let both = present[0]; + both || present[which.index()] } impl Drain { fn index(self) -> usize { diff --git a/crates/cuda-driver/src/original_gpu_schedule/abi/platform/library_drop.rs b/crates/cuda-driver/src/original_gpu_schedule/abi/platform/library_drop.rs index 5d92246d..43fe4660 100644 --- a/crates/cuda-driver/src/original_gpu_schedule/abi/platform/library_drop.rs +++ b/crates/cuda-driver/src/original_gpu_schedule/abi/platform/library_drop.rs @@ -32,6 +32,5 @@ pub(super) unsafe extern "C" fn noop_host_fn(_: *mut c_void) {} /// `LELEKA_CB_WARMUP=off|0|no` skips the warm-up of [`Api::warm_callback_thread`] (A/B arm). #[cfg(target_os = "linux")] pub(super) fn callback_warmup_enabled() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| !matches!(crate::settings::var("LELEKA_CB_WARMUP").as_deref(), Ok("off" | "0" | "no"))) + crate::settings::CALLBACK_WARMUP.get() } diff --git a/crates/cuda-driver/src/original_gpu_schedule/transport.rs b/crates/cuda-driver/src/original_gpu_schedule/transport.rs index a6366a24..274a580c 100644 --- a/crates/cuda-driver/src/original_gpu_schedule/transport.rs +++ b/crates/cuda-driver/src/original_gpu_schedule/transport.rs @@ -58,17 +58,11 @@ pub(super) fn call_unless( /// instantiation of the process fail once with the driver's out-of-memory code, so the fallback can be exercised on a /// card with room. pub(super) fn injected_window_oom(policy: OriginalCapturePolicy) -> bool { - static AT: std::sync::OnceLock = std::sync::OnceLock::new(); static SEEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); if policy != OriginalCapturePolicy::VerifierWindow { return false; } - let at = *AT.get_or_init(|| { - crate::settings::var("LELEKA_TEST_WINDOW_INSTANTIATE_OOM_AT") - .ok() - .and_then(|v| v.trim().parse().ok()) - .unwrap_or(0) - }); + let at = crate::settings::TEST_WINDOW_INSTANTIATE_OOM_AT.get(); at != 0 && SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1 == at } impl Stream<'_> { diff --git a/crates/cuda-driver/src/original_verify.rs b/crates/cuda-driver/src/original_verify.rs index 11dcbe6b..66e38edd 100644 --- a/crates/cuda-driver/src/original_verify.rs +++ b/crates/cuda-driver/src/original_verify.rs @@ -199,6 +199,7 @@ pub struct OriginalVerifyResources<'ctx> { } mod gpu_plan; mod schedule; +pub(crate) use gpu_plan::dma_options_from_host; pub use gpu_plan::{MAX_PCIE_FETCHES, OriginalVerifyGpuPlan, OriginalVerifyPcieSource}; #[cfg(any(test, feature = "expert-tier-probe"))] mod expert_probe; diff --git a/crates/cuda-driver/src/original_verify/chain.rs b/crates/cuda-driver/src/original_verify/chain.rs index 85dd1ac4..8b3d5a7c 100644 --- a/crates/cuda-driver/src/original_verify/chain.rs +++ b/crates/cuda-driver/src/original_verify/chain.rs @@ -114,8 +114,12 @@ pub(crate) fn flags() -> ChainFlags { if let Some(f) = TEST_FLAGS.with(|c| c.get()) { return f; } - static FLAGS: std::sync::OnceLock = std::sync::OnceLock::new(); - *FLAGS.get_or_init(|| ChainFlags::parse(|k| crate::settings::var(k).ok())) + crate::settings::CHAIN_FLAGS.get() +} + +/// The switches as the process environment sets them (what `settings::CHAIN_FLAGS` caches). +pub(crate) fn flags_from_environment() -> ChainFlags { + ChainFlags::parse(|k| crate::settings::var(k).ok()) } #[cfg(test)] diff --git a/crates/cuda-driver/src/original_verify/gpu_plan.rs b/crates/cuda-driver/src/original_verify/gpu_plan.rs index 62a44d32..201c5049 100644 --- a/crates/cuda-driver/src/original_verify/gpu_plan.rs +++ b/crates/cuda-driver/src/original_verify/gpu_plan.rs @@ -59,5 +59,6 @@ mod plan_phases; mod plan_tier_tally; #[cfg(test)] pub(crate) use cpu_sink_publish_gpu_plan::dma_options; +pub(crate) use cpu_sink_publish_gpu_plan::dma_options_from_host; mod dma_options_for; use dma_options_for::dma_options_for; diff --git a/crates/cuda-driver/src/original_verify/gpu_plan/cpu_sink_publish_gpu_plan.rs b/crates/cuda-driver/src/original_verify/gpu_plan/cpu_sink_publish_gpu_plan.rs index 61682c89..7465bd8b 100644 --- a/crates/cuda-driver/src/original_verify/gpu_plan/cpu_sink_publish_gpu_plan.rs +++ b/crates/cuda-driver/src/original_verify/gpu_plan/cpu_sink_publish_gpu_plan.rs @@ -71,10 +71,12 @@ impl<'ctx> schedule::OriginalVerifyCpuSink<'_, 'ctx> { /// (`pcie_copy_gpu_raw_batch_page_locked` repeats the check). The stream write of flag B is also opt-in under WSL2 /// only. `=on` / `=write` force either call. pub(crate) fn dma_options() -> (bool, bool, bool) { - static OPTIONS: std::sync::OnceLock<(bool, bool, bool)> = std::sync::OnceLock::new(); - *OPTIONS.get_or_init(|| { - let wsl = std::fs::read_to_string("/proc/sys/kernel/osrelease") - .is_ok_and(|v| v.to_ascii_lowercase().contains("microsoft")); - dma_options_for(wsl, cfg!(windows), |name| crate::settings::var(name).unwrap_or_default()) - }) + crate::settings::DMA_OPTIONS.get() +} + +/// The options as this host and the process environment give them (what `settings::DMA_OPTIONS` caches). +pub(crate) fn dma_options_from_host() -> (bool, bool, bool) { + let wsl = std::fs::read_to_string("/proc/sys/kernel/osrelease") + .is_ok_and(|v| v.to_ascii_lowercase().contains("microsoft")); + dma_options_for(wsl, cfg!(windows), |name| crate::settings::var(name).unwrap_or_default()) } diff --git a/crates/cuda-driver/src/original_verify/moe.rs b/crates/cuda-driver/src/original_verify/moe.rs index 09afae70..ba619f6c 100644 --- a/crates/cuda-driver/src/original_verify/moe.rs +++ b/crates/cuda-driver/src/original_verify/moe.rs @@ -360,9 +360,9 @@ use pcie_fast_kernel::f32s; #[cfg(test)] use pcie_fast_kernel::gu_qk; use pcie_fast_kernel::items; -pub(crate) use pcie_fast_kernel::pcie_fast_kernel; use pcie_fast_kernel::plan_word; pub(crate) use pcie_fast_kernel::shared_attributes; +pub(crate) use pcie_fast_kernel::{PcieFastKernel, pcie_fast_kernel, pcie_fast_kernel_from_environment}; mod plan_f32_to_bf16; pub(crate) use plan_f32_to_bf16::BatchedRows; pub(crate) use plan_f32_to_bf16::expert_scratch; diff --git a/crates/cuda-driver/src/original_verify/moe/pcie_fast_kernel.rs b/crates/cuda-driver/src/original_verify/moe/pcie_fast_kernel.rs index 3e1d8a63..bedd9108 100644 --- a/crates/cuda-driver/src/original_verify/moe/pcie_fast_kernel.rs +++ b/crates/cuda-driver/src/original_verify/moe/pcie_fast_kernel.rs @@ -11,13 +11,18 @@ use super::{ /// `LELEKA_PCIE_KERNEL` = `k1u4|k1u8|k1u16|k2u4|k2u8|k2u16` selects an alternative staging copy kernel of the /// copy-kernel PCIe mode (default: the sealed `verify_fetch_spans_kernel`); `LELEKA_PCIE_GRID=BLOCKSxTHREADS` its /// launch shape (default 384x256, the Original's `48 * 8` blocks of 256). -pub(crate) fn pcie_fast_kernel() -> Option<(&'static str, [u32; 3], [u32; 3])> { - static CHOICE: std::sync::OnceLock> = std::sync::OnceLock::new(); - *CHOICE.get_or_init(|| { - let name = pcie_kernel_name(crate::settings::var("LELEKA_PCIE_KERNEL").ok()?.as_str())?; - let (blocks, threads) = pcie_grid(crate::settings::var("LELEKA_PCIE_GRID").ok()); - Some((name, [blocks, 1, 1], [threads, 1, 1])) - }) +pub(crate) fn pcie_fast_kernel() -> Option { + crate::settings::PCIE_FAST_KERNEL.get() +} + +/// The kernel name, grid and block of the alternative staging copy kernel. +pub(crate) type PcieFastKernel = (&'static str, [u32; 3], [u32; 3]); + +/// The choice as the process environment makes it (what `settings::PCIE_FAST_KERNEL` caches). +pub(crate) fn pcie_fast_kernel_from_environment() -> Option { + let name = pcie_kernel_name(crate::settings::var("LELEKA_PCIE_KERNEL").ok()?.as_str())?; + let (blocks, threads) = pcie_grid(crate::settings::var("LELEKA_PCIE_GRID").ok()); + Some((name, [blocks, 1, 1], [threads, 1, 1])) } fn pcie_kernel_name(choice: &str) -> Option<&'static str> { diff --git a/crates/cuda-driver/src/qsa_prompt_attention/qsa_prompt_attention_drop.rs b/crates/cuda-driver/src/qsa_prompt_attention/qsa_prompt_attention_drop.rs index 755436a0..2e797443 100644 --- a/crates/cuda-driver/src/qsa_prompt_attention/qsa_prompt_attention_drop.rs +++ b/crates/cuda-driver/src/qsa_prompt_attention/qsa_prompt_attention_drop.rs @@ -38,8 +38,5 @@ impl QsaPromptAttentionCompletion<'_, '_> { /// layer of an 8192-token chunk. Any grid gives the same status words (an OR of the same per-element conditions); /// `LELEKA_PREFILL_GUARD_GRID=64` restores it. pub(crate) fn guard_grid(t: usize) -> u32 { - static FIXED: std::sync::OnceLock> = std::sync::OnceLock::new(); - let fixed = - *FIXED.get_or_init(|| crate::settings::var("LELEKA_PREFILL_GUARD_GRID").ok().and_then(|v| v.parse().ok())); - fixed.unwrap_or_else(|| ((t * 6144).div_ceil(256 * 4)).clamp(64, 2048) as u32) + crate::settings::PREFILL_GUARD_GRID.get().unwrap_or_else(|| ((t * 6144).div_ceil(256 * 4)).clamp(64, 2048) as u32) } diff --git a/crates/cuda-driver/src/qsa_prompt_kv.rs b/crates/cuda-driver/src/qsa_prompt_kv.rs index 2b559c0b..d2109ef6 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv.rs @@ -85,6 +85,7 @@ mod mapped_journal; pub use mapped_journal::{OriginalQsaMappedAppend, OriginalQsaMappedJournal, OriginalQsaMappedPrefix}; mod resident_transport; +pub(crate) use resident_transport::prefetch_from; pub use resident_transport::{OriginalQsaResidentTransport, set_qsa_prefetch_override}; mod offsets; diff --git a/crates/cuda-driver/src/qsa_prompt_kv/resident_transport.rs b/crates/cuda-driver/src/qsa_prompt_kv/resident_transport.rs index 7cb59daa..6ee89edc 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/resident_transport.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/resident_transport.rs @@ -173,10 +173,7 @@ impl<'ctx> OriginalQsaResidentTransport<'ctx> { 1 => return true, _ => {} } - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| { - crate::settings::var("LELEKA_PREFILL_QSA_PREFETCH").map_or(QSA_PREFETCH_DEFAULT, |v| v != "0") - }) + crate::settings::PREFILL_QSA_PREFETCH.get() } /// Start the prefix copy of the layer that is about to run (its stage spans and host mirror are known before the /// indexer runs). The layer's `copy_prefix` then only orders the compute stream after it. Falls back to nothing @@ -339,6 +336,10 @@ pub fn set_qsa_prefetch_override(value: i8) { } /// Default of `LELEKA_PREFILL_QSA_PREFETCH` (flipped after its gates). const QSA_PREFETCH_DEFAULT: bool = true; +/// The position of `LELEKA_PREFILL_QSA_PREFETCH` for a value of the variable (what `settings` caches). +pub(crate) fn prefetch_from(value: Option<&std::ffi::OsStr>) -> bool { + value.and_then(std::ffi::OsStr::to_str).map_or(QSA_PREFETCH_DEFAULT, |v| v != "0") +} impl Drop for OriginalQsaResidentTransport<'_> { fn drop(&mut self) { let _ = self.close_inner(); diff --git a/crates/cuda-driver/src/settings.rs b/crates/cuda-driver/src/settings.rs index bb5cfec3..f1cf1b88 100644 --- a/crates/cuda-driver/src/settings.rs +++ b/crates/cuda-driver/src/settings.rs @@ -1,7 +1,10 @@ -//! 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. +//! The only place of this crate that reads the process environment (`env-read` ratchet of `architecture.json`), and +//! the catalogue of the operator settings: each is a named cell (`EnvSwitch`, `EnvSetting`, `LazySetting`, +//! `MarkerFiles`) that reads its variable on the first use and keeps the value for the process life. A call site asks +//! the catalogue; it never reads a variable or caches a parse of its own. -use leleka_cuda_model::env_switch::{EnvSwitch, rules}; +use crate::marker_files::MarkerFiles; +use leleka_cuda_model::env_switch::{EnvSetting, EnvSwitch, LazySetting, rules}; use std::env::{self, VarError}; use std::ffi::{OsStr, OsString}; @@ -82,3 +85,68 @@ fn gdn_kh(value: Option<&OsStr>) -> bool { fn qsa_topk_wide(value: Option<&OsStr>) -> bool { text(value).map_or(crate::qsa_late::TOPK_DEFAULT_WIDE, |v| v == "wide") } + +// Settings with a value of their own: the variable, the rule for its text and the default, read on first use. +pub(crate) static PREFILL_DEFER_FREE_LIMIT: EnvSetting = + EnvSetting::new("LELEKA_PREFILL_DEFER_FREE_MIB", defer_free_limit_bytes); +pub(crate) static PREFILL_GUARD_GRID: EnvSetting> = + EnvSetting::new("LELEKA_PREFILL_GUARD_GRID", guard_grid_blocks); +pub(crate) static TEST_WINDOW_INSTANTIATE_OOM_AT: EnvSetting = + EnvSetting::new("LELEKA_TEST_WINDOW_INSTANTIATE_OOM_AT", oom_at_instantiation); +pub(crate) static PREFILL_QSA_PREFETCH: EnvSwitch = + EnvSwitch::new("LELEKA_PREFILL_QSA_PREFETCH", crate::qsa_prompt_kv::prefetch_from); +#[cfg(target_os = "linux")] +pub(crate) static CALLBACK_WARMUP: EnvSwitch = EnvSwitch::new("LELEKA_CB_WARMUP", callback_warmup); +/// `None`: off; `Some(None)`: on with 90 % of the available RAM; `Some(Some(bytes))`: on with a fixed budget. +#[cfg(windows)] +pub(crate) static STAGE_PRIORITY: EnvSetting>> = + EnvSetting::new("LELEKA_STAGE_PRIORITY", stage_priority_budget); + +// Settings parsed from several variables (or from the host) by one function of the module that owns them. +pub(crate) static CHAIN_FLAGS: LazySetting = + LazySetting::new(crate::original_verify::chain::flags_from_environment); +pub(crate) static DMA_OPTIONS: LazySetting<(bool, bool, bool)> = + LazySetting::new(crate::original_verify::dma_options_from_host); +pub(crate) static PCIE_FAST_KERNEL: LazySetting> = + LazySetting::new(crate::original_verify::moe::pcie_fast_kernel_from_environment); + +// Marker files of the A/B controls: the path variables are read once, the files are looked at every 250 ms. +pub(crate) static STREAM_K_MARKERS: MarkerFiles<2> = + MarkerFiles::new(["LELEKA_MMQ_NO_STREAMK_FILE", "LELEKA_MMQ_STREAMK_FILE"]); +pub(crate) static CHUNK_DRAIN_MARKER: MarkerFiles<1> = MarkerFiles::new(["LELEKA_CHUNK_DRAIN_FILE"]); +pub(crate) static RING_SERIALIZE_MARKERS: MarkerFiles<3> = MarkerFiles::new([ + "LELEKA_RING_SERIALIZE_FILE", + "LELEKA_RING_SERIALIZE_COPY_FILE", + "LELEKA_RING_SERIALIZE_CMD_FILE", +]); + +/// `LELEKA_PREFILL_DEFER_FREE_MIB`: MiB of deferred frees a prefill may hold before one device synchronization (512). +fn defer_free_limit_bytes(value: Option<&OsStr>) -> usize { + text(value).and_then(|v| v.trim().parse::().ok()).unwrap_or(512) << 20 +} + +/// `LELEKA_PREFILL_GUARD_GRID`: a fixed block count for the prompt attention's guards. +fn guard_grid_blocks(value: Option<&OsStr>) -> Option { + text(value).and_then(|v| v.parse().ok()) +} + +/// `LELEKA_TEST_WINDOW_INSTANTIATE_OOM_AT`: the 1-based graph instantiation that fails once (0: none). +fn oom_at_instantiation(value: Option<&OsStr>) -> usize { + text(value).and_then(|v| v.trim().parse().ok()).unwrap_or(0) +} + +/// `LELEKA_CB_WARMUP=off|0|no` skips the callback-thread warm-up. +#[cfg(target_os = "linux")] +fn callback_warmup(value: Option<&OsStr>) -> bool { + !matches!(text(value), Some("off" | "0" | "no")) +} + +/// `LELEKA_STAGE_PRIORITY=on|auto|1|`. +#[cfg(windows)] +fn stage_priority_budget(value: Option<&OsStr>) -> Option> { + match text(value) { + Some("on") | Some("auto") | Some("1") => Some(None), + Some(other) => other.parse::().ok().filter(|g| *g > 0.0).map(|g| Some((g * (1u64 << 30) as f64) as u64)), + None => None, + } +}