diff --git a/architecture.json b/architecture.json index 04c45b08..0c650341 100644 --- a/architecture.json +++ b/architecture.json @@ -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: 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-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): the Setting catalogue parses the A/B switches and the kernel dispatch once; the pool and report readers still call the pass-through var/var_os with their own parsing"}, {"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"}, @@ -174,35 +174,15 @@ {"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/spawn_preview.rs", "ratchet": "dyn-trait", "reason": "Box is the process boundary: the factory hands the composed engine to the host, which holds one Backend per process (startup composition only, never per round)"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/measurement.rs", "ratchet": "dyn-trait", "reason": "the evaluation measurement sink is a stored callback handed in by the host (observer port, called once per request)"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/original_serve/runner.rs", "ratchet": "dyn-trait", "reason": "the GPU telemetry probe is a stored callback handed in by the host at load (port, sampled by the telemetry tick, not per token)"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/session.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/model_binding/weight_binding.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/model_binding/weight_binding/binding_identity.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/model_binding/weight_binding/binding_identity.rs", "ratchet": "process-global", "reason": "the model binding captures the serving context in cells once, when it is made (the driver's context is configured before the engine binds a model); the validators read the bound from the binding, not from the process"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding/model_binding.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/contract.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/mtp/mtp_frame.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/mtp/state/chunk/checked_chunk_end.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/mtp/state/dense_kv.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/mtp/state/prefix_draft_snapshot.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/mtp/state/warming.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/mtp_attention/dense_geometry.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/mtp_decode/first_seed_reuse_enabled.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/mtp_decode/mtp_decoder/decoder_entry.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/mtp_decode/mtp_window_spec.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/contract.rs", "ratchet": "process-global", "reason": "the engine's one reader of the driver's serving context (cells): contract::serving_cells() is called where a model is bound (InputConstants::from_artifact) and by sizing code that has no binding; every validator takes the bound from the binding"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_residency/split_group_pcie.rs", "ratchet": "process-global", "reason": "the adaptive-tier tuning constants, derived once from the settings capture (immutable after the first read)"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack.rs", "ratchet": "process-global", "reason": "the epoch of the bring-up trace timestamps (DBG_T0), set once; diagnostics only"}, - {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_open/assemble.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/original_serve_stack/stack_phases/original_serve_stack_prefill_phase.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/original_serve_stack/stack_config.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/original_spec_controller/trace_enabled.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/original_spec_draft.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/original_spec_draft/prefill_records.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/qsa_index/context.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/qsa_native_resources.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/qsa_index/context.rs", "ratchet": "process-global", "reason": "the QSA index owner bounds positions and sizes its pages by the process geometry in about ten places (validate_ids, pending rows, native state, max rows, index image sizes) that are reached without a model binding; carrying the bound in QsaOwner is the next step. Same value as the driver's serving context, read through the engine's contract::serving_cells"}, + {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/qsa_native_resources.rs", "ratchet": "process-global", "reason": "the byte sizes of a layer's host image come from the process geometry (QsaGeometry over the serving cells) when the resource set is built, before any binding is passed in; they follow the QSA owner's bound (see qsa_index/context.rs)"}, {"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/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/chunk/host_charge_bounded.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/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-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"}, @@ -243,36 +223,19 @@ {"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"}, {"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"} + {"crate": "leleka-native-cpu-expert", "file": "src/settings.rs", "ratchet": "process-global", "reason": "the cell of a Setting: the operator's switches and the CPU probes the kernels dispatch on are computed on the first read and kept for the process life (immutable; a hot path pays one atomic load, and kernel code carries no context to pass a settings value through)"} ], "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"}, 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, + } +} diff --git a/crates/cuda-model/src/env_switch.rs b/crates/cuda-model/src/env_switch.rs index ed6ebc56..e881f237 100644 --- a/crates/cuda-model/src/env_switch.rs +++ b/crates/cuda-model/src/env_switch.rs @@ -6,7 +6,8 @@ //! read), and can be judged without touching the process environment through [`EnvSwitch::decide`]. //! //! This file is the one place of the model crate where a variable is read and a value is cached for the process life; -//! both are listed in `architecture.json` `exceptions`. +//! both are listed in `architecture.json` `exceptions`. [`EnvSetting`] carries any typed value (a number, a choice, a +//! tuple) the same way, and [`LazySetting`] a value parsed from several variables by one function. use std::ffi::OsStr; use std::sync::OnceLock; @@ -49,16 +50,20 @@ pub mod rules { } } -/// One switch: the variable, its rule, and the answer cached on the first read. -pub struct EnvSwitch { +/// One operator setting: the variable, the rule that turns its text into a value, and the value cached on the first +/// read. [`EnvSwitch`] is the setting whose value is a flag. +pub struct EnvSetting { name: &'static str, - rule: Rule, - answer: OnceLock, + rule: fn(Option<&OsStr>) -> T, + answer: OnceLock, } -impl EnvSwitch { - /// A switch over the variable `name`; nothing is read until the first [`Self::get`]. - pub const fn new(name: &'static str, rule: Rule) -> Self { +/// One on/off switch: the variable, its [`Rule`], and the answer cached on the first read. +pub type EnvSwitch = EnvSetting; + +impl EnvSetting { + /// A setting over the variable `name`; nothing is read until the first [`Self::get_ref`]. + pub const fn new(name: &'static str, rule: fn(Option<&OsStr>) -> T) -> Self { Self { name, rule, answer: OnceLock::new() } } @@ -67,21 +72,57 @@ impl EnvSwitch { self.name } - /// The position of the switch: the environment is read on the first call only. + /// The value of the setting: the environment is read on the first call only. #[inline] - pub fn get(&self) -> bool { - *self.answer.get_or_init(|| (self.rule)(std::env::var_os(self.name).as_deref())) + pub fn get_ref(&self) -> &T { + self.answer.get_or_init(|| (self.rule)(std::env::var_os(self.name).as_deref())) } /// What the rule says for a given value, without reading the environment or the cache. - pub fn decide(&self, value: Option<&OsStr>) -> bool { + pub fn decide(&self, value: Option<&OsStr>) -> T { (self.rule)(value) } } +impl EnvSetting { + /// The value of the setting (a hot path pays one atomic load after the first call). + #[inline] + pub fn get(&self) -> T { + *self.get_ref() + } +} + +/// A setting that is parsed from several variables (or from the platform) by one function, run on the first read. +/// The function is the only reader; a hot path pays one atomic load afterwards. +pub struct LazySetting { + parse: fn() -> T, + answer: OnceLock, +} + +impl LazySetting { + /// A setting that `parse` computes on the first [`Self::get_ref`]. + pub const fn new(parse: fn() -> T) -> Self { + Self { parse, answer: OnceLock::new() } + } + + /// The value of the setting: `parse` runs on the first call only. + #[inline] + pub fn get_ref(&self) -> &T { + self.answer.get_or_init(self.parse) + } +} + +impl LazySetting { + /// The value of the setting (a hot path pays one atomic load after the first call). + #[inline] + pub fn get(&self) -> T { + *self.get_ref() + } +} + #[cfg(test)] mod tests { - use super::{EnvSwitch, rules}; + use super::{EnvSetting, EnvSwitch, LazySetting, rules}; use std::ffi::OsStr; fn os(text: &str) -> Option<&OsStr> { @@ -119,4 +160,28 @@ mod tests { assert_eq!(ABSENT_ON.name(), "LELEKA_TEST_SWITCH_THAT_IS_NEVER_SET"); assert!(!ABSENT_ON.decide(os("0"))); } + + #[test] + fn a_typed_setting_parses_its_text_once() { + fn parse(value: Option<&OsStr>) -> usize { + value.and_then(OsStr::to_str).and_then(|v| v.trim().parse().ok()).unwrap_or(512) + } + static ABSENT: EnvSetting = EnvSetting::new("LELEKA_TEST_SETTING_THAT_IS_NEVER_SET", parse); + assert_eq!(ABSENT.get(), 512); + assert_eq!(*ABSENT.get_ref(), 512); + assert_eq!(ABSENT.decide(os(" 7 ")), 7); + assert_eq!(ABSENT.decide(os("seven")), 512); + } + + #[test] + fn a_lazy_setting_runs_its_parser_once() { + static CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + fn parse() -> u32 { + CALLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + 41 + 1 + } + static SETTING: LazySetting = LazySetting::new(parse); + assert_eq!((SETTING.get(), SETTING.get(), *SETTING.get_ref()), (42, 42, 42)); + assert_eq!(CALLS.load(std::sync::atomic::Ordering::SeqCst), 1); + } } diff --git a/crates/engine-qwen35-cuda/src/backend/generate_mtp/mtp_loop_steps.rs b/crates/engine-qwen35-cuda/src/backend/generate_mtp/mtp_loop_steps.rs index e7a2e3ab..8f75539c 100644 --- a/crates/engine-qwen35-cuda/src/backend/generate_mtp/mtp_loop_steps.rs +++ b/crates/engine-qwen35-cuda/src/backend/generate_mtp/mtp_loop_steps.rs @@ -20,7 +20,7 @@ pub(super) fn begin_decoder( ) -> Result { Ok(match resume { Some(old) => { - if !append_compatible(&old.tokens, prompt) { + if !append_compatible(run.binding.input_constants().bound_cells(), &old.tokens, prompt) { return Err(invalid("resident MTP prefix mismatch").into()); } old.decoder diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_laptop.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_laptop.rs index 5337b909..4447aff2 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_laptop.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_laptop.rs @@ -146,7 +146,7 @@ fn load_experts(binding: &mut ModelBinding, start: std::time::Instant) { } /// Experimental: a process geometry of N cells instead of the trained 262144 (the Original sizes its KV by -/// --max-context). Unscaled RoPE; must precede the first CUDA context user. +/// --max-context). Unscaled RoPE; must precede the model binding (which carries it) and the first CUDA context user. fn configure_cells() { if let Ok(cells) = env::var("LELEKA_LAPTOP_CELLS") { let cells: usize = cells.parse().expect("LELEKA_LAPTOP_CELLS must be a count"); @@ -266,8 +266,8 @@ fn close_context(context: Rc>) { fn original_serve_laptop_bench() { assert!(env::var("LELEKA_LAPTOP_BENCH").is_ok_and(|v| v == "yes"), "explicit laptop bench opt-in required"); let start = std::time::Instant::now(); - let loaded = bind_laptop(start); configure_cells(); + let loaded = bind_laptop(start); let budget_gib = number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 15); let driver = Driver::load().expect("CUDA driver load failed"); let device = driver.device(0).expect("CUDA device 0 unavailable"); diff --git a/crates/engine-qwen35-cuda/src/backend/original_serve_prefix_smoke/run.rs b/crates/engine-qwen35-cuda/src/backend/original_serve_prefix_smoke/run.rs index a9c22b26..4436c534 100644 --- a/crates/engine-qwen35-cuda/src/backend/original_serve_prefix_smoke/run.rs +++ b/crates/engine-qwen35-cuda/src/backend/original_serve_prefix_smoke/run.rs @@ -44,16 +44,23 @@ fn open_archive(laptop: bool) -> InheritedKarArchive { fn load_experts(binding: &mut ModelBinding, laptop: bool) { if laptop { binding.load_mapped_expert_source().expect("mapped expert source load failed"); - if let Ok(cells) = env::var("LELEKA_LAPTOP_CELLS") { - let cells: usize = cells.parse().expect("LELEKA_LAPTOP_CELLS must be a count"); - leleka_cuda_driver::configure_serving_context(cells, &Default::default()).expect("serving context refused"); - eprintln!("PFX config: process geometry {cells} cells (experimental)"); - } } else { binding.load_resident_expert_source().expect("resident expert source load failed"); } } +/// Experimental: a process geometry of N cells (`LELEKA_LAPTOP_CELLS`). It is fixed before the model is bound, because +/// the binding carries the serving context. +fn configure_laptop_cells() { + if let Ok(cells) = env::var("LELEKA_LAPTOP_CELLS") { + let cells: usize = cells.parse().expect("LELEKA_LAPTOP_CELLS must be a count"); + leleka_cuda_driver::configure_serving_context(cells, &Default::default()).expect("serving context refused"); + eprintln!("PFX config: process geometry {cells} cells (experimental)"); + } +} fn load(laptop: bool) -> Pinned { + if laptop { + configure_laptop_cells(); + } let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0) .expect("pinned shard0 verification failed"); let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) diff --git a/crates/engine-qwen35-cuda/src/backend/serve_generate.rs b/crates/engine-qwen35-cuda/src/backend/serve_generate.rs index fc80c128..8b4c8125 100644 --- a/crates/engine-qwen35-cuda/src/backend/serve_generate.rs +++ b/crates/engine-qwen35-cuda/src/backend/serve_generate.rs @@ -154,7 +154,9 @@ fn resumable( shared: &Shared, prompt: &[u32], ) -> bool { - if entry.loaded != *loaded || !append_compatible(&entry.continuation.tokens, prompt) { + if entry.loaded != *loaded + || !append_compatible(binding.input_constants().bound_cells(), &entry.continuation.tokens, prompt) + { return false; } let resume = &entry.continuation; diff --git a/crates/engine-qwen35-cuda/src/backend/session.rs b/crates/engine-qwen35-cuda/src/backend/session.rs index d81085e9..da4aa419 100644 --- a/crates/engine-qwen35-cuda/src/backend/session.rs +++ b/crates/engine-qwen35-cuda/src/backend/session.rs @@ -16,10 +16,10 @@ pub(super) struct MtpContinuation { /// Exactly target-committed IDs, never a speculative or merely emitted ID. pub(super) tokens: Vec, } -pub(super) fn append_compatible(committed: &[u32], incoming: &[u32]) -> bool { +pub(super) fn append_compatible(serving_cells: u64, committed: &[u32], incoming: &[u32]) -> bool { !committed.is_empty() - && committed.len() as u64 <= crate::qwen_forward::contract::serving_cells() - && incoming.len() as u64 <= crate::qwen_forward::contract::serving_cells() + && committed.len() as u64 <= serving_cells + && incoming.len() as u64 <= serving_cells && incoming.starts_with(committed) } diff --git a/crates/engine-qwen35-cuda/src/model_binding/weight_binding.rs b/crates/engine-qwen35-cuda/src/model_binding/weight_binding.rs index f508fc69..6e6540df 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/weight_binding.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/weight_binding.rs @@ -72,8 +72,14 @@ impl<'a> TensorSignature<'a> { } } +/// What one binding stamps on everything built from it: the serving context in cells, fixed when the model is bound. +pub(crate) struct BindingSeal { + serving_cells: u64, +} + +/// The identity of one model binding: two identities match only when they are clones of the same one. #[derive(Clone)] -pub(crate) struct BindingIdentity(Rc<()>); +pub(crate) struct BindingIdentity(Rc); #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum BoundLayerKind { @@ -92,6 +98,8 @@ pub(crate) struct InputConstants { multipliers: [u64; 3], eos: u32, context_length: u32, + /// The serving context in cells (the bound of every `Position`), fixed when the model is bound. + serving_cells: u32, } pub(crate) struct ModelBinding { @@ -128,8 +136,8 @@ mod tests { } #[test] fn exact_model_identity_is_retained_and_not_reconstructible_from_value() { - let first = BindingIdentity(Rc::new(())); - let second = BindingIdentity(Rc::new(())); + let first = BindingIdentity::new(262_144); + let second = BindingIdentity::new(262_144); assert!(first.matches(&first.clone())); assert!(!first.matches(&second)); } diff --git a/crates/engine-qwen35-cuda/src/model_binding/weight_binding/binding_identity.rs b/crates/engine-qwen35-cuda/src/model_binding/weight_binding/binding_identity.rs index 7e64b905..cb196846 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/weight_binding/binding_identity.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/weight_binding/binding_identity.rs @@ -3,7 +3,7 @@ //! the artifact (PLE head offsets and vocabularies, EOS, context length) with their validation. use super::{ - BindingIdentity, BoundLayer, BoundLayerKind, InputBindingError, InputConstants, InputResult, PLE_ROWS, + BindingIdentity, BindingSeal, BoundLayer, BoundLayerKind, InputBindingError, InputConstants, InputResult, PLE_ROWS, Qwen4ExpArtifact, Rc, fmt, }; @@ -14,9 +14,16 @@ impl fmt::Display for InputBindingError { } impl std::error::Error for InputBindingError {} impl BindingIdentity { + pub(super) fn new(serving_cells: u64) -> Self { + Self(Rc::new(BindingSeal { serving_cells })) + } pub(crate) fn matches(&self, other: &Self) -> bool { Rc::ptr_eq(&self.0, &other.0) } + /// The serving context in cells (the bound of every `Position`) the model was bound under. + pub(crate) fn bound_cells(&self) -> u64 { + self.0.serving_cells + } } impl BoundLayer { pub(crate) fn index(&self) -> u32 { @@ -38,6 +45,8 @@ impl InputConstants { multipliers: t.ple_layer_multipliers().try_into().map_err(|_| InputBindingError::Metadata)?, eos: t.ple_eos_token_id(), context_length: t.context_length(), + serving_cells: u32::try_from(crate::qwen_forward::contract::serving_cells()) + .map_err(|_| InputBindingError::Metadata)?, }; constants.validate()?; Ok(constants) @@ -68,7 +77,11 @@ impl InputConstants { /// The serving context in cells (the bound of every `Position`): 262144 unless the process configured a /// larger one. NOT the artifact's metadata value; that is [`Self::trained_context`]. pub(crate) fn context_length(&self) -> u32 { - crate::qwen_forward::contract::serving_cells() as u32 + self.serving_cells + } + /// The same bound as `u64`, the width of a sequence position. + pub(crate) fn bound_cells(&self) -> u64 { + u64::from(self.serving_cells) } /// The context the artifact was trained over (`context_length` metadata), validated to be 262144. #[allow(dead_code)] diff --git a/crates/engine-qwen35-cuda/src/model_binding/weight_binding/model_binding.rs b/crates/engine-qwen35-cuda/src/model_binding/weight_binding/model_binding.rs index 7f268be3..2657ab87 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/weight_binding/model_binding.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/weight_binding/model_binding.rs @@ -3,8 +3,8 @@ use super::{ BindingError, BindingIdentity, BoundLayer, EMBEDDING_VALUES, GlobalRole, InputBindingError, InputConstants, - InputResult, ModelBinding, MtpWeights, PLE_ROW_VALUES, PLE_ROWS, Qwen4ExpArtifact, Rc, RefCell, TensorRole, - VOCABULARY, bind_layers, decode, mtp, validate_ple_descriptor, + InputResult, ModelBinding, MtpWeights, PLE_ROW_VALUES, PLE_ROWS, Qwen4ExpArtifact, RefCell, TensorRole, VOCABULARY, + bind_layers, decode, mtp, validate_ple_descriptor, }; use leleka_model_format::verify_stamp::VerifyPolicy; @@ -24,12 +24,13 @@ impl ModelBinding { validate_ple_descriptor(&artifact)?; let layers = bind_layers(&artifact)?; let (expert_count, expert_used_count) = bind_expert_counts(&artifact)?; + let identity = BindingIdentity::new(constants.bound_cells()); Ok(Self { artifact: RefCell::new(artifact), constants, embedding_kind, embedding_bytes, - identity: BindingIdentity(Rc::new(())), + identity, layers, expert_count, expert_used_count, diff --git a/crates/engine-qwen35-cuda/src/model_binding/weight_binding/validate_ple_descriptor.rs b/crates/engine-qwen35-cuda/src/model_binding/weight_binding/validate_ple_descriptor.rs index 6eecb9b7..7c1c1c9d 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/weight_binding/validate_ple_descriptor.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/weight_binding/validate_ple_descriptor.rs @@ -2,7 +2,7 @@ //! bound layers with their kinds. Also the test fixtures for `InputConstants` and `BindingIdentity`. #[cfg(test)] -use super::{BindingIdentity, InputConstants, Rc}; +use super::{BindingIdentity, InputConstants}; use super::{ BoundLayer, BoundLayerKind, GlobalRole, InputBindingError, InputResult, LayerRole, PLE_ROWS, Qwen4ExpArtifact, TensorRole, @@ -36,6 +36,7 @@ impl InputConstants { multipliers: [23703573157769, 20109073645365, 8052911324071], eos: 248044, context_length: 262144, + serving_cells: 262144, } } } @@ -68,6 +69,6 @@ pub(super) fn bind_layer(artifact: &Qwen4ExpArtifact, index: u32, interval: u32) #[cfg(test)] impl BindingIdentity { pub(crate) fn test_identity() -> Self { - Self(Rc::new(())) + Self::new(262_144) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/contract.rs b/crates/engine-qwen35-cuda/src/qwen_forward/contract.rs index 64e8041a..4c671279 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/contract.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/contract.rs @@ -82,7 +82,7 @@ impl Dimension { } } -/// The serving context in cells: every sequence position lies in `0..serving_cells()`. +/// The serving context in cells: every sequence position lies in `0..bound_cells()`. /// /// This is the ONE runtime context bound. It is `262144` (the trained context, the previous hard-coded pin) /// unless `crate::serving::apply_effective_context` configured the process from a resolved diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/mtp_frame.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/mtp_frame.rs index 82321638..9bc0c2bc 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/mtp_frame.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/mtp_frame.rs @@ -11,9 +11,9 @@ use super::{ }; impl MtpFrame { - fn within_bounds(&self) -> Result { + fn within_bounds(&self, serving_cells: u64) -> Result { Ok(self.token == TokenId::new(u64::from(self.token.get()), Dimension::new(248320)?)? - && self.position.get() < crate::qwen_forward::contract::serving_cells() + && self.position.get() < serving_cells && self.depth < 4) } pub(in super::super) fn validate(&self, binding: &ModelBinding, session: &QwenSession<'_>) -> Result<()> { @@ -22,7 +22,7 @@ impl MtpFrame { return Err(Error::IdentityMismatch); } binding.mtp_weights().map_err(binding_error)?.validate_binding(binding).map_err(binding_error)?; - if !self.within_bounds()? { + if !self.within_bounds(binding.input_constants().bound_cells())? { return Err(Error::IdentityMismatch); } Ok(()) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/chunk.rs index 31f5eb5a..cc56a0cf 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/chunk.rs @@ -49,17 +49,17 @@ mod tests { #[test] fn exact_transaction_row_bounds_preserve_native64_and_admit_outer256() { - assert_eq!(checked_chunk_end(170000, 64, 64), Ok(170064)); - assert_eq!(checked_chunk_end(170000, 65, 64), Err(Error::IdentityMismatch)); + assert_eq!(checked_chunk_end(170000, 64, 64, 262_144), Ok(170064)); + assert_eq!(checked_chunk_end(170000, 65, 64, 262_144), Err(Error::IdentityMismatch)); for rows in [64, 65, 256] { - assert_eq!(checked_chunk_end(190000, rows, 256), Ok(190000 + rows as u64)); + assert_eq!(checked_chunk_end(190000, rows, 256, 262_144), Ok(190000 + rows as u64)); } - assert_eq!(checked_chunk_end(190000, 257, 256), Err(Error::IdentityMismatch)); - assert_eq!(checked_chunk_end(0, 0, 64), Err(Error::IdentityMismatch)); - assert_eq!(checked_chunk_end(0, 65, 65), Err(Error::IdentityMismatch)); - assert_eq!(checked_chunk_end(u64::MAX, 1, 64), Err(Error::Overflow)); - assert_eq!(checked_chunk_end(262080, 64, 64), Ok(262144)); - assert_eq!(checked_chunk_end(262081, 64, 64), Err(Error::InvalidPosition)); + assert_eq!(checked_chunk_end(190000, 257, 256, 262_144), Err(Error::IdentityMismatch)); + assert_eq!(checked_chunk_end(0, 0, 64, 262_144), Err(Error::IdentityMismatch)); + assert_eq!(checked_chunk_end(0, 65, 65, 262_144), Err(Error::IdentityMismatch)); + assert_eq!(checked_chunk_end(u64::MAX, 1, 64, 262_144), Err(Error::Overflow)); + assert_eq!(checked_chunk_end(262080, 64, 64, 262_144), Ok(262144)); + assert_eq!(checked_chunk_end(262081, 64, 64, 262_144), Err(Error::InvalidPosition)); } #[test] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/chunk/checked_chunk_end.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/chunk/checked_chunk_end.rs index 5c5a9210..32fbbe6b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/chunk/checked_chunk_end.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/chunk/checked_chunk_end.rs @@ -8,21 +8,21 @@ use super::{ ValidatedWarmEnd, }; -pub(super) fn checked_chunk_end(start: u64, rows: usize, limit: usize) -> Result { +pub(super) fn checked_chunk_end(start: u64, rows: usize, limit: usize, serving_cells: u64) -> Result { if !matches!(limit, 64 | 256) || rows == 0 || rows > limit { return Err(Error::IdentityMismatch); } let end = start.checked_add(u64::try_from(rows).map_err(|_| Error::Overflow)?).ok_or(Error::Overflow)?; - if end > crate::qwen_forward::contract::serving_cells() { + if end > serving_cells { return Err(Error::InvalidPosition); } Ok(end) } impl ValidatedWarmEnd { - pub(super) fn from_txn(txn: &QwenChunkTxn<'_, '_>) -> Result { + pub(super) fn from_txn(txn: &QwenChunkTxn<'_, '_>, serving_cells: u64) -> Result { let start = txn.start_position(); let rows = txn.rows(); - let end = checked_chunk_end(start, rows.len(), txn.warm_row_limit())?; + let end = checked_chunk_end(start, rows.len(), txn.warm_row_limit(), serving_cells)?; if end != txn.end_position() { return Err(Error::IdentityMismatch); } @@ -49,7 +49,7 @@ impl MtpSession { binding: &ModelBinding, txn: &QwenChunkTxn<'_, '_>, ) -> Result> { - let bound = ValidatedWarmEnd::from_txn(txn)?; + let bound = ValidatedWarmEnd::from_txn(txn, binding.input_constants().bound_cells())?; let target = txn.original_session()?; let start = Position::new(txn.start_position(), crate::qwen_forward::contract::position_dimension())?; binding @@ -72,7 +72,7 @@ impl MtpSession { anchor: TargetStepOrigin, start: Position, ) -> Result> { - let end = checked_chunk_end(start.get(), 64, 64)?; + let end = checked_chunk_end(start.get(), 64, 64, 262_144)?; self.stage_chunk_with_end(target, anchor, start, ValidatedWarmEnd(end)) } pub(super) fn stage_chunk_with_end<'a>( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/dense_kv.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/dense_kv.rs index d00ef22e..cd95e4b4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/dense_kv.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/dense_kv.rs @@ -15,7 +15,7 @@ impl DenseKv { || !Rc::ptr_eq(&self.owner, &frame.epoch) || frame.generation != frame.epoch.get() || frame.position.get() != self.next_position - || self.next_position >= crate::qwen_forward::contract::serving_cells() + || self.next_position >= self.binding.bound_cells() { return Err(Error::IdentityMismatch); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/prefix_draft_snapshot.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/prefix_draft_snapshot.rs index c2ef55a6..44422f37 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/prefix_draft_snapshot.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/prefix_draft_snapshot.rs @@ -65,7 +65,7 @@ impl MtpSession { || !Rc::ptr_eq(&self.kv.owner, &self.epoch) || self.kv.next_position != self.next_position || self.next_position == 0 - || self.next_position > crate::qwen_forward::contract::serving_cells() + || self.next_position > binding.input_constants().bound_cells() || self.target_owner.as_ref().is_none_or(|old| !old.same_session(¤t.origin)) { return Err(Error::IdentityMismatch); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/warming.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/warming.rs index ae61a8d7..9d8d32ce 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/warming.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/state/warming.rs @@ -34,7 +34,7 @@ impl MtpKvPrefill { original: &MtpSession, tokens: &[TokenId], ) -> Result { - Self::admit_tokens(tokens)?; + Self::admit_tokens(tokens, binding.input_constants().bound_cells())?; binding.mtp_weights().map_err(mtp::binding_error)?.validate_binding(binding).map_err(mtp::binding_error)?; let anchor = target.target_origin()?; anchor.validate(target)?; @@ -46,8 +46,8 @@ impl MtpKvPrefill { owner.validate_original(binding, original, target)?; Ok(owner) } - fn admit_tokens(tokens: &[TokenId]) -> Result<()> { - if tokens.len() < 2 || tokens.len() as u64 > crate::qwen_forward::contract::serving_cells() { + fn admit_tokens(tokens: &[TokenId], serving_cells: u64) -> Result<()> { + if tokens.len() < 2 || tokens.len() as u64 > serving_cells { return Err(Error::InvalidDimension); } let vocab = Dimension::new(248320)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/attention_stage.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/attention_stage.rs index 7312adca..d43830b6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/attention_stage.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/attention_stage.rs @@ -85,7 +85,7 @@ fn admit_run<'a, 'd>( input.frame().validate(binding, session)?; let prior = draft.prior(input.frame())?; validate_read_values(input)?; - let geometry = geometry(input.frame().position().get())?; + let geometry = geometry(input.frame().position().get(), binding.input_constants().bound_cells())?; check_roles( binding, &[ @@ -198,7 +198,7 @@ pub(in super::super) fn produce_kv_cell( ) -> Result { input.frame().validate(binding, session)?; validate_read_values(input)?; - let geometry = geometry(input.frame().position().get())?; + let geometry = geometry(input.frame().position().get(), binding.input_constants().bound_cells())?; check_roles( binding, &[ diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/dense_geometry.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/dense_geometry.rs index 09552f82..3484991a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/dense_geometry.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/dense_geometry.rs @@ -8,8 +8,8 @@ use super::{ validate_values, }; -pub(super) fn geometry(position: u64) -> Result { - if position >= crate::qwen_forward::contract::serving_cells() { +pub(super) fn geometry(position: u64, serving_cells: u64) -> Result { + if position >= serving_cells { return Err(Error::InvalidPosition); } let position = u32::try_from(position).map_err(|_| Error::InvalidPosition)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/reuse_gpu_tests/phases.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/reuse_gpu_tests/phases.rs index 4ba4a4d3..ff55f60a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/reuse_gpu_tests/phases.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/reuse_gpu_tests/phases.rs @@ -23,7 +23,7 @@ pub(super) struct Tiny { impl Tiny { pub(super) fn new() -> Self { let (keys, values) = half_kv(1, false); - Self { query: vec![0.125; Q], gate: vec![0.25; Q], keys, values, shape: geometry(0).unwrap() } + Self { query: vec![0.125; Q], gate: vec![0.25; Q], keys, values, shape: geometry(0, 262_144).unwrap() } } /// The one-cell key and value window. fn window(&self) -> KvWindow<'_> { @@ -47,7 +47,7 @@ fn pair_inputs(zero: bool) -> (Vec, Vec) { impl<'c> Env<'c> { fn pair_case(&self, matrix: &DeviceBuffer<'_>, position: u32, zero: bool) { let context = self.context; - let shape = geometry(u64::from(position)).unwrap(); + let shape = geometry(u64::from(position), 262_144).unwrap(); let (query, gate) = pair_inputs(zero); let (query_bits, gate_bits) = (bits(&query), bits(&gate)); let (keys, values) = half_kv(shape.width, zero); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/tests.rs index 8e0eb2e1..72db5e31 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/tests.rs @@ -14,17 +14,17 @@ fn mtp_attention_new_causal_geometry_and_budget_boundaries() { (32768, 32768, 33554432, 12681472), (262143, 32768, 33554432, 12681472), ] { - let g = geometry(position).unwrap(); + let g = geometry(position, 262_144).unwrap(); assert_eq!((g.width, g.half_bytes, g.scratch), (width, half_bytes, scratch)); assert_eq!(g.device_bytes, 2 * half_bytes + scratch + 49152 + 2097152); } - for position in [crate::qwen_forward::contract::serving_cells(), u32::MAX as u64, u64::MAX] { - assert!(matches!(geometry(position), Err(Error::InvalidPosition))); + for position in [262_144, u32::MAX as u64, u64::MAX] { + assert!(matches!(geometry(position, 262_144), Err(Error::InvalidPosition))); } } #[test] fn mtp_attention_new_window_shape_halfdomains_and_caller_preservation() { - let g = geometry(0).unwrap(); + let g = geometry(0, 262_144).unwrap(); let mut keys = vec![0u8; 1024]; let mut values = vec![0u8; 1024]; for (i, word) in [0x0001u16, 0x8000, 0x0400, 0x7bff].into_iter().enumerate() { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode.rs index 30fd5619..8a5646ca 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode.rs @@ -60,12 +60,12 @@ mod tests { #[test] fn window_never_exceeds_remaining_or_last_target_position() { - assert_eq!(window_limit(0, 4, 9), Ok(4)); - assert_eq!(window_limit(0, 4, 2), Ok(2)); - assert_eq!(window_limit(262140, 4, 9), Ok(3)); - assert_eq!(window_limit(262142, 4, 9), Ok(1)); - assert_eq!(window_limit(262143, 4, 9), Err(Error::InvalidPosition)); - assert_eq!(window_limit(u64::MAX, 4, 9), Err(Error::Overflow)); + assert_eq!(window_limit(0, 4, 9, 262_144), Ok(4)); + assert_eq!(window_limit(0, 4, 2, 262_144), Ok(2)); + assert_eq!(window_limit(262140, 4, 9, 262_144), Ok(3)); + assert_eq!(window_limit(262142, 4, 9, 262_144), Ok(1)); + assert_eq!(window_limit(262143, 4, 9, 262_144), Err(Error::InvalidPosition)); + assert_eq!(window_limit(u64::MAX, 4, 9, 262_144), Err(Error::Overflow)); } } @@ -92,7 +92,7 @@ mod draft_bound_tests { for position in [0, 262140, 262142] { for depth in 1..=4 { for remaining in 1..=6 { - let limit = window_limit(position, depth, remaining).unwrap(); + let limit = window_limit(position, depth, remaining, 262_144).unwrap(); assert_capacity_cases(&predictions, limit); } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/first_seed_reuse_enabled.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/first_seed_reuse_enabled.rs index b5aff2b2..8a5e1711 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/first_seed_reuse_enabled.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/first_seed_reuse_enabled.rs @@ -25,9 +25,9 @@ pub(super) fn needed_draft_predictions(capacity: usize, limit: usize) -> Result< capacity.min(limit).checked_sub(1).ok_or(Error::Overflow) } -pub(super) fn window_limit(position: u64, depth: usize, remaining: usize) -> Result { +pub(super) fn window_limit(position: u64, depth: usize, remaining: usize, serving_cells: u64) -> Result { let next = position.checked_add(1).ok_or(Error::Overflow)?; - let available = crate::qwen_forward::contract::serving_cells().checked_sub(next).ok_or(Error::InvalidPosition)?; + let available = serving_cells.checked_sub(next).ok_or(Error::InvalidPosition)?; let limit = depth.min(remaining).min(usize::try_from(available).map_err(|_| Error::Overflow)?); if limit == 0 { Err(Error::InvalidPosition) } else { Ok(limit) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/batched_window.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/batched_window.rs index 86f1f904..df384c62 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/batched_window.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/batched_window.rs @@ -55,7 +55,7 @@ impl MtpDecoder { return Ok(Err(eos)); } self.require_batched_admission(cache)?; - let limit = window_limit(source_position, spec.depth, spec.remaining)?; + let limit = window_limit(source_position, spec.depth, spec.remaining, binding.input_constants().bound_cells())?; Ok(Ok(self.batched_sizing(request, target, cache, WindowHead { first, limit })?)) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/decoder_entry.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/decoder_entry.rs index 63900082..110b134b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/decoder_entry.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/decoder_entry.rs @@ -18,11 +18,12 @@ impl MtpDecoder { if prompt.len() == 1 { return Ok(decoder); } - if !(2..=crate::qwen_forward::contract::serving_cells() as usize).contains(&prompt.len()) { + let serving_cells = binding.input_constants().bound_cells(); + if !(2..=serving_cells as usize).contains(&prompt.len()) { return Err(Error::InvalidDimension); } // Admit this persistent baseline before allocating the owner/queue. - let host_charge = kv_prefill_host_charge(prompt.len())?; + let host_charge = kv_prefill_host_charge(prompt.len(), serving_cells)?; if host_charge > 512 * 1024 * 1024 { return Err(Error::InputAllocation); } @@ -67,7 +68,7 @@ impl MtpDecoder { ) -> Result<()> { let (token, position, _, origin) = source.mtp_source(binding, target)?; if committed.is_empty() - || committed.len() as u64 > crate::qwen_forward::contract::serving_cells() + || committed.len() as u64 > binding.input_constants().bound_cells() || position.get().checked_add(1) != Some(committed.len() as u64) || committed.last().copied() != Some(token.get()) { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/scalar_window.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/scalar_window.rs index f7572575..0824f0a5 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/scalar_window.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_decoder/scalar_window.rs @@ -67,7 +67,7 @@ fn scalar_start( if Some(first) == spec.eos { return Ok(Err(true)); } - let limit = window_limit(source_position, spec.depth, spec.remaining)?; + let limit = window_limit(source_position, spec.depth, spec.remaining, binding.input_constants().bound_cells())?; Ok(Ok((first, source_position, limit))) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_window_spec.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_window_spec.rs index 5a7aa4a3..f6d1498e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_window_spec.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/mtp_window_spec.rs @@ -38,8 +38,8 @@ impl MtpVerifiedWindow { // Conservative charge separate from the transaction's existing 98MiB MTP // temporaries: actual 64MiB payload, cell/allocator metadata, three bounded // pointer vectors, and conversion Vec + immutable actual whole-prompt Box. -pub(super) fn kv_prefill_host_charge(prompt_len: usize) -> Result { - if !(2..=crate::qwen_forward::contract::serving_cells() as usize).contains(&prompt_len) { +pub(super) fn kv_prefill_host_charge(prompt_len: usize, serving_cells: u64) -> Result { + if !(2..=serving_cells as usize).contains(&prompt_len) { return Err(Error::InvalidDimension); } (64usize * 1024 * 1024) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine.rs index a421a8ab..c096a558 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine.rs @@ -10,7 +10,7 @@ use super::contract::{Error, Result}; use super::original_spec_adaptive::AdaptiveConfig; use super::original_spec_controller::{ - NanGuard, OriginalSpecController, OriginalSpecEngine, SpecConfig, SpecError, SpecWindow, + NanGuard, OriginalSpecController, OriginalSpecEngine, SpecConfig, SpecContext, SpecError, SpecWindow, }; use super::original_spec_draft::{DraftPick, OriginalDraftEngine, OriginalFirstDraftEngine, TargetSeedRow}; use super::original_spec_policy::MAX_T; @@ -164,6 +164,8 @@ pub(crate) struct OriginalServeSettings { pub(crate) max_t: usize, pub(crate) mtp_max_t: usize, pub(crate) max_context: i64, + /// The serving cells of the model binding the settings are made for (the bound of every cell position). + pub(crate) serving_cells: i64, pub(crate) vocabulary: u32, pub(crate) suffix_min_match: usize, pub(crate) coupled: bool, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/env_tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/env_tests.rs index 2eed6bf0..92891e56 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/env_tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/env_tests.rs @@ -4,12 +4,18 @@ use super::super::original_spec_adaptive::{AdaptiveConfig, FLOOR_CEILING_LEGACY}; use super::super::original_spec_controller::NanGuard; use super::{MAX_T, OriginalServeSettings}; +use crate::qwen_forward::original_spec_controller::SpecContext; use crate::settings::MapEnv; const VOCAB: u32 = 1000; +/// The context of an unconfigured process, with the usual 4096-token ceiling. +fn ctx() -> SpecContext { + SpecContext::trained(4096) +} + fn engine(pairs: &[(&str, &str)]) -> OriginalServeSettings { - OriginalServeSettings::from_environment(4096, VOCAB, false, &MapEnv::of(pairs)) + OriginalServeSettings::from_environment(ctx(), VOCAB, false, &MapEnv::of(pairs)) } #[test] @@ -114,7 +120,7 @@ fn the_legacy_policy_lowers_the_ceiling_before_an_explicit_ceiling_overrides_it( fn arms(list: &str) -> Vec<(String, OriginalServeSettings)> { let env = MapEnv::of(&[("LELEKA_SPEC_ARMS", list)]); - OriginalServeSettings::arms_from_environment(4096, VOCAB, false, &env) + OriginalServeSettings::arms_from_environment(ctx(), VOCAB, false, &env) } fn arm_labels(list: &str) -> Vec { @@ -124,7 +130,7 @@ fn arm_labels(list: &str) -> Vec { #[test] #[rustfmt::skip] fn the_arm_list_builds_one_setting_per_known_arm() { - assert!(OriginalServeSettings::arms_from_environment(4096, VOCAB, false, &MapEnv::new()).is_empty()); + assert!(OriginalServeSettings::arms_from_environment(ctx(), VOCAB, false, &MapEnv::new()).is_empty()); assert_eq!(arm_labels("fixed3, fixed6 ,adaptive@0.5,bogus,"), ["fixed3", "fixed6", "adaptive@0.5"]); let fixed = arms("fixed3").remove(0).1; assert_eq!((fixed.max_t, fixed.mtp_max_t, fixed.suffix_min_match, fixed.adaptive), (5, 3, 3, None)); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/round_tally.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/round_tally.rs index 2e576a2b..82013f81 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/round_tally.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/round_tally.rs @@ -5,7 +5,7 @@ use super::{ ADAPTIVE_DEFAULT, AdaptiveConfig, CommittedWindow, DraftCompletion, DraftLimits, DraftPick, DraftStage, EnvSource, Error, FirstDraftSeed, FirstStage, MAX_T, NanGuard, OriginalFirstDraftEngine, OriginalServeEngine, OriginalServePort, OriginalServeSettings, OriginalSpecController, OriginalSpecEngine, Result, ServeOutcome, - ServeStop, SpecConfig, SpecError, SpecWindow, TracePort, + ServeStop, SpecConfig, SpecContext, SpecError, SpecWindow, TracePort, }; /// The produced-token and round counters of one served request, and why it stopped if a round decided that. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/round_tally/original_serve_settings.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/round_tally/original_serve_settings.rs index a9325d3c..8bfed56c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/round_tally/original_serve_settings.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/round_tally/original_serve_settings.rs @@ -4,17 +4,19 @@ use super::{ ADAPTIVE_DEFAULT, AdaptiveConfig, EnvSource, MAX_T, NanGuard, OriginalServeSettings, OriginalSpecController, - OriginalSpecEngine, Result, RoundTally, ServeOutcome, ServeStop, SpecConfig, SpecError, SpecWindow, serve_rounds, + OriginalSpecEngine, Result, RoundTally, ServeOutcome, ServeStop, SpecConfig, SpecContext, SpecError, SpecWindow, + serve_rounds, }; impl OriginalServeSettings { - pub(crate) fn mode17(max_context: i64, vocabulary: u32, coupled: bool) -> Self { + pub(crate) fn mode17(context: SpecContext, vocabulary: u32, coupled: bool) -> Self { const SPEC: usize = 4; const SUFFIX: usize = 3; Self { max_t: (SPEC + 2).min(MAX_T), mtp_max_t: SPEC, - max_context, + max_context: context.max_context, + serving_cells: context.serving_cells, vocabulary, suffix_min_match: SUFFIX, coupled, @@ -29,9 +31,9 @@ impl OriginalServeSettings { /// `LELEKA_SPEC_ADAPTIVE=on` (adaptive window; widest window `LELEKA_SPEC_ADAPTIVE_MAX_T`, default 8 rows, MTP /// chain up /// to `max_t - 1` drafts). Unset = mode17 exactly. - pub(crate) fn from_environment(max_context: i64, vocabulary: u32, coupled: bool, env: &impl EnvSource) -> Self { + pub(crate) fn from_environment(context: SpecContext, vocabulary: u32, coupled: bool, env: &impl EnvSource) -> Self { let num = |name: &str| env.get(name).and_then(|v| v.trim().parse::().ok()); - let mut s = Self::mode17(max_context, vocabulary, coupled); + let mut s = Self::mode17(context, vocabulary, coupled); s.nan_guard = NanGuard::from_environment(env); if let Some(spec) = num("LELEKA_SPEC") { let spec = spec.clamp(2, MAX_T); @@ -72,13 +74,13 @@ impl OriginalServeSettings { /// the /// adaptive window; the verifier is built for the widest arm. Empty when unset. pub(crate) fn arms_from_environment( - max_context: i64, + context: SpecContext, vocabulary: u32, coupled: bool, env: &impl EnvSource, ) -> Vec<(String, Self)> { let Some(list) = env.get("LELEKA_SPEC_ARMS") else { return Vec::new() }; - let base = Self::from_environment(max_context, vocabulary, coupled, env); + let base = Self::from_environment(context, vocabulary, coupled, env); let mut arms = Vec::new(); for entry in list.split(',').map(str::trim).filter(|l| !l.is_empty()) { if let Some(arm) = base.arm(entry, env) { @@ -166,7 +168,7 @@ impl OriginalServeSettings { OriginalSpecController::new( SpecConfig::new( SpecWindow { max_t: self.max_t, mtp_max_t: self.mtp_max_t }, - self.max_context, + SpecContext { max_context: self.max_context, serving_cells: self.serving_cells }, self.vocabulary, self.suffix_min_match, self.coupled, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests.rs index 9b31660b..e3c3af89 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests.rs @@ -263,7 +263,7 @@ fn run_request(skew: i32, max_t: usize, max_new: usize) -> (Vec, Vec OriginalServeSettings { max_t: 4, mtp_max_t: 0, max_context, + serving_cells: 262_144, vocabulary: VOCAB, suffix_min_match: 0, coupled: false, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/restore_attempts_do_not_depend.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/restore_attempts_do_not_depend.rs index 098dc35b..59417272 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/restore_attempts_do_not_depend.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/restore_attempts_do_not_depend.rs @@ -7,6 +7,7 @@ use super::{ ServeStop, SpecConfig, SpecError, SpecWindow, SpeculativeRequest, VOCAB, VerifiedWindow, engine, events, idx, model, prompt, prompt_long, run_request, seed_row, serve, serve_in, }; +use crate::qwen_forward::original_spec_controller::SpecContext; #[test] fn restore_attempts_do_not_depend_on_engine_health_and_reset_draft_state() { @@ -116,7 +117,7 @@ fn controller_both_restores_run_when_the_verifier_fails() { let (f, w) = Fake::new(&p); let mut e = OriginalServeEngine::new(f, VOCAB, 4, 3).unwrap(); let mut c = OriginalSpecController::new( - SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 0 }, 4096, VOCAB, 0, false).unwrap(), + SpecConfig::new_trained(SpecWindow { max_t: 4, mtp_max_t: 0 }, 4096, VOCAB, 0, false).unwrap(), ) .unwrap(); c.begin_request(&p, 8, 0.0, &[]).unwrap(); @@ -136,7 +137,7 @@ fn preparation_drives_the_engine_through_after_verified() { let mut v = e.verify(2, &[a], &p[..2]).unwrap(); let outs = e.outputs(&v).to_vec(); e.commit_verified(&mut v, 1).unwrap(); - let prep = DraftPreparation::new(4, 3, VOCAB).unwrap(); + let prep = DraftPreparation::new(4, 3, VOCAB, 262_144).unwrap(); let batch = prep .after_verified( &mut e, @@ -167,7 +168,7 @@ fn the_adaptive_window_is_selected_by_the_explicit_switch_then_by_a_fixed_spec_t #[test] fn a_window_cap_narrows_every_bound_and_leaves_the_rest() { - let mut wide = OriginalServeSettings::mode17(4096, VOCAB, true); + let mut wide = OriginalServeSettings::mode17(SpecContext::trained(4096), VOCAB, true); wide.max_t = 8; wide.mtp_max_t = 8; wide.adaptive = Some(AdaptiveConfig::new(8, 7)); @@ -187,7 +188,7 @@ fn a_window_cap_narrows_every_bound_and_leaves_the_rest() { } // a cap above the settings changes nothing; a fixed window narrower than the cap keeps its own width assert_eq!(wide.with_window_cap(8), wide); - let fixed = OriginalServeSettings::mode17(4096, VOCAB, false); + let fixed = OriginalServeSettings::mode17(SpecContext::trained(4096), VOCAB, false); assert_eq!(fixed.with_window_cap(8), fixed); let narrow = fixed.with_window_cap(3); assert_eq!((narrow.max_t, narrow.mtp_max_t, narrow.max_drafts()), (3, 3, 2)); @@ -204,7 +205,7 @@ fn assert_controller_and_engine_accept(s: &OriginalServeSettings, cap: usize) { #[test] fn mode17_settings_follow_generate_defaults() { - let s = OriginalServeSettings::mode17(4096, VOCAB, false); + let s = OriginalServeSettings::mode17(SpecContext::trained(4096), VOCAB, false); assert_eq!((s.max_t, s.mtp_max_t, s.suffix_min_match), (6, 4, 3)); assert_eq!(s.max_drafts(), 3); // the drafter is loaded at the verify width (6), not at its own window width (4): suffix windows are 6 rows wide diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/stack.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/stack.rs index c57ae8e1..bf2422bd 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/stack.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/stack.rs @@ -11,6 +11,7 @@ use crate::qwen_forward::contract::Error; use crate::qwen_forward::original_serve_engine::{ OriginalServeEngine, OriginalServeSettings, ServeCallbacks, ServeOutcome, SpeculativeRequest, serve_request, }; +use crate::qwen_forward::original_spec_controller::SpecContext; use crate::qwen_forward::original_spec_controller::{OriginalSpecController, SpecError}; use leleka_obs::time::{Clock, ManualClock}; @@ -49,8 +50,10 @@ pub(crate) struct FakeStack { impl FakeStack { /// A stack over `dev`, with the cross-session prefix cache on a `GRID` grid when `prefix` is set. pub(crate) fn new(dev: FakeDevice, clock: ManualClock, prefix: bool) -> Self { - let settings = - OriginalServeSettings { suffix_min_match: 0, ..OriginalServeSettings::mode17(4096, VOCAB, false) }; + let settings = OriginalServeSettings { + suffix_min_match: 0, + ..OriginalServeSettings::mode17(SpecContext::trained(4096), VOCAB, false) + }; let cache = prefix.then(|| { let cfg = PrefixConfig { block_tokens: GRID, ..PrefixConfig::auto() }; PrefixServe::new(cfg, 1024, 1 << 30, "fake").with_clock(clock.clone().into()) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_config.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_config.rs index 74892860..3baae87a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_config.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_config.rs @@ -62,16 +62,15 @@ impl StackConfig { fn capacity_invalid(&self) -> bool { !ADMITTED_CAPACITIES.contains(&self.capacity) || self.kv_footprint().is_none() || self.capacity > 8192 } - fn context_invalid(&self) -> bool { - self.max_context < 1 - || self.max_context as u64 > super::super::contract::serving_cells() - || !(1..=64).contains(&self.cpu_workers) + fn context_invalid(&self, serving_cells: u64) -> bool { + self.max_context < 1 || self.max_context as u64 > serving_cells || !(1..=64).contains(&self.cpu_workers) } - pub(crate) fn validate(&self) -> Result<()> { + /// `serving_cells`: the serving context of the binding the stack is opened over (the ceiling of `max_context`). + pub(crate) fn validate(&self, serving_cells: u64) -> Result<()> { if self.kv_format != KvFormat::Int8 { return Err(Error::Unsupported(super::super::contract::Stage::Session)); } - if self.capacity_invalid() || self.context_invalid() { + if self.capacity_invalid() || self.context_invalid(serving_cells) { return Err(Error::InvalidDimension); } if let Some(conversation) = &self.conversation { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/open_phase_steps.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/open_phase_steps.rs index 74e37f21..42bd0e7f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/open_phase_steps.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/open_phase_steps.rs @@ -39,7 +39,7 @@ pub(super) fn check_open<'ctx>( config: &StackConfig, ) -> std::result::Result<(), ServeFailure> { crate::bringup_trace!("DBG[{:.0}s] OriginalServeStack::open begin", dbg_el()); - config.validate().map_err(at("config.validate"))?; + config.validate(binding.input_constants().bound_cells()).map_err(at("config.validate"))?; // generate.cpp: qsa_set_kv_resident before any QSA state exists (every streamed owner sizes from it) leleka_cuda_driver::configure_kv_resident(config.kv_resident).map_err(|_| ServeFailure { error: Error::InvalidDimension, @@ -77,17 +77,17 @@ fn check_model_shape(binding: &ModelBinding) -> std::result::Result<(), ServeFai } /// The window policies the environment names: the first arm is live, the rest are parked with their controllers. -pub(super) fn serve_policies(config: &StackConfig) -> std::result::Result { +pub(super) fn serve_policies(config: &StackConfig, serving_cells: u64) -> std::result::Result { let env = crate::settings::process().env(); - let mut settings = OriginalServeSettings::from_environment(config.max_context, VOCABULARY, config.coupled, env); + let context = crate::qwen_forward::original_spec_controller::SpecContext::new(config.max_context, serving_cells); + let mut settings = OriginalServeSettings::from_environment(context, VOCABULARY, config.coupled, env); let mut arm_label = String::from("env"); - let arm_order: Vec = - OriginalServeSettings::arms_from_environment(config.max_context, VOCABULARY, config.coupled, env) - .into_iter() - .map(|(l, _)| l) - .collect(); + let arm_order: Vec = OriginalServeSettings::arms_from_environment(context, VOCABULARY, config.coupled, env) + .into_iter() + .map(|(l, _)| l) + .collect(); let mut parked = Vec::new(); - let arms = OriginalServeSettings::arms_from_environment(config.max_context, VOCABULARY, config.coupled, env); + let arms = OriginalServeSettings::arms_from_environment(context, VOCABULARY, config.coupled, env); let verifier_max_t = arms.iter().map(|(_, s)| s.max_t).chain([settings.max_t]).max().unwrap_or(settings.max_t); if let Some(((label, first), rest)) = arms.split_first() { settings = *first; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_open/assemble.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_open/assemble.rs index 762f9f38..89ac2ba9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_open/assemble.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_open/assemble.rs @@ -33,9 +33,8 @@ pub(super) struct Assembly<'a, 'ctx> { /// The cell count, the window policies, the RoPE constants, the expert blob sizes and formats and the prefill layout, /// in the order `open` computed them. pub(super) fn prepare(binding: &ModelBinding, config: &StackConfig) -> std::result::Result { - let max_cells = - usize::try_from(crate::qwen_forward::contract::serving_cells()).map_err(|_| failure(Error::Overflow))?; - let policies = serve_policies(config)?; + let max_cells = usize::try_from(binding.input_constants().bound_cells()).map_err(|_| failure(Error::Overflow))?; + let policies = serve_policies(config, binding.input_constants().bound_cells())?; let rope = RopeConstants::from_serving_context(); let blobs = ExpertBlobSizes::from_binding(binding).map_err(at("ExpertBlobSizes::from_binding"))?; let formats = expert_formats(binding).map_err(at("expert_formats"))?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_prefill_phase.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_prefill_phase.rs index 27b2dd32..2e78bde1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_prefill_phase.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/stack_phases/original_serve_stack_prefill_phase.rs @@ -236,7 +236,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { let (options, reread_to) = self.prompt_options(resume)?; let capacity = self.config.capacity; let plan = PromptPlan::new_in_context( - crate::qwen_forward::contract::serving_cells(), + self.binding.input_constants().bound_cells(), tokens, ResumePoint { resume, reread_to }, None, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/tests.rs index 8031996a..f875782f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/tests.rs @@ -32,15 +32,15 @@ fn the_default_chunk_is_an_admitted_capacity_and_validation_follows_the_prefill_ let config = StackConfig::new(4096); assert!(ADMITTED_CAPACITIES.contains(&config.capacity)); for capacity in [256usize, 1024, 8192] { - assert!(StackConfig { capacity, ..config.clone() }.validate().is_ok(), "{capacity}"); + assert!(StackConfig { capacity, ..config.clone() }.validate(262_144).is_ok(), "{capacity}"); } for capacity in [0usize, 255, 300, 16384, 32768] { - assert!(StackConfig { capacity, ..config.clone() }.validate().is_err(), "{capacity}"); + assert!(StackConfig { capacity, ..config.clone() }.validate(262_144).is_err(), "{capacity}"); } - assert!(StackConfig { max_context: 0, ..config.clone() }.validate().is_err()); - assert!(StackConfig { cpu_workers: 0, ..config.clone() }.validate().is_err()); - assert!(StackConfig { cpu_workers: 65, ..config.clone() }.validate().is_err()); - assert!(StackConfig { max_context: i64::MAX, ..config }.validate().is_err()); + assert!(StackConfig { max_context: 0, ..config.clone() }.validate(262_144).is_err()); + assert!(StackConfig { cpu_workers: 0, ..config.clone() }.validate(262_144).is_err()); + assert!(StackConfig { cpu_workers: 65, ..config.clone() }.validate(262_144).is_err()); + assert!(StackConfig { max_context: i64::MAX, ..config }.validate(262_144).is_err()); } #[test] @@ -52,8 +52,8 @@ fn the_conversation_cache_is_on_by_default_with_the_original_settings() { (6, 16_384, 2048) ); assert_eq!(conversation.turn_token, Some(TURN_TOKEN)); - assert!(config.validate().is_ok()); - assert!(StackConfig { conversation: None, ..config }.validate().is_ok(), "the cache can be turned off"); + assert!(config.validate(262_144).is_ok()); + assert!(StackConfig { conversation: None, ..config }.validate(262_144).is_ok(), "the cache can be turned off"); } #[test] @@ -62,12 +62,12 @@ fn kv_defaults_to_the_production_int8_window_and_refuses_unported_formats() { assert_eq!((config.kv_format, config.kv_resident), (KvFormat::Int8, 32_768)); assert_eq!(config.kv_footprint().map(|f| f.resident_pages), Some(8192)); for kv_resident in [0usize, 1, 20_480, 40_000, 262_144] { - assert!(StackConfig { kv_resident, ..config.clone() }.validate().is_ok(), "{kv_resident}"); + assert!(StackConfig { kv_resident, ..config.clone() }.validate(262_144).is_ok(), "{kv_resident}"); } - assert!(StackConfig { kv_resident: 524_292, ..config.clone() }.validate().is_err()); + assert!(StackConfig { kv_resident: 524_292, ..config.clone() }.validate(262_144).is_err()); for kv_format in [KvFormat::Fp16, KvFormat::Q4_0, KvFormat::K8V4, KvFormat::Int8Keyless] { assert_eq!( - StackConfig { kv_format, ..config.clone() }.validate(), + StackConfig { kv_format, ..config.clone() }.validate(262_144), Err(Error::Unsupported(crate::qwen_forward::contract::Stage::Session)) ); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller.rs index 8d83ed9f..519f4a88 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller.rs @@ -75,10 +75,32 @@ struct WindowFailure<'a> { error: Error, attempt: &'a mut u32, } +/// The context a speculative run is bound by: the request ceiling (`--max-context`) and the serving cells of the +/// model binding it runs over (the bound of every cell position). +#[derive(Clone, Copy, Debug)] +pub(crate) struct SpecContext { + pub(crate) max_context: i64, + pub(crate) serving_cells: i64, +} +impl SpecContext { + pub(crate) const fn new(max_context: i64, serving_cells: u64) -> Self { + Self { max_context, serving_cells: serving_cells as i64 } + } + /// The request ceiling is at least one cell and no larger than the serving cells. + pub(crate) const fn is_servable(&self) -> bool { + self.max_context >= 1 && self.max_context <= self.serving_cells + } + /// The context of an unconfigured process: the 262144 trained cells. + #[cfg(test)] + pub(crate) const fn trained(max_context: i64) -> Self { + Self::new(max_context, 262_144) + } +} pub(crate) struct SpecConfig { max_t: usize, mtp_t: usize, max_context: i64, + serving_cells: i64, vocabulary: u32, suffix_min_match: usize, coupled: bool, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/finish_round_steps.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/finish_round_steps.rs index 1885f338..0f230a6d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/finish_round_steps.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/finish_round_steps.rs @@ -173,7 +173,8 @@ impl OriginalSpecController { Ok(()) }; self.chain_clamped = clamped; - let preparation = DraftPreparation::new(self.config.max_t, chain, self.config.vocabulary); + let preparation = + DraftPreparation::new(self.config.max_t, chain, self.config.vocabulary, self.config.serving_cells); match (planned, preparation) { (Err(e), _) | (_, Err(e)) => Err(e.into()), (Ok(()), Ok(preparation)) => draft_batch(engine, round, r, (preparation, floor, self.config.coupled)), diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests.rs index c447f0a2..370828f0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests.rs @@ -190,7 +190,7 @@ impl Fake { } fn config(max_t: usize, mtp: usize, suffix: usize) -> SpecConfig { - SpecConfig::new(SpecWindow { max_t: max_t, mtp_max_t: mtp }, 4096, VOCAB, suffix, false).unwrap() + SpecConfig::new_trained(SpecWindow { max_t: max_t, mtp_max_t: mtp }, 4096, VOCAB, suffix, false).unwrap() } fn prompt(n: usize) -> Vec { let mut v = vec![11]; @@ -247,7 +247,8 @@ fn run_to_the_end( let EndRunSetup { max_t, mtp, suffix, adaptive } = setup; let p = prompt(prompt_len); let mut e = Fake::new(&p[..prompt_len - 1]); - let mut cfg = SpecConfig::new(SpecWindow { max_t: max_t, mtp_max_t: mtp }, 64, VOCAB, suffix, false).unwrap(); + let mut cfg = + SpecConfig::new_trained(SpecWindow { max_t: max_t, mtp_max_t: mtp }, 64, VOCAB, suffix, false).unwrap(); cfg.max_context = max_context; if adaptive { cfg = cfg.with_adaptive(Some(AdaptiveConfig::new(max_t, max_t - 1))); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/adaptation_join_failure_is_reported.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/adaptation_join_failure_is_reported.rs index dd7a8672..bf02e9d1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/adaptation_join_failure_is_reported.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/adaptation_join_failure_is_reported.rs @@ -135,7 +135,7 @@ fn check_shape(g: &Greedy, shape: Shape) { e.bad_draft = bad; e.probs = pr.to_vec(); let mut c = OriginalSpecController::new( - SpecConfig::new(SpecWindow { max_t: max_t, mtp_max_t: mtp }, 4096, VOCAB, suffix, false).unwrap(), + SpecConfig::new_trained(SpecWindow { max_t: max_t, mtp_max_t: mtp }, 4096, VOCAB, suffix, false).unwrap(), ) .unwrap(); c.begin_request(&g.p, max_new, min_p, &eos).unwrap(); @@ -232,7 +232,7 @@ impl OriginalFirstDraftEngine for First { #[test] fn draft_first_entry_is_a_separate_literal_path_and_drains() { - let prep = DraftPreparation::new(4, 3, VOCAB).unwrap(); + let prep = DraftPreparation::new(4, 3, VOCAB, 262_144).unwrap(); let (point, sampling) = (FirstSeedPoint { cell: 9, token: 5 }, DraftSampling { min_p: 0.0, coupled: false }); let mut f = First { log: Vec::new(), fail: false }; let b = prep.from_committed_seed(&mut f, &0u8, point, sampling).unwrap(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/config_rejects_out_of_range.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/config_rejects_out_of_range.rs index f9ee0902..ba5daa09 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/config_rejects_out_of_range.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/config_rejects_out_of_range.rs @@ -9,14 +9,14 @@ use super::{ #[test] fn config_rejects_out_of_range_and_mtp_zero_means_max_t() { - assert!(SpecConfig::new(SpecWindow { max_t: 0, mtp_max_t: 0 }, 4096, VOCAB, 0, false).is_err()); - assert!(SpecConfig::new(SpecWindow { max_t: 9, mtp_max_t: 0 }, 4096, VOCAB, 0, false).is_err()); - assert!(SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 0 }, 0, VOCAB, 0, false).is_err()); - assert!(SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 0 }, 262145, VOCAB, 0, false).is_err()); - assert!(SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 0 }, 4096, 0, 0, false).is_err()); - assert_eq!(SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 0 }, 4096, VOCAB, 0, false).unwrap().mtp_t, 4); - assert_eq!(SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 9 }, 4096, VOCAB, 0, false).unwrap().mtp_t, 4); - assert_eq!(SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 2 }, 4096, VOCAB, 0, false).unwrap().mtp_t, 2); + assert!(SpecConfig::new_trained(SpecWindow { max_t: 0, mtp_max_t: 0 }, 4096, VOCAB, 0, false).is_err()); + assert!(SpecConfig::new_trained(SpecWindow { max_t: 9, mtp_max_t: 0 }, 4096, VOCAB, 0, false).is_err()); + assert!(SpecConfig::new_trained(SpecWindow { max_t: 4, mtp_max_t: 0 }, 0, VOCAB, 0, false).is_err()); + assert!(SpecConfig::new_trained(SpecWindow { max_t: 4, mtp_max_t: 0 }, 262145, VOCAB, 0, false).is_err()); + assert!(SpecConfig::new_trained(SpecWindow { max_t: 4, mtp_max_t: 0 }, 4096, 0, 0, false).is_err()); + assert_eq!(SpecConfig::new_trained(SpecWindow { max_t: 4, mtp_max_t: 0 }, 4096, VOCAB, 0, false).unwrap().mtp_t, 4); + assert_eq!(SpecConfig::new_trained(SpecWindow { max_t: 4, mtp_max_t: 9 }, 4096, VOCAB, 0, false).unwrap().mtp_t, 4); + assert_eq!(SpecConfig::new_trained(SpecWindow { max_t: 4, mtp_max_t: 2 }, 4096, VOCAB, 0, false).unwrap().mtp_t, 2); } #[test] @@ -180,7 +180,7 @@ fn max_new_ends_inside_a_window_without_overshooting_output() { fn a_window_near_the_context_end_takes_only_the_rows_that_fit() { let p = prompt(4); let mut e = Fake::new(&p[..3]); - let mut cfg = SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 4 }, 6, VOCAB, 0, false).unwrap(); + let mut cfg = SpecConfig::new_trained(SpecWindow { max_t: 4, mtp_max_t: 4 }, 6, VOCAB, 0, false).unwrap(); cfg.max_context = 6; let mut c = OriginalSpecController::new(cfg).unwrap(); begin(&mut c, &p, 100, &[]); @@ -236,7 +236,7 @@ fn the_chain_is_shortened_near_the_end_and_restored_after_it() { fn a_chain_clamped_by_one_request_is_restored_for_the_next() { let p = prompt(10); let mut e = Fake::new(&p[..9]); - let mut cfg = SpecConfig::new(SpecWindow { max_t: 4, mtp_max_t: 4 }, 64, VOCAB, 0, false).unwrap(); + let mut cfg = SpecConfig::new_trained(SpecWindow { max_t: 4, mtp_max_t: 4 }, 64, VOCAB, 0, false).unwrap(); cfg.max_context = 20; let mut c = OriginalSpecController::new(cfg).unwrap(); c.begin_request(&p, 1000, 0.0, &[]).unwrap(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/golden.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/golden.rs index 0310962d..dd56f8a7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/golden.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/golden.rs @@ -9,6 +9,7 @@ use super::super::super::original_spec_adaptive::AdaptiveConfig; use super::{Fake, OriginalSpecController, SpecConfig, SpecWindow, VOCAB, drive, next, prompt}; +use crate::qwen_forward::original_spec_controller::SpecContext; use std::path::PathBuf; fn golden_path(name: &str) -> PathBuf { @@ -73,8 +74,14 @@ impl Scenario { let p = prompt(self.prompt_len); let mut e = Fake::new(&p[..self.prompt_len - 1]); e.bad_draft = self.bad_draft; - let mut cfg = - SpecConfig::new(SpecWindow { max_t: self.max_t, mtp_max_t: self.mtp }, 64, VOCAB, 0, false).unwrap(); + let mut cfg = SpecConfig::new( + SpecWindow { max_t: self.max_t, mtp_max_t: self.mtp }, + SpecContext::trained(64), + VOCAB, + 0, + false, + ) + .unwrap(); cfg.max_context = self.max_context; if self.adaptive { cfg = cfg.with_adaptive(Some(AdaptiveConfig::new(self.max_t, self.max_t - 1))); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/trace_enabled.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/trace_enabled.rs index 524ec46d..832f8176 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/trace_enabled.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/trace_enabled.rs @@ -1,7 +1,9 @@ //! Settings of the speculative controller: NanGuard (non-finite window retry policy and its injection), SpecConfig //! (window, context, suffix and adaptive options), the round accessors, and the `LELEKA_SPEC_TRACE/STATS` switches. -use super::{AdaptiveConfig, CommittedRound, Error, MAX_T, NanGuard, Result, SpecConfig, SpecError, SpecWindow}; +use super::{ + AdaptiveConfig, CommittedRound, Error, MAX_T, NanGuard, Result, SpecConfig, SpecContext, SpecError, SpecWindow, +}; /// `LELEKA_SPEC_TRACE`: one `DBG spec-trace` line per timed round (width, source, accepted, round ms, the policy's /// expectation). @@ -100,18 +102,14 @@ impl NanGuard { impl SpecConfig { pub(crate) fn new( window: SpecWindow, - max_context: i64, + context: SpecContext, vocabulary: u32, suffix_min_match: usize, coupled: bool, ) -> Result { let SpecWindow { max_t, mtp_max_t } = window; - if !(1..=MAX_T).contains(&max_t) - || max_context < 1 - || max_context > crate::qwen_forward::contract::serving_cells() as i64 - || vocabulary == 0 - || vocabulary > 262144 - { + let SpecContext { max_context, serving_cells } = context; + if !(1..=MAX_T).contains(&max_t) || !context.is_servable() || vocabulary == 0 || vocabulary > 262144 { return Err(Error::InvalidDimension); } // Original --mtp-max-t<=0 means S; public usize zero carries that case. @@ -120,6 +118,7 @@ impl SpecConfig { max_t, mtp_t, max_context, + serving_cells, vocabulary, suffix_min_match, coupled, @@ -127,6 +126,17 @@ impl SpecConfig { nan_guard: NanGuard::off(), }) } + /// `new` for the context of an unconfigured process (262144 serving cells). + #[cfg(test)] + pub(crate) fn new_trained( + window: SpecWindow, + max_context: i64, + vocabulary: u32, + suffix_min_match: usize, + coupled: bool, + ) -> Result { + Self::new(window, SpecContext::trained(max_context), vocabulary, suffix_min_match, coupled) + } pub(crate) fn with_nan_guard(mut self, guard: NanGuard) -> Self { self.nan_guard = guard; self diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft.rs index ac65cb46..e0a1b0e0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft.rs @@ -118,13 +118,15 @@ pub(crate) struct DraftPreparation { max_t: usize, max_drafts: usize, vocabulary: u32, + /// The serving cells of the binding: no draft cell lies at or past it. + serving_cells: i64, } impl DraftPreparation { - pub(crate) fn new(max_t: usize, max_drafts: usize, vocabulary: u32) -> Result { + pub(crate) fn new(max_t: usize, max_drafts: usize, vocabulary: u32, serving_cells: i64) -> Result { if !(1..=MAX_T).contains(&max_t) || max_drafts > max_t - 1 || vocabulary == 0 || vocabulary > 262144 { return Err(Error::InvalidDimension); } - Ok(Self { max_t, max_drafts, vocabulary }) + Ok(Self { max_t, max_drafts, vocabulary, serving_cells }) } /// Target receipts stay borrowed until catch-up, selection, chain and drain /// complete. Ordinary confidence truncation leaves the rest of IDs/probs 0. @@ -150,8 +152,7 @@ impl DraftPreparation { || outputs.len() > self.max_t || a >= outputs.len() || p < 0 - || p.checked_add(outputs.len() as i64) - .is_none_or(|end| end > (crate::qwen_forward::contract::serving_cells() as i64)) + || p.checked_add(outputs.len() as i64).is_none_or(|end| end > self.serving_cells) || !min_p.is_finite() { return Err(Error::InvalidDimension); @@ -239,9 +240,7 @@ impl DraftPreparation { ) -> Result { let FirstSeedPoint { cell, token } = point; if cell < 0 - || cell - .checked_add(self.max_t as i64) - .is_none_or(|end| end > (crate::qwen_forward::contract::serving_cells() as i64)) + || cell.checked_add(self.max_t as i64).is_none_or(|end| end > self.serving_cells) || token < 0 || token as u32 >= self.vocabulary || !sampling.min_p.is_finite() diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft/prefill_records.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft/prefill_records.rs index bfda9ca1..5ed7fa67 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft/prefill_records.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft/prefill_records.rs @@ -8,24 +8,24 @@ pub(crate) struct PrefillRecords { records: Box<[i32]>, rows: usize, cell0: i64, + /// The serving cells of the binding: no record cell lies past it. + serving_cells: i64, } impl PrefillRecords { - pub(crate) fn new(next_tokens: &[i32], cell0: i64, vocabulary: u32) -> Result { + pub(crate) fn new(next_tokens: &[i32], cell0: i64, vocabulary: u32, serving_cells: i64) -> Result { let n = next_tokens.len(); - Self::check_geometry(n, cell0, vocabulary)?; + Self::check_geometry(n, cell0, (vocabulary, serving_cells))?; if next_tokens.iter().any(|&v| v < 0 || v as u32 >= vocabulary) { return Err(Error::InvalidToken); } let rec = Self::build_records(next_tokens, cell0)?; - Ok(Self { records: rec.into_boxed_slice(), rows: n, cell0 }) + Ok(Self { records: rec.into_boxed_slice(), rows: n, cell0, serving_cells }) } - fn check_geometry(n: usize, cell0: i64, vocabulary: u32) -> Result<()> { + fn check_geometry(n: usize, cell0: i64, (vocabulary, serving_cells): (u32, i64)) -> Result<()> { if n == 0 - || (n as i64) > (crate::qwen_forward::contract::serving_cells() as i64) + || (n as i64) > serving_cells || cell0 < 0 - || cell0 - .checked_add(n as i64) - .is_none_or(|end| end > (crate::qwen_forward::contract::serving_cells() as i64)) + || cell0.checked_add(n as i64).is_none_or(|end| end > serving_cells) || vocabulary == 0 || vocabulary > 262144 { @@ -69,8 +69,8 @@ impl PrefillRecords { let PrefillSchedule { max_t, cell0, window, prompt_len } = schedule; if !(1..=MAX_T).contains(&max_t) || cell0 != self.cell0 - || !(0..=(crate::qwen_forward::contract::serving_cells() as i64)).contains(&window) - || !(0..=(crate::qwen_forward::contract::serving_cells() as i64)).contains(&prompt_len) + || !(0..=self.serving_cells).contains(&window) + || !(0..=self.serving_cells).contains(&prompt_len) { return Err(Error::InvalidDimension); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk.rs index 461e4fd9..422a55ff 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk.rs @@ -170,11 +170,11 @@ mod tests { use super::*; #[test] fn chunk_incremental_retention_is_bounded_and_refuses_invalid_counts() { - assert_eq!(host_charge(0, 0), Err(Error::InvalidDimension)); - assert_eq!(host_charge(65, 1), Err(Error::InvalidDimension)); - assert_eq!(host_charge(4, 262145), Err(Error::InvalidDimension)); - assert!(host_charge(64, 190000).unwrap() < 512 * 1024 * 1024); - assert!(host_charge(64, 190000).unwrap() > host_charge(4, 190000).unwrap()); + assert_eq!(host_charge(0, 0, 262_144), Err(Error::InvalidDimension)); + assert_eq!(host_charge(65, 1, 262_144), Err(Error::InvalidDimension)); + assert_eq!(host_charge(4, 262145, 262_144), Err(Error::InvalidDimension)); + assert!(host_charge(64, 190000, 262_144).unwrap() < 512 * 1024 * 1024); + assert!(host_charge(64, 190000, 262_144).unwrap() > host_charge(4, 190000, 262_144).unwrap()); } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/gdn_chunk_start.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/gdn_chunk_start.rs index 3cb0b173..f5d04e4b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/gdn_chunk_start.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/gdn_chunk_start.rs @@ -265,6 +265,6 @@ impl ChunkCommit { // Charge new rolling GDN/PLE, two QSA pointer vectors and appended pages, // all T inputs + residuals + copied warm witnesses; baseline owners/caches // remain charged externally. Does not retain T full recurrent snapshots. -pub(super) fn host_charge(tokens: usize, end: u64) -> Result { - host_charge_bounded(tokens, end, 64) +pub(super) fn host_charge(tokens: usize, end: u64, serving_cells: u64) -> Result { + host_charge_bounded(tokens, end, 64, serving_cells) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/host_charge_bounded.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/host_charge_bounded.rs index 39409dea..f37bf440 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/host_charge_bounded.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/host_charge_bounded.rs @@ -4,8 +4,8 @@ use super::{Error, Rc, Result}; -pub(super) fn host_charge_bounded(tokens: usize, end: u64, limit: usize) -> Result { - if !(1..=limit).contains(&tokens) || end > crate::qwen_forward::contract::serving_cells() { +pub(super) fn host_charge_bounded(tokens: usize, end: u64, limit: usize, serving_cells: u64) -> Result { + if !(1..=limit).contains(&tokens) || end > serving_cells { return Err(Error::InvalidDimension); } let rolling: usize = 36 * (786432 + 30720) * 4 + 9 * 10240 * 4; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/qwen_chunk_txn/qwen_chunk_txn_begin.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/qwen_chunk_txn/qwen_chunk_txn_begin.rs index 5213dba6..30a19213 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/qwen_chunk_txn/qwen_chunk_txn_begin.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/qwen_chunk_txn/qwen_chunk_txn_begin.rs @@ -180,11 +180,11 @@ fn prompt_origin( } Ok(origin) } -/// The end position of the prompt, which must stay below the model context and the served cells. +/// The end position of the prompt, which must stay below the served cells (the model context of the binding). fn prompt_end(session: &QwenSession<'_>, binding: &ModelBinding, count: usize) -> Result<(u64, Dimension)> { let end = session.next_position.checked_add(count as u64).ok_or(Error::Overflow)?; let context_bound = Dimension::new(u64::from(binding.input_constants().context_length()))?; - if end >= u64::from(context_bound.get()) || end >= crate::qwen_forward::contract::serving_cells() { + if end >= u64::from(context_bound.get()) { return Err(Error::InvalidPosition); } Ok((end, context_bound)) @@ -207,7 +207,12 @@ fn admit_prompt_host( (end, host_remaining, windowed): (u64, usize, bool), ) -> Result<()> { check_vocab(tokens, known_next)?; - let charge = if windowed { host_charge_bounded(tokens.len(), end, 256)? } else { host_charge(tokens.len(), end)? }; + let cells = session.binding.bound_cells(); + let charge = if windowed { + host_charge_bounded(tokens.len(), end, 256, cells)? + } else { + host_charge(tokens.len(), end, cells)? + }; if charge > host_remaining { return Err(Error::InputAllocation); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/qwen_chunk_txn/qwen_chunk_txn_begin_verification.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/qwen_chunk_txn/qwen_chunk_txn_begin_verification.rs index 7ac97543..89dbe9cf 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/qwen_chunk_txn/qwen_chunk_txn_begin_verification.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/qwen_chunk_txn/qwen_chunk_txn_begin_verification.rs @@ -43,10 +43,8 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { return Err(Error::IdentityMismatch); } let end = session.next_position.checked_add(tokens as u64).ok_or(Error::Overflow)?; - let total = verification_total_charge(tokens, end)?; - if end >= u64::from(binding.input_constants().context_length()) - || end >= crate::qwen_forward::contract::serving_cells() - { + let total = verification_total_charge(tokens, end, binding.input_constants().bound_cells())?; + if end >= u64::from(binding.input_constants().context_length()) { return Err(Error::InvalidPosition); } if total > host_remaining.min(HOST_LIMIT) { @@ -63,7 +61,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { ) -> Result { Self::preflight_mtp_verification(session, binding, tokens.len(), host_remaining)?; let end = session.next_position.checked_add(tokens.len() as u64).ok_or(Error::Overflow)?; - let extra = verification_extra_charge(tokens.len(), end)?; + let extra = verification_extra_charge(tokens.len(), end, binding.input_constants().bound_cells())?; let available = host_remaining.min(HOST_LIMIT).checked_sub(extra).ok_or(Error::InputAllocation)?; // Both charges are admitted before rows, pointer journals or numeric // producers allocate. This preserves the old admission and VRAM cap. @@ -83,8 +81,9 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { /// The host charge of the rows plus the device-GDN metadata must fit what remains of the verification cap. fn admit_verification_charge(&self, metadata: usize, host_remaining: usize) -> Result<()> { - let charged = host_charge_bounded(self.rows.len(), self.end, 256)? - .checked_add(verification_extra_charge(self.rows.len(), self.end)?) + let serving_cells = self.session.binding.bound_cells(); + let charged = host_charge_bounded(self.rows.len(), self.end, 256, serving_cells)? + .checked_add(verification_extra_charge(self.rows.len(), self.end, serving_cells)?) .and_then(|n| n.checked_add(metadata)) .ok_or(Error::Overflow)?; if charged > host_remaining.min(HOST_LIMIT) { @@ -388,7 +387,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { } /// The host charge of `tokens` rows ending at `end` plus the verification extra charge. -fn verification_total_charge(tokens: usize, end: u64) -> Result { - let extra = verification_extra_charge(tokens, end)?; - host_charge_bounded(tokens, end, 256)?.checked_add(extra).ok_or(Error::Overflow) +fn verification_total_charge(tokens: usize, end: u64, serving_cells: u64) -> Result { + let extra = verification_extra_charge(tokens, end, serving_cells)?; + host_charge_bounded(tokens, end, 256, serving_cells)?.checked_add(extra).ok_or(Error::Overflow) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/tests.rs index 3615e73f..1c5a2630 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/tests.rs @@ -30,17 +30,17 @@ fn real_head_decision_stops_at_first_rejection_or_eos() { } #[test] fn complete_journal_charge_preserves_512_mib_refusal() { - assert_eq!(verification_extra_charge(0, 1), Err(Error::InvalidDimension)); - assert_eq!(verification_extra_charge(5, 5), Err(Error::InvalidDimension)); - assert_eq!(verification_extra_charge(2, 262145), Err(Error::InvalidDimension)); + assert_eq!(verification_extra_charge(0, 1, 262_144), Err(Error::InvalidDimension)); + assert_eq!(verification_extra_charge(5, 5, 262_144), Err(Error::InvalidDimension)); + assert_eq!(verification_extra_charge(2, 262145, 262_144), Err(Error::InvalidDimension)); for rows in [2, 3] { - let charge = host_charge_bounded(rows, rows as u64, 256).unwrap() - + verification_extra_charge(rows, rows as u64).unwrap(); + let charge = host_charge_bounded(rows, rows as u64, 256, 262_144).unwrap() + + verification_extra_charge(rows, rows as u64, 262_144).unwrap(); assert!(charge < HOST_LIMIT); } - let four = host_charge_bounded(4, 4, 256).unwrap() + verification_extra_charge(4, 4).unwrap(); + let four = host_charge_bounded(4, 4, 256, 262_144).unwrap() + verification_extra_charge(4, 4, 262_144).unwrap(); assert!(four > HOST_LIMIT); - assert!(verification_extra_charge(3, 190000).unwrap() > verification_extra_charge(3, 3).unwrap()); + assert!(verification_extra_charge(3, 190000, 262_144).unwrap() > verification_extra_charge(3, 3, 262_144).unwrap()); } // This tests private session/phase admission, NOT a ModelBinding, CUDA diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/verified_target_prefix.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/verified_target_prefix.rs index 168b1746..4652fd22 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/verified_target_prefix.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session/chunk/verify/verified_target_prefix.rs @@ -11,8 +11,8 @@ impl VerifiedTargetPrefix { // Existing admission already charges one rolling state. Journal references // retain T-1 additional genuine states, PLE histories and QSA pointer vectors. -pub(super) fn verification_extra_charge(tokens: usize, end: u64) -> Result { - if !(1..=4).contains(&tokens) || end > crate::qwen_forward::contract::serving_cells() { +pub(super) fn verification_extra_charge(tokens: usize, end: u64, serving_cells: u64) -> Result { + if !(1..=4).contains(&tokens) || end > serving_cells { return Err(Error::InvalidDimension); } let extra = tokens - 1; diff --git a/crates/native-cpu-expert/src/rust_ggml_native.rs b/crates/native-cpu-expert/src/rust_ggml_native.rs index 4ff2e216..876300ba 100644 --- a/crates/native-cpu-expert/src/rust_ggml_native.rs +++ b/crates/native-cpu-expert/src/rust_ggml_native.rs @@ -2,7 +2,6 @@ //! The integration patch keeps the original AVX2 bodies as the unselected branch. use super::rust_ggml::Kind; use std::arch::{asm, x86_64::*}; -use std::sync::OnceLock; // These correspond to actual GGML compiler macros, not a runtime highest-ISA // heuristic. Root must seal compiler features together with the Original build. @@ -14,8 +13,7 @@ const V256: bool = cfg!(target_feature = "avxvnni"); const SIGNED: bool = cfg!(target_feature = "avxvnniint8"); pub(super) fn compiled_admitted() -> bool { - static ADMITTED: OnceLock = OnceLock::new(); - *ADMITTED.get_or_init(probe) + crate::settings::GGML_ADMITTED.get() } /// The baseline AVX2 gate: CPUID leaf 7 present, AVX/OSXSAVE/FMA/F16C bits, XCR0 enabling XMM+YMM, AVX2 bit. /// Returns XCR0 and the leaf-7 registers when it holds. @@ -66,7 +64,7 @@ fn leaf1_ok(p: &CpuidResult) -> bool { let p1 = __cpuid_count(7, 1); !(BF && p1.eax & (1 << 5) == 0 || V256 && p1.eax & (1 << 4) == 0 || SIGNED && p1.edx & (1 << 4) == 0) } -fn probe() -> bool { +pub(super) fn probe() -> bool { // SAFETY: CPUID is available on x86_64; XGETBV follows OSXSAVE. // No STRATA_FORCE_AVX2 read here: that flag only controls Original explicit // IQ/Q2 dispatch and does not change compiled GGML type-trait arithmetic. diff --git a/crates/native-cpu-expert/src/rust_iq/dot_multi512.rs b/crates/native-cpu-expert/src/rust_iq/dot_multi512.rs index b2a76c8d..58e06b1f 100644 --- a/crates/native-cpu-expert/src/rust_iq/dot_multi512.rs +++ b/crates/native-cpu-expert/src/rust_iq/dot_multi512.rs @@ -113,8 +113,7 @@ pub(super) unsafe fn dot_multi512_impl( /// `LELEKA_IQ_SINGLE=legacy` keeps the generic single-token tree for IQ3_S / IQ3_XXS (A/B arm); the default is the /// register-built tree below (`dot_single_iq3`), the same integer lanes and float operations, so the same bits. pub(super) fn iq3_single_fast() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| crate::settings::var("LELEKA_IQ_SINGLE").as_deref() != Ok("legacy")) + crate::settings::IQ3_SINGLE_FAST.get() } // GGML AVX2 T1: two alternating exact integer accumulators, factor AFTER final reduction. #[target_feature(enable = "avx2,fma,f16c")] diff --git a/crates/native-cpu-expert/src/rust_iq/u16.rs b/crates/native-cpu-expert/src/rust_iq/u16.rs index de895a1e..50f5dba5 100644 --- a/crates/native-cpu-expert/src/rust_iq/u16.rs +++ b/crates/native-cpu-expert/src/rust_iq/u16.rs @@ -224,8 +224,7 @@ pub(in super::super) unsafe fn dot_multi512(t: i32, row: &[u8], ys: &[&[Q8K]], o /// drain per expert in `cpu_service_bench`, runs/cpu-service2 bench out-b) builds the multi-token AVX-512 IQ3 /// halves in registers; the default keeps the stack arrays. pub(super) fn iq3_multi_fast() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| crate::settings::var("LELEKA_IQ_MULTI").as_deref() == Ok("register")) + crate::settings::IQ3_MULTI_FAST.get() } /// One 32-weight half of an IQ3_S (21) / IQ3_XXS (18) block in a register: the eight grid words (lane l = word l, /// `decode`'s bytes 4l..4l+4), the sign word `decode` returns and its (uniform) 16-bit scale. diff --git a/crates/native-cpu-expert/src/rust_legacy.rs b/crates/native-cpu-expert/src/rust_legacy.rs index df7800bb..07e6595e 100644 --- a/crates/native-cpu-expert/src/rust_legacy.rs +++ b/crates/native-cpu-expert/src/rust_legacy.rs @@ -5,10 +5,7 @@ use super::rust_types::ActQ; use super::{Error, FF, H, MAX_ROWS, Result}; use std::{ arch::x86_64::*, - sync::{ - OnceLock, - atomic::{AtomicBool, Ordering}, - }, + sync::atomic::{AtomicBool, Ordering}, }; pub const BLOB: usize = 1_382_400; const D_CODES: usize = 2 * FF * 640; diff --git a/crates/native-cpu-expert/src/rust_legacy/set_oracle_q8_zero.rs b/crates/native-cpu-expert/src/rust_legacy/set_oracle_q8_zero.rs index a1f30b0b..6f55e82b 100644 --- a/crates/native-cpu-expert/src/rust_legacy/set_oracle_q8_zero.rs +++ b/crates/native-cpu-expert/src/rust_legacy/set_oracle_q8_zero.rs @@ -10,8 +10,8 @@ use super::{ _mm512_cvtepi32_ps, _mm512_cvtepu16_epi64, _mm512_dpbusd_epi32, _mm512_fmadd_ps, _mm512_loadu_si512, _mm512_maskz_loadu_ps, _mm512_maskz_mov_ps, _mm512_mul_ps, _mm512_multishift_epi64_epi8, _mm512_permutexvar_ps, _mm512_reduce_add_ps, _mm512_set1_epi8, _mm512_set1_epi32, _mm512_set1_epi64, _mm512_setr_epi32, _mm512_setzero_ps, - _mm512_setzero_si512, _xgetbv, ActQ, Error, FF, H, MAX_ROWS, ORACLE, OnceLock, Ordering, PlanarActivation, - PlanarScratch, Result, SingleScratch, hsum_original, + _mm512_setzero_si512, _xgetbv, ActQ, Error, FF, H, MAX_ROWS, ORACLE, Ordering, PlanarActivation, PlanarScratch, + Result, SingleScratch, hsum_original, }; pub fn set_oracle_q8_zero(enabled: bool) { @@ -262,8 +262,7 @@ pub(super) fn row(codes: &[u8], scales: &[u8], a: &[&ActQ], out: &mut [f32], ora out[t] = row_oracle(codes, scales, a[t]); } } else { - static ZMM: OnceLock = OnceLock::new(); - if *ZMM.get_or_init(|| crate::settings::var_os("STRATA_CPU_YMM").is_none()) { + if crate::settings::CPU_ZMM.get() { row512(codes, scales, a, out); } else { row256(codes, scales, a, out); diff --git a/crates/native-cpu-expert/src/rust_native_general/group_dot_bytes_policy.rs b/crates/native-cpu-expert/src/rust_native_general/group_dot_bytes_policy.rs index 98726ee0..b6cffdcc 100644 --- a/crates/native-cpu-expert/src/rust_native_general/group_dot_bytes_policy.rs +++ b/crates/native-cpu-expert/src/rust_native_general/group_dot_bytes_policy.rs @@ -45,10 +45,7 @@ pub(super) unsafe fn kq_dot(kind: Kind, row: &[u8], act: &[&NativeActivation], w } /// `STRATA_KQ256`: route multi-token Q4_K / Q5 / Q8 rows through the 256-bit kq kernels. fn kq256_enabled() -> bool { - static KQ: std::sync::OnceLock = std::sync::OnceLock::new(); - *KQ.get_or_init(|| { - crate::settings::var("STRATA_KQ256").ok().is_some_and(|s| super::super::rust_simd::atoi(&s) != 0) - }) + crate::settings::KQ256.get() } /// The kq kernel a multi-token row of original kind `k` takes under the env policy (gate/up Q4_K, down Q5/Q8). fn kq_route(k: i32, gu: bool, policy_nt: usize) -> bool { diff --git a/crates/native-cpu-expert/src/rust_pool/epoch_scheduling.rs b/crates/native-cpu-expert/src/rust_pool/epoch_scheduling.rs index b2131401..48d33282 100644 --- a/crates/native-cpu-expert/src/rust_pool/epoch_scheduling.rs +++ b/crates/native-cpu-expert/src/rust_pool/epoch_scheduling.rs @@ -132,12 +132,5 @@ impl Shared { /// Tasks per participating thread in a phase (pool.cpp `phase_tasks`: 3). `LELEKA_POOL_TASKS_PER_THREAD` (1..=16) is an /// A/B knob: every row is computed by the same code whatever task holds it, so the output does not depend on it. pub(super) fn tasks_per_thread() -> usize { - static V: std::sync::OnceLock = std::sync::OnceLock::new(); - *V.get_or_init(|| { - crate::settings::var("LELEKA_POOL_TASKS_PER_THREAD") - .ok() - .and_then(|v| v.parse().ok()) - .filter(|v| (1..=16).contains(v)) - .unwrap_or(3) - }) + crate::settings::POOL_TASKS_PER_THREAD.get() } diff --git a/crates/native-cpu-expert/src/rust_quant.rs b/crates/native-cpu-expert/src/rust_quant.rs index ea6842f1..ed795a0a 100644 --- a/crates/native-cpu-expert/src/rust_quant.rs +++ b/crates/native-cpu-expert/src/rust_quant.rs @@ -40,8 +40,7 @@ pub(super) fn q8_k(x: &[f32], y: &mut [Q8K]) { } /// `LELEKA_Q8K=legacy` keeps the scalar `q8_k` on the borrowed-group path (A/B arm); the default there is `q8_k_avx2`. pub(super) fn q8k_fast() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| crate::settings::var("LELEKA_Q8K").as_deref() != Ok("legacy")) + crate::settings::Q8K_FAST.get() } /// Horizontal maximum of the 8 lanes of `m` (high half first, then the pairwise reductions). #[target_feature(enable = "avx2,fma,f16c")] diff --git a/crates/native-cpu-expert/src/rust_simd.rs b/crates/native-cpu-expert/src/rust_simd.rs index cf84f5a3..bc1a0788 100644 --- a/crates/native-cpu-expert/src/rust_simd.rs +++ b/crates/native-cpu-expert/src/rust_simd.rs @@ -1,6 +1,5 @@ //! x86 instruction leaves: copied arithmetic trees, no portable numerical fallback. use std::arch::x86_64::*; -use std::sync::OnceLock; // SAFETY CONTRACT of every `#[target_feature]` leaf in this crate (rust_simd/quant/iq/q2/kq/k_blocks/ggml*/legacy): // a call requires the matching CPU gate to have succeeded first: avx2_ok() (AVX2+FMA+F16C+AVX+OSXSAVE+XCR0 and the // compiled GGML branch) for `avx2,fma,f16c` leaves; avx512_ok() && dq_ok() (or legacy_supported()) additionally for @@ -48,25 +47,25 @@ pub(super) struct Dispatch { pub avx512: bool, } pub(super) fn dispatch() -> &'static Dispatch { - static D: OnceLock = OnceLock::new(); - D.get_or_init(|| { - let avx512 = avx512_ok(); - Dispatch { - iq512: avx512 && crate::settings::var_os("STRATA_NO_IQ512").is_none(), - iq256: crate::settings::var_os("STRATA_NO_IQ256").is_none(), - iq4nl: crate::settings::var_os("STRATA_NO_IQ4NL").is_none(), - mt_min: crate::settings::var("STRATA_IQ_MT_MIN").map(|s| atoi(&s)).unwrap_or(2), - gather: crate::settings::var_os("STRATA_IQ_GATHER").is_some(), - prefetch: crate::settings::var("STRATA_IQ_PREFETCH").map(|s| atoi(&s)).unwrap_or(2048), - avx512, - } - }) + crate::settings::DISPATCH.get_ref() +} +/// The dispatch as the CPU and the process environment give it (what `settings::DISPATCH` caches). +pub(super) fn dispatch_from_environment() -> Dispatch { + let avx512 = avx512_ok(); + Dispatch { + iq512: avx512 && crate::settings::var_os("STRATA_NO_IQ512").is_none(), + iq256: crate::settings::var_os("STRATA_NO_IQ256").is_none(), + iq4nl: crate::settings::var_os("STRATA_NO_IQ4NL").is_none(), + mt_min: crate::settings::var("STRATA_IQ_MT_MIN").map(|s| atoi(&s)).unwrap_or(2), + gather: crate::settings::var_os("STRATA_IQ_GATHER").is_some(), + prefetch: crate::settings::var("STRATA_IQ_PREFETCH").map(|s| atoi(&s)).unwrap_or(2048), + avx512, + } } pub(super) fn avx2_ok() -> bool { - static VALUE: OnceLock = OnceLock::new(); - *VALUE.get_or_init(probe_avx2) && super::rust_ggml_native::compiled_admitted() + crate::settings::HOST_AVX2.get() && super::rust_ggml_native::compiled_admitted() } -fn probe_avx2() -> bool { +pub(super) fn probe_avx2() -> bool { // SAFETY: CPUID always available on x86_64; XGETBV only after OSXSAVE. unsafe { if __cpuid(0).eax < 7 { @@ -80,10 +79,9 @@ fn probe_avx2() -> bool { } } pub(super) fn avx512_ok() -> bool { - static VALUE: OnceLock = OnceLock::new(); - *VALUE.get_or_init(probe_avx512) + crate::settings::HOST_AVX512.get() } -fn probe_avx512() -> bool { +pub(super) fn probe_avx512() -> bool { if crate::settings::var("STRATA_FORCE_AVX2").is_ok_and(|v| v.as_bytes().first() == Some(&b'1')) { return false; } diff --git a/crates/native-cpu-expert/src/settings.rs b/crates/native-cpu-expert/src/settings.rs index 4ce948db..ede758ce 100644 --- a/crates/native-cpu-expert/src/settings.rs +++ b/crates/native-cpu-expert/src/settings.rs @@ -1,8 +1,11 @@ -//! 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 and host probes the kernels dispatch on: each is a named [`Setting`] that is +//! computed on first use and kept for the process life. A call site asks the catalogue; it never reads a variable or +//! caches a parse of its own. use std::env::{self, VarError}; use std::ffi::{OsStr, OsString}; +use std::sync::OnceLock; /// `std::env::var`: the text of an environment variable. #[inline] @@ -15,3 +18,75 @@ pub(crate) fn var>(key: K) -> Result { pub(crate) fn var_os>(key: K) -> Option { env::var_os(key) } + +/// A value that one function computes (from variables, or from the CPU) on the first read; a hot path pays one atomic +/// load afterwards. +pub(crate) struct Setting { + compute: fn() -> T, + value: OnceLock, +} + +impl Setting { + pub(crate) const fn new(compute: fn() -> T) -> Self { + Self { compute, value: OnceLock::new() } + } + + #[inline] + pub(crate) fn get_ref(&self) -> &T { + self.value.get_or_init(self.compute) + } +} + +impl Setting { + #[inline] + pub(crate) fn get(&self) -> T { + *self.get_ref() + } +} + +// What the CPU offers (a probe of the host, immutable for the process). +pub(crate) static HOST_AVX2: Setting = Setting::new(crate::rust_simd::probe_avx2); +pub(crate) static HOST_AVX512: Setting = Setting::new(crate::rust_simd::probe_avx512); +/// Whether the compiled GGML kernels are admitted on this CPU. +pub(crate) static GGML_ADMITTED: Setting = Setting::new(crate::rust_ggml_native::probe); +/// The kernel dispatch: the CPU plus the `STRATA_*` switches. +pub(crate) static DISPATCH: Setting = + Setting::new(crate::rust_simd::dispatch_from_environment); + +// The operator's A/B switches of the kernels. +/// `LELEKA_IQ_SINGLE=legacy` keeps the generic single-token tree for IQ3_S / IQ3_XXS. +pub(crate) static IQ3_SINGLE_FAST: Setting = Setting::new(iq3_single_fast); +/// `LELEKA_IQ_MULTI=register` builds the multi-token AVX-512 IQ3 halves in registers. +pub(crate) static IQ3_MULTI_FAST: Setting = Setting::new(iq3_multi_fast); +/// `LELEKA_Q8K=legacy` keeps the scalar `q8_k` on the borrowed-group path. +pub(crate) static Q8K_FAST: Setting = Setting::new(q8k_fast); +/// `STRATA_CPU_YMM` set: the legacy rows take the 256-bit kernel instead of the 512-bit one. +pub(crate) static CPU_ZMM: Setting = Setting::new(cpu_zmm); +/// `STRATA_KQ256`: route multi-token Q4_K / Q5 / Q8 rows through the 256-bit kq kernels. +pub(crate) static KQ256: Setting = Setting::new(kq256); +/// `LELEKA_POOL_TASKS_PER_THREAD` (1..=16, default 3): tasks per participating thread in a phase. +pub(crate) static POOL_TASKS_PER_THREAD: Setting = Setting::new(pool_tasks_per_thread); + +fn iq3_single_fast() -> bool { + var("LELEKA_IQ_SINGLE").as_deref() != Ok("legacy") +} + +fn iq3_multi_fast() -> bool { + var("LELEKA_IQ_MULTI").as_deref() == Ok("register") +} + +fn q8k_fast() -> bool { + var("LELEKA_Q8K").as_deref() != Ok("legacy") +} + +fn cpu_zmm() -> bool { + var_os("STRATA_CPU_YMM").is_none() +} + +fn kq256() -> bool { + var("STRATA_KQ256").ok().is_some_and(|s| crate::rust_simd::atoi(&s) != 0) +} + +fn pool_tasks_per_thread() -> usize { + var("LELEKA_POOL_TASKS_PER_THREAD").ok().and_then(|v| v.parse().ok()).filter(|v| (1..=16).contains(v)).unwrap_or(3) +}