cuda-driver and CPU expert pool (hot path, awaiting the identity gate): head_dispatch compiled once (shared module, no glob, no #[path]), copy_ring_layer split in two with explicit imports, measurement-timer comments, exceptions for the dyn, Instant::now and process-global sites that stay

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-11-14 21:20:07 +01:00
co-authored by Claude Sonnet 5.5
parent dce1676baf
commit d027790278
41 changed files with 304 additions and 171 deletions
-7
View File
@@ -5,23 +5,16 @@
"source": {
"allow-unused-imports:leleka-engine-core": 18,
"allow-unused-imports:leleka-engine-qwen35-cuda": 166,
"dyn-trait:leleka-cuda-driver": 26,
"dyn-trait:leleka-engine-core": 18,
"dyn-trait:leleka-engine-fake": 1,
"dyn-trait:leleka-engine-qwen35-cuda": 53,
"env-read:leleka-engine-qwen35-cuda": 1,
"env-read:strata-control": 3,
"glob-super-import:leleka-cuda-driver": 2,
"glob-super-import:leleka-engine-qwen35-cuda": 70,
"instant-now:leleka-cuda-driver": 25,
"instant-now:leleka-engine-qwen35-cuda": 16,
"instant-now:leleka-native-cpu-expert": 27,
"instant-now:strata-control": 15,
"instant-now:strata-desktop-core": 4,
"path-include:leleka-cuda-driver": 1,
"process-global:leleka-cuda-driver": 43,
"process-global:leleka-engine-qwen35-cuda": 59,
"process-global:leleka-native-cpu-expert": 27,
"process-global:strata-control": 2
},
"mechanical_names": []
+72 -3
View File
@@ -63,8 +63,8 @@
{"crate": "leleka-gptoss", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: it returns the operator's switches as typed values"},
{"crate": "leleka-model-format", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: it returns the operator's switches as typed values"},
{"crate": "leleka-obs", "file": "src/level.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: LELEKA_LOG* parsed once into Settings, and the request-log path"},
{"crate": "leleka-cuda-driver", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate; call sites still parse the text they ask for (typed switches: EnvSwitch in leleka-cuda-model, in progress on claude/debt-hot-low)"},
{"crate": "leleka-native-cpu-expert", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate; call sites still parse the text they ask for (CPU expert pool: hot path, in progress on claude/debt-hot-low)"},
{"crate": "leleka-cuda-driver", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: the 22 on/off switches are EnvSwitch entries of its catalogue (leleka_cuda_model::env_switch); the option parsers (stager, stream-all, chain flags, sm120 switches) still call the pass-through var/var_os with their own parsing, which a typed Settings value of the driver would replace"},
{"crate": "leleka-native-cpu-expert", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate (CPU expert pool, a hot path): call sites still parse the text they ask for with the pass-through var/var_os; a typed Settings value captured when the pool starts would replace them"},
{"crate": "leleka-cpu-kernels", "file": "src/dispatch.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: ISA_ENV is parsed by Isa::from_request into the selected instruction set"},
{"crate": "leleka-libc-shim", "file": "src/cuda_trace/trace_state.rs", "ratchet": "env-read", "reason": "Windows interposer (FFI): the CUDA call tracer reads its own LELEKA_BRINGUP_TRACE switches and must not depend on other crates"},
{"crate": "leleka-libc-shim", "file": "src/lib.rs", "ratchet": "env-read", "reason": "Windows interposer (FFI): the DLL search directories come from the process environment before any other crate can load"},
@@ -158,7 +158,76 @@
{"crate": "leleka-gateway-text", "file": "src/prompt/renderer.rs", "ratchet": "process-global", "reason": "the compiled pinned chat template: immutable, built on first use, read by every request"},
{"crate": "strata-control", "file": "src/request_log.rs", "ratchet": "process-global", "reason": "the process-wide request counters and histograms that /metrics renders; written by every request"},
{"crate": "strata-control", "file": "src/responses/harmony_prompt.rs", "ratchet": "process-global", "reason": "the gpt-oss prompt date: configuration set once by serve before the first request"},
{"crate": "strata-control", "file": "src/stage_trace.rs", "ratchet": "process-global", "reason": "diagnostic stage table of the replay harness and STRATA_STAGE_TRACE: one table per process by design"}
{"crate": "strata-control", "file": "src/stage_trace.rs", "ratchet": "process-global", "reason": "diagnostic stage table of the replay harness and STRATA_STAGE_TRACE: one table per process by design"},
{"crate": "leleka-cuda-driver", "file": "src/compute_drain.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: stall span of one timed drain, reported by the prefill stall trace"},
{"crate": "leleka-cuda-driver", "file": "src/mmq/resident/original_group/copy_ring/chunk_stream/chunk_issuing.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: span of one chunk issue, summed into the copy-ring profile"},
{"crate": "leleka-cuda-driver", "file": "src/mmq/resident/original_group/copy_ring/original_mmq_copy_schedule/stream_start.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: start of the copy-ring stream, read once per stream for the profile"},
{"crate": "leleka-cuda-driver", "file": "src/native_prompt_device/original_prompt_device/run_phases.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: span of one prompt phase, reported by the prefill profile"},
{"crate": "leleka-cuda-driver", "file": "src/original_file_expert_source/original_file_expert_source_operations/file_expert_source_prefetch.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: span of one expert-file prefetch, summed into the stager profile"},
{"crate": "leleka-cuda-driver", "file": "src/original_file_expert_source/original_file_expert_source_operations/file_expert_source_stages_and_blobs.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: spans of the expert-file stages, summed into the stager profile"},
{"crate": "leleka-cuda-driver", "file": "src/original_gpu_schedule/original_gpu_graph.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: span of one graph launch, reported by the graph profile"},
{"crate": "leleka-cuda-driver", "file": "src/original_gpu_schedule/original_gpu_stream.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: span of one stream synchronisation, reported by the stream profile"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/diag.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: wait loop of the live-verifier release diagnostic, bounded by its own timeout"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/schedule/verifier_commit_window_lifecycle.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: span of one commit window, reported by the verifier profile"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/schedule/verifier_logits_diagnostics_close.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: span of one logits readout, reported by the verifier profile"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/schedule/window_phases.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: spans of the window phases, reported by the verifier profile"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/share_window_modules/physical.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: span of the physical bank open, reported by the verifier profile"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_prompt_index/prompt_device/resident_device/original_qsa_prompt_device.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: timestamp of the last prompt-device use, read by the idle-trim policy of the device"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_prompt_index/resident_program/qsa_prompt_index_workspace.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: span of one resident index program run, reported by the prefill profile"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_prompt_kv/mapped_journal/original_qsa_mapped_prefix/qsa_mapped_journal_append_and_resolve.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: spans of the mapped-journal append and resolve, reported by the prefill profile"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_dispatch/gdn_native_batch/prompt_device/original_gdn_prompt_device/original_gdn_prompt_device_drain.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: spans of the GDN prompt drain, reported by the prefill profile"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_bench_frontend/cpu_blob.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: benchmark harness timers around the blob kernels, printed by the bench"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_general_pool/epoch_scheduling.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: per-epoch timers of the CPU expert pool (hot loop), summed into the pool trace; one reading per phase"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_general_pool/expert_pool.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: per-call phase timers of the CPU expert pool (hot loop), summed into the pool trace; one reading per phase"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_general_pool/expert_pool_split_multi_run.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: per-run phase timers of the split multi-expert run (hot loop), summed into the pool trace"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_general_pool/shared_wait_done_and_quantize_lanes.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: wait and quantize lap timers of the pool (hot loop), summed into the pool trace"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_pool/epoch_scheduling.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: the pool's one monotonic reading, wrapped so every epoch timestamp comes from it (hot loop)"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_pool/native_pool.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: per-thread start stamps of the native pool for its timing mode (hot loop)"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_pool/trace.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: origin of the pool trace timeline, read once when tracing starts"},
{"crate": "leleka-cuda-driver", "file": "src/mmq/resident/original_group.rs", "ratchet": "dyn-trait", "reason": "the group borrows its arena view (GroupArena) from the caller for one run; a test seam with a mock arena"},
{"crate": "leleka-cuda-driver", "file": "src/mmq/resident/original_group/copy_ring.rs", "ratchet": "dyn-trait", "reason": "the copy ring borrows its arena view (RingArena) from the caller for one run; a test seam with a mock arena"},
{"crate": "leleka-cuda-driver", "file": "src/mtp_dense_kv/original_int8/prefill/scalar/full_forward/full_round/put.rs", "ratchet": "dyn-trait", "reason": "the put step takes the copy and the fence of one round as callbacks, so the same code runs over the real streams and a recording test double"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/diag.rs", "ratchet": "dyn-trait", "reason": "the live-verifier release diagnostic writes an optional note to any writer (stderr, a file or a buffer in the tests)"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/gr.rs", "ratchet": "dyn-trait", "reason": "the window planner reads weight addresses through the ArenaMap seam (the device arena in production, an in-memory table in the tests); the planner structs keep it for one window plan, which is built at capture time, not per token"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/moe/plan_expert_groups.rs", "ratchet": "dyn-trait", "reason": "the window planner reads weight addresses through the ArenaMap seam (the device arena in production, an in-memory table in the tests); the planner structs keep it for one window plan, which is built at capture time, not per token"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/moe/plan_f32_to_bf16.rs", "ratchet": "dyn-trait", "reason": "the window planner reads weight addresses through the ArenaMap seam (the device arena in production, an in-memory table in the tests); the planner structs keep it for one window plan, which is built at capture time, not per token"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/planner.rs", "ratchet": "dyn-trait", "reason": "the window planner reads weight addresses through the ArenaMap seam (the device arena in production, an in-memory table in the tests); the planner structs keep it for one window plan, which is built at capture time, not per token"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/qsa.rs", "ratchet": "dyn-trait", "reason": "the window planner reads weight addresses through the ArenaMap seam (the device arena in production, an in-memory table in the tests); the planner structs keep it for one window plan, which is built at capture time, not per token"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/qsa/qsa_window/qsa_window_query_key_paths.rs", "ratchet": "dyn-trait", "reason": "the window planner reads weight addresses through the ArenaMap seam (the device arena in production, an in-memory table in the tests); the planner structs keep it for one window plan, which is built at capture time, not per token"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_dispatch/gdn_native_batch.rs", "ratchet": "dyn-trait", "reason": "the batch owner holds its GEMM provider (cuBLAS-backed in production, a host stand-in in the tests) as a trait object for the life of one batch; it is a port, chosen when the owner is opened"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_dispatch/gdn_native_batch/context.rs", "ratchet": "dyn-trait", "reason": "the batch owner holds its GEMM provider (cuBLAS-backed in production, a host stand-in in the tests) as a trait object for the life of one batch; it is a port, chosen when the owner is opened"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_dispatch/moe_prefill_batch.rs", "ratchet": "dyn-trait", "reason": "the batch owner holds its GEMM provider (cuBLAS-backed in production, a host stand-in in the tests) as a trait object for the life of one batch; it is a port, chosen when the owner is opened"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_dispatch/moe_prefill_batch/moe_prefill_batch_lifecycle.rs", "ratchet": "dyn-trait", "reason": "the batch owner holds its GEMM provider (cuBLAS-backed in production, a host stand-in in the tests) as a trait object for the life of one batch; it is a port, chosen when the owner is opened"},
{"crate": "leleka-cuda-driver", "file": "src/arch_ptx/stream_k_off.rs", "ratchet": "process-global", "reason": "marker-file polls of the A/B controls (LELEKA_MMQ_NO_STREAMK_FILE, LELEKA_CHUNK_DRAIN_FILE): the paths are operator setting parsed once from the environment and cached for the process, the poll instants are rate-limit state"},
{"crate": "leleka-cuda-driver", "file": "src/context.rs", "ratchet": "process-global", "reason": "LELEKA_PREFILL_DEFER_FREE_MIB: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-cuda-driver", "file": "src/mmq/asset.rs", "ratchet": "process-global", "reason": "the verdict of the immutable MMQ artifact check, computed once"},
{"crate": "leleka-cuda-driver", "file": "src/mmq/resident/original_group/copy_ring/host_stage/verify_enabled.rs", "ratchet": "process-global", "reason": "LELEKA_STAGE_PRIORITY: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-cuda-driver", "file": "src/mmq/resident/original_group/copy_ring/skip_expert_dma.rs", "ratchet": "process-global", "reason": "marker-file polls of the ring A/B controls: the paths are operator setting parsed once from the environment and cached for the process, the start instant is rate-limit state"},
{"crate": "leleka-cuda-driver", "file": "src/original_gpu_schedule/abi/platform/library_drop.rs", "ratchet": "process-global", "reason": "LELEKA_CB_WARMUP: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-cuda-driver", "file": "src/original_gpu_schedule/transport.rs", "ratchet": "process-global", "reason": "LELEKA_TEST_WINDOW_INSTANTIATE_OOM_AT, a test hook: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/chain.rs", "ratchet": "process-global", "reason": "the chain switches parsed by ChainFlags::parse: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/gpu_plan/cpu_sink_publish_gpu_plan.rs", "ratchet": "process-global", "reason": "the DMA options of the CPU sink: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/moe/pcie_fast_kernel.rs", "ratchet": "process-global", "reason": "LELEKA_PCIE_KERNEL and LELEKA_PCIE_GRID: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-cuda-driver", "file": "src/prefill_stage.rs", "ratchet": "process-global", "reason": "the usability of the kh recurrence on this device: immutable result of a probe or proof of a sealed image, computed once and cached"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_index_ffi.rs", "ratchet": "process-global", "reason": "the RoPE ABI of the loaded index module: immutable result of a probe or proof of a sealed image, computed once and cached"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_prompt_attention/qsa_prompt_attention_drop.rs", "ratchet": "process-global", "reason": "LELEKA_PREFILL_GUARD_GRID: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_prompt_kv/resident_transport.rs", "ratchet": "process-global", "reason": "LELEKA_PREFILL_QSA_PREFETCH: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_prompt_resolver.rs", "ratchet": "process-global", "reason": "the resolver ABI of the loaded module: immutable result of a probe or proof of a sealed image, computed once and cached"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_ffi/asset_validation_and_bf16_layout.rs", "ratchet": "process-global", "reason": "per-operation memo of the PTX proof: immutable result of a probe or proof of a sealed image, computed once and cached"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_ffi/n_types.rs", "ratchet": "process-global", "reason": "the table of PTX proof memos, one cell per operation: immutable result of a probe or proof of a sealed image, computed once and cached"},
{"crate": "leleka-cuda-driver", "file": "src/vram_ledger.rs", "ratchet": "process-global", "reason": "the process-wide VRAM ledger (LELEKA_VRAM_LEDGER): a diagnostic singleton fed by every allocation site"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_bench_frontend.rs", "ratchet": "process-global", "reason": "FFI: `static mut stdout` is libc's C stream, declared in an extern block"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_expert_layout.rs", "ratchet": "process-global", "reason": "the process-wide expert layout the pool threads read; it is set at load time by the engine"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_general_pool/job_default.rs", "ratchet": "process-global", "reason": "the origin instant of the pool's job timestamps"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_general_pool.rs", "ratchet": "process-global", "reason": "the hook that releases the GPU waits, installed once by the engine (a function pointer)"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_ggml_native.rs", "ratchet": "process-global", "reason": "the admission verdict of the native ggml kernels on this CPU, computed once"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_iq/dot_multi512.rs", "ratchet": "process-global", "reason": "LELEKA_IQ_SINGLE: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_iq/u16.rs", "ratchet": "process-global", "reason": "LELEKA_IQ_MULTI: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_legacy/set_oracle_q8_zero.rs", "ratchet": "process-global", "reason": "STRATA_CPU_YMM: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_native_general/group_dot_bytes_policy.rs", "ratchet": "process-global", "reason": "STRATA_KQ256: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_pool/epoch_scheduling.rs", "ratchet": "process-global", "reason": "LELEKA_POOL_TASKS_PER_THREAD: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_quant.rs", "ratchet": "process-global", "reason": "LELEKA_Q8K: operator setting parsed once from the environment and cached for the process"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_simd.rs", "ratchet": "process-global", "reason": "the CPU feature dispatch and the STRATA_* switches parsed from it: operator setting parsed once from the environment and cached for the process"}
],
"source_patterns": [
{"id": "env-read", "regex": "\\benv::var(_os)?\\(", "why": "configuration must be parsed once into a Settings struct (S13), not read all over the code"},
+1
View File
@@ -122,6 +122,7 @@ pub(crate) fn timed<T>(kind: usize, f: impl FnOnce() -> T) -> T {
if background() == 0 {
return f();
}
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let started = std::time::Instant::now();
let out = f();
let took = started.elapsed();
+2
View File
@@ -240,6 +240,8 @@ mod native_parity_ffi;
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
mod native_head;
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
mod native_head_dispatch;
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
mod original_file_expert_source;
@@ -146,6 +146,7 @@ use kind::kind;
use kind::layout;
use kind::shared;
mod copy_ring_layer;
mod copy_ring_projection;
mod mmq_workspace;
mod original_mmq_layer;
mod original_mmq_output;
@@ -36,6 +36,7 @@ impl Core {
if self.depth == 0 {
return self.issue_until(k + 1);
}
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let started = Instant::now();
while self.issued.load(Ordering::Acquire) <= k {
if self.failed.load(Ordering::Acquire) || started.elapsed() > Duration::from_secs(60) {
@@ -163,6 +163,7 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> {
) {
// from here the compute path's drains stop waiting for the copy stream (end_prompt_stream restores them)
crate::compute_drain::set_background(copy);
// Measurement timer, not decision logic (instant-now exception in architecture.json).
self.stream_started = Some(std::time::Instant::now());
self.stream = Some(stream);
self.stream_bank = Some(Rc::clone(bank));
@@ -1,6 +1,11 @@
//! Copy-ring execution of an `OriginalMmqLayer`: stage, gather, enqueue, drain (a glob import: at the line limit).
//! Copy-ring execution of an `OriginalMmqLayer`: preflight, stage-ahead, gather and the enqueue of each group's
//! kernels while the ring streams the experts in (projection launches and status words: `copy_ring_projection`).
use super::*;
use crate::combine;
use super::{
D, GU, Error, GatherDest, GroupArena, H, HQ, MmqFormat, OriginalMmqCopySchedule, OriginalMmqLayer,
ProjectSlots, ProjectSpec, Result, RingExperts, TMP, WD, WG, XQ, copy_ring, ffi, layout,
};
impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> {
/// Execute the actual ascending expert layer through Original's copy ring.
@@ -256,144 +261,4 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> {
ffi::MmqResidentArguments::finite(q, q_flag, 1, (ql.payload / 144) as u32, (128 * 144) as u32),
))
}
/// Maps the finite/Q8 witness words of every group to the first refusal.
fn check_ring_statuses(flags: &[u8]) -> Result<()> {
for group in flags.chunks_exact(16) {
let words = group.as_chunks::<4>().0;
Self::check_group_status([0, 1, 2, 3].map(|i| u32::from_le_bytes(words[i])))?;
}
Ok(())
}
fn check_group_status([gu, h, q, down]: [u32; 4]) -> Result<()> {
Self::check_gate_up_status(gu, h)?;
Self::check_q8_down_status(q, down)
}
fn check_gate_up_status(gu: u32, h: u32) -> Result<()> {
match gu {
0 => {}
1 | 3 => return Err(Error::NonFiniteMmqOutput("Gate")),
2 => return Err(Error::NonFiniteMmqOutput("Up")),
_ => return Err(Error::InvalidDriverValue("Original GU finite witness")),
}
match h {
0 => {}
1 => return Err(Error::NonFiniteMmqOutput("SwiGLU")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
Ok(())
}
fn check_q8_down_status(q: u32, down: u32) -> Result<()> {
match q {
0 => {}
1 | 3 => return Err(Error::InvalidQ8Activation),
2 => return Err(Error::InvalidDriverValue("Original grouped Q8 tail")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
match down {
0 => {}
1 => return Err(Error::NonFiniteMmqOutput("Down")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
Ok(())
}
pub(super) fn enqueue_ring_project(
&self,
ring: &mut copy_ring::Ring<'_, 'ctx>,
spec: ProjectSpec,
slots: ProjectSlots,
) -> Result<()> {
let ProjectSpec { format, down, width } = spec;
let ProjectSlots { weights, packed, out } = slots;
let b = self.bank()?;
let experts = self.staged as u32;
let nr = self.bounds[self.next + self.staged] - self.bounds[self.next];
let rows = if down { 2560 } else { 1280 };
let tokens = if down { nr } else { self.total };
let l = layout(format, rows, tokens, width)?;
let functions = Self::ring_project_functions(b, format, width)?;
let maxr = self.counts[self.next..self.next + self.staged].iter().copied().max();
let maxr = maxr.ok_or(Error::InvalidProjectionShape)?;
let (grid, needs_fix) = self.ring_project_grid(&l, rows, (experts, maxr, width))?;
let hs = self.ring_project_handles(&l, (weights, packed, out), (down, tokens, experts))?;
let tmp = self.ring_project_tmp(needs_fix, grid, width)?;
Self::ring_project_commands(
ring,
functions,
(l, grid),
(hs, tmp),
ffi::MmqGroupShape { experts, max_rows: maxr, width },
)
}
/// The projection and fixup function of `format` at tile `width`.
fn ring_project_functions(
b: &OriginalGroupBank<'ctx>,
format: MmqFormat,
width: u32,
) -> Result<(ffi::FunctionHandle, ffi::FunctionHandle)> {
let fi = format_index(format)?;
let ti = WIDTHS.iter().position(|j| *j == width).ok_or(Error::UnsupportedProjection)?;
let f = b.functions[fi][ti].ok_or(Error::UnsupportedProjection)?;
Ok((f, b.fixups[fi][ti].ok_or(Error::UnsupportedProjection)?))
}
/// `(grid, needs fixup)`: complete tiles, or the stream-k grid when the tile count fills the SMs poorly.
fn ring_project_grid(&self, l: &Layout, rows: u32, (experts, maxr, width): (u32, u32, u32)) -> Result<(u32, bool)> {
let ntx = maxr.div_ceil(width);
let tiles =
(rows / 128).checked_mul(ntx).and_then(|n| n.checked_mul(experts)).ok_or(Error::InvalidProjectionShape)?;
if tiles.checked_mul(l.columns / l.qk).is_none_or(|n| n >= 1 << 30) {
return Err(Error::InvalidProjectionShape);
}
let sms = self.workspace.experiment.as_ref().ok_or(Error::ContextPoisoned)?.sms;
let efficiency = 100 * tiles / (sms * tiles.div_ceil(sms));
let grid = if efficiency >= 90 || crate::arch_ptx::stream_k_off() { tiles } else { sms };
Ok((grid, !tiles.is_multiple_of(grid)))
}
/// `[weights, packed, output, ids, bounds]` handles of one projection.
fn ring_project_handles(
&self,
l: &Layout,
(weights, packed, out): (usize, usize, usize),
(down, tokens, experts): (bool, u32, u32),
) -> Result<[ffi::BufferHandle; 5]> {
let wh = self.handle(weights, 0, l.raw_weight * experts as usize + 4096, 4)?;
let ph = self.handle(packed, 0, l.packed, 16)?;
let oh = self.handle(out, 0, l.output, 4)?;
let ids = self.handle(IDENTITY, 0, tokens as usize * 4, 4)?;
let offset = if down { self.counts.len() + 1 + (self.next / 16) * 17 } else { self.next };
let bounds = self.handle(BOUNDS, offset * 4, (experts as usize + 1) * 4, 4)?;
Ok([wh, ph, oh, ids, bounds])
}
/// The stream-k fixup scratch when the grid does not divide the tile count.
fn ring_project_tmp(&self, needs_fix: bool, grid: u32, width: u32) -> Result<Option<ffi::BufferHandle>> {
if !needs_fix {
return Ok(None);
}
Ok(Some(self.handle(TMP, 0, grid as usize * width as usize * 128 * 4, 4)?))
}
fn ring_project_commands(
ring: &mut copy_ring::Ring<'_, 'ctx>,
(f, fix): (ffi::FunctionHandle, ffi::FunctionHandle),
(l, grid): (Layout, u32),
([wh, ph, oh, ids, bounds], tmp): ([ffi::BufferHandle; 5], Option<ffi::BufferHandle>),
shape: ffi::MmqGroupShape,
) -> Result<()> {
use crate::ffi::original_enqueue::Command;
let routing = ffi::MmqGroupRouting { ids, bounds };
let buffers = ffi::MmqGroupBuffers { weights: wh, packed: ph, output: oh, tmp };
ring.enqueue(Command::Project(f, l, grid, ffi::MmqArguments::original_group(buffers, routing, l, shape)))?;
if let Some(tmp) = tmp {
let args = ffi::MmqFixupArguments::original_group(routing, oh, tmp, l, shape);
ring.enqueue(Command::Fixup(fix, grid, args))?;
}
Ok(())
}
}
@@ -0,0 +1,149 @@
//! The projection launches of the copy ring (MMQ over the staged group) and the status words they publish: the
//! launch geometry of one projection, and the mapping of the finite and Q8 witness words to the first refusal.
use super::{
BOUNDS, Error, IDENTITY, Layout, MmqFormat, OriginalGroupBank, OriginalMmqLayer, ProjectSlots, ProjectSpec,
Result, TMP, WIDTHS, copy_ring, ffi, format_index, layout,
};
impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> {
/// Maps the finite/Q8 witness words of every group to the first refusal.
pub(super) fn check_ring_statuses(flags: &[u8]) -> Result<()> {
for group in flags.chunks_exact(16) {
let words = group.as_chunks::<4>().0;
Self::check_group_status([0, 1, 2, 3].map(|i| u32::from_le_bytes(words[i])))?;
}
Ok(())
}
fn check_group_status([gu, h, q, down]: [u32; 4]) -> Result<()> {
Self::check_gate_up_status(gu, h)?;
Self::check_q8_down_status(q, down)
}
fn check_gate_up_status(gu: u32, h: u32) -> Result<()> {
match gu {
0 => {}
1 | 3 => return Err(Error::NonFiniteMmqOutput("Gate")),
2 => return Err(Error::NonFiniteMmqOutput("Up")),
_ => return Err(Error::InvalidDriverValue("Original GU finite witness")),
}
match h {
0 => {}
1 => return Err(Error::NonFiniteMmqOutput("SwiGLU")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
Ok(())
}
fn check_q8_down_status(q: u32, down: u32) -> Result<()> {
match q {
0 => {}
1 | 3 => return Err(Error::InvalidQ8Activation),
2 => return Err(Error::InvalidDriverValue("Original grouped Q8 tail")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
match down {
0 => {}
1 => return Err(Error::NonFiniteMmqOutput("Down")),
_ => return Err(Error::InvalidDriverValue("Original grouped finite status")),
}
Ok(())
}
pub(super) fn enqueue_ring_project(
&self,
ring: &mut copy_ring::Ring<'_, 'ctx>,
spec: ProjectSpec,
slots: ProjectSlots,
) -> Result<()> {
let ProjectSpec { format, down, width } = spec;
let ProjectSlots { weights, packed, out } = slots;
let b = self.bank()?;
let experts = self.staged as u32;
let nr = self.bounds[self.next + self.staged] - self.bounds[self.next];
let rows = if down { 2560 } else { 1280 };
let tokens = if down { nr } else { self.total };
let l = layout(format, rows, tokens, width)?;
let functions = Self::ring_project_functions(b, format, width)?;
let maxr = self.counts[self.next..self.next + self.staged].iter().copied().max();
let maxr = maxr.ok_or(Error::InvalidProjectionShape)?;
let (grid, needs_fix) = self.ring_project_grid(&l, rows, (experts, maxr, width))?;
let hs = self.ring_project_handles(&l, (weights, packed, out), (down, tokens, experts))?;
let tmp = self.ring_project_tmp(needs_fix, grid, width)?;
Self::ring_project_commands(
ring,
functions,
(l, grid),
(hs, tmp),
ffi::MmqGroupShape { experts, max_rows: maxr, width },
)
}
/// The projection and fixup function of `format` at tile `width`.
fn ring_project_functions(
b: &OriginalGroupBank<'ctx>,
format: MmqFormat,
width: u32,
) -> Result<(ffi::FunctionHandle, ffi::FunctionHandle)> {
let fi = format_index(format)?;
let ti = WIDTHS.iter().position(|j| *j == width).ok_or(Error::UnsupportedProjection)?;
let f = b.functions[fi][ti].ok_or(Error::UnsupportedProjection)?;
Ok((f, b.fixups[fi][ti].ok_or(Error::UnsupportedProjection)?))
}
/// `(grid, needs fixup)`: complete tiles, or the stream-k grid when the tile count fills the SMs poorly.
fn ring_project_grid(&self, l: &Layout, rows: u32, (experts, maxr, width): (u32, u32, u32)) -> Result<(u32, bool)> {
let ntx = maxr.div_ceil(width);
let tiles =
(rows / 128).checked_mul(ntx).and_then(|n| n.checked_mul(experts)).ok_or(Error::InvalidProjectionShape)?;
if tiles.checked_mul(l.columns / l.qk).is_none_or(|n| n >= 1 << 30) {
return Err(Error::InvalidProjectionShape);
}
let sms = self.workspace.experiment.as_ref().ok_or(Error::ContextPoisoned)?.sms;
let efficiency = 100 * tiles / (sms * tiles.div_ceil(sms));
let grid = if efficiency >= 90 || crate::arch_ptx::stream_k_off() { tiles } else { sms };
Ok((grid, !tiles.is_multiple_of(grid)))
}
/// `[weights, packed, output, ids, bounds]` handles of one projection.
fn ring_project_handles(
&self,
l: &Layout,
(weights, packed, out): (usize, usize, usize),
(down, tokens, experts): (bool, u32, u32),
) -> Result<[ffi::BufferHandle; 5]> {
let wh = self.handle(weights, 0, l.raw_weight * experts as usize + 4096, 4)?;
let ph = self.handle(packed, 0, l.packed, 16)?;
let oh = self.handle(out, 0, l.output, 4)?;
let ids = self.handle(IDENTITY, 0, tokens as usize * 4, 4)?;
let offset = if down { self.counts.len() + 1 + (self.next / 16) * 17 } else { self.next };
let bounds = self.handle(BOUNDS, offset * 4, (experts as usize + 1) * 4, 4)?;
Ok([wh, ph, oh, ids, bounds])
}
/// The stream-k fixup scratch when the grid does not divide the tile count.
fn ring_project_tmp(&self, needs_fix: bool, grid: u32, width: u32) -> Result<Option<ffi::BufferHandle>> {
if !needs_fix {
return Ok(None);
}
Ok(Some(self.handle(TMP, 0, grid as usize * width as usize * 128 * 4, 4)?))
}
fn ring_project_commands(
ring: &mut copy_ring::Ring<'_, 'ctx>,
(f, fix): (ffi::FunctionHandle, ffi::FunctionHandle),
(l, grid): (Layout, u32),
([wh, ph, oh, ids, bounds], tmp): ([ffi::BufferHandle; 5], Option<ffi::BufferHandle>),
shape: ffi::MmqGroupShape,
) -> Result<()> {
use crate::ffi::original_enqueue::Command;
let routing = ffi::MmqGroupRouting { ids, bounds };
let buffers = ffi::MmqGroupBuffers { weights: wh, packed: ph, output: oh, tmp };
ring.enqueue(Command::Project(f, l, grid, ffi::MmqArguments::original_group(buffers, routing, l, shape)))?;
if let Some(tmp) = tmp {
let args = ffi::MmqFixupArguments::original_group(routing, oh, tmp, l, shape);
ring.enqueue(Command::Fixup(fix, grid, args))?;
}
Ok(())
}
}
@@ -17,7 +17,6 @@ mod full_abi;
use full_abi::{Arg as F, Arguments as FA, Module as FM};
#[allow(unsafe_code)]
mod full_mapped;
mod head_dispatch;
mod symbols;
use crate::mtp_dense_kv::original_int8::abi::LaunchShape;
use crate::native_head::OriginalMtpNativeEmbedding;
@@ -4,7 +4,7 @@
use super::{
CHUNKS, DeviceBuffer, DraftKvPolicy, Error, F, ForwardPrefix, FullCommand, LaunchShape, NativeHeadDispatch,
OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, Result, SCRATCH_FLOATS, SamplerParams,
TAIL_FLAGS, daily_mtp, fixed_entry, head_dispatch, mmvf_block, push, symbols, validate_scalar_prefix,
TAIL_FLAGS, daily_mtp, fixed_entry, mmvf_block, push, symbols, validate_scalar_prefix,
};
/// Device addresses of one matrix-vector product launch: the weight matrix, the input vector and the output vector.
@@ -1,10 +1,11 @@
//! Small command builders of the draft step tail: finiteness and Q8 flag checks, input quantization, the
//! quantized and float matrix-vector launches, and the fused MLP GR kernel launch with its 114 by-value words.
use crate::native_head_dispatch::head_dispatch;
use super::{
Error, F, ForwardPrefix, FullCommand, LaunchShape, MatVecBuffers, MatVecShape, NativeHeadDispatch,
OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, Result, TAIL_FLAGS, fixed_entry,
head_dispatch, mmvf_block, push,
mmvf_block, push,
};
impl OriginalMtpFullForward<'_> {
@@ -49,7 +50,7 @@ impl OriginalMtpFullForward<'_> {
) -> Result<()> {
let MatVecBuffers { weights: w, input: q, output: y } = buffers;
let MatVecShape { columns: n, rows: out } = shape;
let (name, grid, block, _) = head_dispatch::head_dispatch(8, n, out, 1, NativeHeadDispatch::default())?;
let (name, grid, block, _) = head_dispatch(8, n, out, 1, NativeHeadDispatch::default())?;
push(
v,
13,
@@ -1,9 +1,10 @@
//! The MoE and tail blocks of `OriginalMtpFullForward::plan` (STRA-338), recorded in the order of the former single
//! function: router, experts, shared expert and combine; then the final GR, the head and the sampler.
use crate::native_head_dispatch::head_dispatch;
use super::{
DeviceBuffer, Error, F, ForwardPrefix, FullCommand, LaunchShape, MatVecBuffers, MatVecShape,
OriginalMtpFullForward, OriginalMtpFullPolicy, Result, SamplerParams, fixed_entry, head_dispatch, push, symbols,
OriginalMtpFullForward, OriginalMtpFullPolicy, Result, SamplerParams, fixed_entry, push, symbols,
};
/// What the coupled sampler needs besides the logits.
@@ -242,7 +243,7 @@ impl OriginalMtpFullForward<'_> {
}
fn plan_head(&self, v: &mut Vec<FullCommand>, p: &ForwardPrefix<'_, '_>) -> Result<()> {
let w = &self.inner.weights;
let (name, grid, block, iq) = head_dispatch::head_dispatch(w.head_kind, 2560, w.vocab, 1, w.dispatch)?;
let (name, grid, block, iq) = head_dispatch(w.head_kind, 2560, w.vocab, 1, w.dispatch)?;
let asset = if iq { 14 } else { 13 };
let index = fixed_entry(asset, name)?;
push(v, asset, index, LaunchShape::new(grid, block, 0), self.head_args(p.q, iq)?)?;
@@ -1,5 +1,7 @@
use super::*;
use crate::NativeHeadDispatch;
//! Kernel names and launch geometry of the native and IQ head projections of the MTP draft and of the window verifier:
//! one table shared by the two (it used to be compiled twice, once under each of them).
use crate::{Error, NativeHeadDispatch, Result};
/// Kernel names of the IQ head kernels: `[old, c1, c2, c4, c8]` (kind 7 has the old kernel only).
const IQ_NAMES: [(u32, &[&str]); 7] = [
@@ -344,7 +346,7 @@ fn native_head_rows(small: bool, upstream: bool) -> usize {
}
}
pub(super) fn head_dispatch(
pub(crate) fn head_dispatch(
kind: u32,
n: usize,
v: usize,
@@ -100,6 +100,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
if op.is_err() {
break;
}
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let started = std::time::Instant::now();
let (launched, label) = self.launch_one(blas, cmd, timed)?;
op = launched;
@@ -178,6 +178,7 @@ fn fetch_worker(jobs: &[abi::Copy], next: &AtomicUsize, result: &[Mutex<Option<(
if i >= jobs.len() {
break;
}
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let t = Instant::now();
let r = jobs[i].run();
if let Ok(mut out) = result[i].lock() {
@@ -76,6 +76,7 @@ impl<'ctx> OriginalFileExpertSource<'ctx> {
Ok(v)
}
pub(in super::super) fn fill_stage(&mut self, v: usize, k: usize) -> Result<()> {
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let t = Instant::now();
let operation = (|| {
let parts = self.parts(k / EXPERTS, k % EXPERTS)?;
@@ -201,6 +201,7 @@ impl<R: OriginalGraphResources> OriginalGraphFlight<'_, '_, R> {
/// Registry's wait polls actual driver completion on a real monotonic deadline,
/// with64 pauses between polls. Timeout keeps the graph pending; it never means ready.
pub fn wait_ms(mut self, timeout: Duration) -> Result<OriginalWait> {
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let start = Instant::now();
loop {
if self.query()? {
@@ -95,6 +95,7 @@ impl<'ctx> OriginalGpuStream<'ctx> {
resources: R,
body: impl FnOnce(&mut OriginalCapture<'_, 'ctx>, &mut R) -> Result<()>,
) -> Result<OriginalGpuGraph<'ctx, R>> {
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let started = std::time::Instant::now();
let (h, mut g) = self.open_graph(policy, resources)?;
if let Err(primary) = self.record_graph(h, &mut g, policy, body) {
@@ -175,6 +175,7 @@ pub fn original_verify_live_count() -> usize {
/// from the serve watchdog thread while the owner thread is blocked in a sync.
pub fn original_verify_release_live(timeout: Duration, note: Option<&mut dyn Write>) -> bool {
let live = raise_all_released();
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let start = Instant::now();
let drained = wait_drained(&live, start, timeout);
if let Some(f) = note {
@@ -184,7 +184,12 @@ pub(super) fn hc_read_up(chain_gr: bool, full: Vec<u64>) -> Result<Launch> {
// ------------------------------------------------------------------------------------------------
/// `gr_write(Rt(t), bo_ + t*N, inj2_ + t*HC, gs, Rt(t), cs)` for one window row: `native_gr_post`.
pub(super) fn write_row(arena: &(impl ArenaMap + ?Sized), cfg: &GrConfig, row: usize, producer: &'static str) -> Result<Launch> {
pub(super) fn write_row(
arena: &(impl ArenaMap + ?Sized),
cfg: &GrConfig,
row: usize,
producer: &'static str,
) -> Result<Launch> {
if !cfg.native_mmvf {
return Err(refuse(producer));
}
@@ -91,7 +91,13 @@ impl PleScratch {
}
/// key = ple_key @ emb (BF16 MMVF, or q8_1 quantize + MMVQ for a native key).
fn plan_ple_key(arena: &(impl ArenaMap + ?Sized), ple: &PleConfig, a: &PleAddrs, emb: u64, out: &mut Vec<Launch>) -> Result<()> {
fn plan_ple_key(
arena: &(impl ArenaMap + ?Sized),
ple: &PleConfig,
a: &PleAddrs,
emb: u64,
out: &mut Vec<Launch>,
) -> Result<()> {
let key = PleScratch::at(a.scratch).key;
match a.key {
PleKey::Bf16(w) => out.push(plan_bf16_gemv(
@@ -234,14 +234,25 @@ pub(super) fn check_rows(g: &OriginalVerifyGeometry, rows: Rows) -> Result<usize
Ok(rows.len())
}
/// `n_elems` consecutive `elem`-byte items of a span starting at item `first`.
pub(super) fn items(arena: &(impl ArenaMap + ?Sized), name: &str, first: usize, count: usize, elem: usize) -> Result<u64> {
pub(super) fn items(
arena: &(impl ArenaMap + ?Sized),
name: &str,
first: usize,
count: usize,
elem: usize,
) -> Result<u64> {
arena.span(name, first * elem, count * elem)
}
pub(super) fn f32s(arena: &(impl ArenaMap + ?Sized), name: &str, first: usize, count: usize) -> Result<u64> {
items(arena, name, first, count, 4)
}
/// Word `word` of group `group`'s device plan copy (`plan_ + group * (plan_i32_ + 16)`).
pub(super) fn plan_word(arena: &(impl ArenaMap + ?Sized), g: &OriginalVerifyGeometry, group: usize, word: usize) -> Result<u64> {
pub(super) fn plan_word(
arena: &(impl ArenaMap + ?Sized),
g: &OriginalVerifyGeometry,
group: usize,
word: usize,
) -> Result<u64> {
let layout = PlanLayout::new(g.max_t * g.k);
if group > 1 || word >= layout.words {
return Err(Error::InvalidQwenShape);
@@ -18,8 +18,6 @@ use crate::native_head::native_head_row_bytes;
use crate::{Context, DeviceRef};
use crate::{Error, NativeHeadDispatch, Result};
#[path = "../mtp_dense_kv/original_int8/prefill/scalar/full_forward/head_dispatch.rs"]
mod head_dispatch;
#[cfg(test)]
#[path = "../original_verify_window_proj/tests.rs"]
@@ -4,7 +4,7 @@
use super::{
A, ArenaMap, AssetSpec, BF16, BF16_ENTRIES, Error, GdnProjectionAddrs, HEAD_IQ, HEAD_NATIVE, Launch, LaunchExtent,
NativeHeadDispatch, NativeWeight, OriginalVerifyGeometry, Projection, QsaProjectionAddrs, QuantSource, Result,
Rows, gdn_index, head_dispatch, native_head_row_bytes, qsa_index,
Rows, gdn_index, native_head_row_bytes, qsa_index,
};
/// Bytes of one q8_1-quantized activation row of `n_in` elements (`n_in/32` blocks of 36).
@@ -102,7 +102,7 @@ pub(crate) fn plan_mmvq(
) -> Result<Launch> {
let MmvqExtents { n_in, n_out, rows } = extents;
let (n_in32, n_out32) = mmvq_extents(n_in, n_out, rows)?;
let (entry, grid, block, iq) = head_dispatch::head_dispatch(w.ty, n_in, n_out, rows, dispatch)?;
let (entry, grid, block, iq) = crate::native_head_dispatch::head_dispatch(w.ty, n_in, n_out, rows, dispatch)?;
let mut args = vec![A::P(w.data)];
if iq {
args.push(A::U64(native_head_row_bytes(w.ty, n_in)? as u64));
@@ -184,6 +184,7 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
r.mark_released()
}
let mut result = self.bank.as_mut().map_or(Ok(()), OriginalVerifyBank::release_gpu_waits);
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let start = Instant::now();
let mut drained = true;
for stream in [self.compute.as_ref(), self.copy.as_ref()].into_iter().flatten() {
@@ -78,7 +78,13 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
pub fn window_logprobs(&self, targets: &[i32], extra_id: i32, out: &mut (impl Write + ?Sized)) -> Result<()> {
self.window_logprobs_topk(targets, extra_id, logpos_topk_from_environment(), out)
}
pub fn window_logprobs_topk(&self, targets: &[i32], extra_id: i32, topk: usize, out: &mut (impl Write + ?Sized)) -> Result<()> {
pub fn window_logprobs_topk(
&self,
targets: &[i32],
extra_id: i32,
topk: usize,
out: &mut (impl Write + ?Sized),
) -> Result<()> {
self.with_completed_logits(|logits, rows, vocabulary, first| {
if targets.is_empty() || targets.len() > rows {
return Err(Error::InvalidQwenShape);
@@ -131,6 +137,7 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
r.mark_released()
}
let mut result = self.bank.as_mut().map_or(Ok(()), OriginalVerifyBank::release_gpu_waits);
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let start = Instant::now();
// Original #267 bounded release: no blocking wait on a spin kernel forever.
for s in [self.compute.as_ref(), self.copy.as_ref()].into_iter().flatten() {
@@ -117,6 +117,7 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
let layer = k / groups;
let group = k % groups;
let want = window_plan::ring(layer, groups, group);
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let start = Instant::now();
if let Some(r) = &self.registration {
r.layer_step(want)
@@ -30,6 +30,7 @@ impl Physical<'_> {
/// unioned). Every sealed module is loaded; the first unsealed one fails closed AFTER that, by name.
pub(in super::super) fn ensure_window_assets(&self, specs: &[&'static kernels::AssetSpec]) -> Result<()> {
self.validate(self.context)?;
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let started = std::time::Instant::now();
let (ready, unsealed) = self.select_ready(group_specs(specs))?;
if ready.is_empty() {
@@ -35,6 +35,7 @@ struct ResidentRollback<'a, 'ctx> {
pub(super) fn lap(mark: &mut Option<std::time::Instant>, index: usize, label: &'static str) {
if let Some(at) = mark {
crate::command_profile::add("qsa", index, label, at.elapsed());
// Measurement timer, not decision logic (instant-now exception in architecture.json).
*at = std::time::Instant::now();
}
}
@@ -124,6 +124,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
let mut late = LateQueue { launches: &mut plan.late, next: 0 };
for (i, (shape, args)) in plan.commands.iter_mut().enumerate() {
self.run_late(blas, &mut late, i, timed)?;
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let started = std::time::Instant::now();
module.launch(*shape, blas.stream(), args)?;
if timed {
@@ -19,6 +19,7 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> {
) -> Result<OriginalQsaMappedAppend> {
let (plan, table) = self.arena_plan(workspace, stage, prior, inputs)?;
let timed = crate::command_profile::enabled();
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let started = std::time::Instant::now();
self.run_append(workspace, stage, &plan)?;
if timed {
@@ -104,6 +104,7 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
let ((commands, host), (hd, t)) = (buffers, run);
let timed = crate::command_profile::enabled();
let mut operation = self.submit(blas, commands, (&host.history_bytes, hd.hin, t), timed);
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let started = std::time::Instant::now();
let sync = blas.synchronize();
if operation.is_ok() && sync.is_ok() {
@@ -85,6 +85,7 @@ fn iq_gate_up(c: &mut Case) -> Fail<usize> {
fn time_ggml_gu(c: &Case) -> Fail<f64> {
let (f, a) = (c.f, &c.act[0]);
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let start = Instant::now();
for _ in 0..50 {
for r in 0..FF {
@@ -63,6 +63,7 @@ impl Shared {
}
/// Spin (then sleep) until the epoch moves past `seen`; false when the pool is stopping.
fn await_epoch(&self, id: usize, seen: u32) -> bool {
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let at = Instant::now();
let mut spins = 0u32;
while self.epoch.0.load(Ordering::Acquire) == seen {
@@ -183,6 +183,7 @@ impl ExpertPool {
if jobs.len() > 65535 {
return Err(Error::Shape);
}
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let a = Instant::now();
self.load(jobs, None)?;
if self.shared.n == 1 {
@@ -11,6 +11,7 @@ impl ExpertPool {
if jobs.len() > 16 || self.shared.n == 1 || super::super::rust_legacy::oracle_q8_zero_enabled() {
return self.whole(jobs);
}
// Measurement timer, not decision logic (instant-now exception in architecture.json).
self.split_run(jobs, Instant::now())
}
/// The two-phase (gate/up, requantize, down) single-activation split path; `t` is when the caller started timing.
@@ -8,6 +8,7 @@ impl Shared {
self.state(self.n, -12);
let mut spins = 0u32;
let mut seen = 0;
// Measurement timer, not decision logic (instant-now exception in architecture.json).
let mut t = Instant::now();
loop {
let d = self.done.0.load(Ordering::Acquire);
@@ -5,6 +5,7 @@ use super::{Duration, Instant, Ordering, Shared, trace};
/// The clock of the park/stall deadlines (one site for the three waits).
fn stall_clock() -> Instant {
// Measurement timer, not decision logic (instant-now exception in architecture.json).
Instant::now()
}
@@ -89,7 +89,8 @@ impl NativePool {
pub(super) fn phase(&mut self, mode: u32, rows: usize) {
self.phase_timed(mode, rows, 0)
}
/// `at`: first of the five timing stages of this phase (ignored when timing is off).
/// `at`: first of the five timing stages of this phase (ignored when timing is off). The stage laps are measurement
/// timers, not decision logic (instant-now exception in architecture.json).
pub(super) fn phase_timed(&mut self, mode: u32, rows: usize, at: usize) {
let on = self.timing.is_some();
let mut t = [None; 6];
@@ -56,6 +56,7 @@ impl TraceState {
/// `n` workers and the host.
pub(super) fn new(n: usize) -> Self {
Self {
// Measurement timer, not decision logic (instant-now exception in architecture.json).
start: Instant::now(),
slots: (0..=n).map(|_| Slot::default()).collect(),
task_ns: (0..TASK_TABLE).map(|_| AtomicU32::new(0)).collect(),