Expand description
A0 — native LLM benchmark harness (STELLAR §A; decisions D17 + D22).
This is the shared measurement surface for the performance push. It drives
the real inference path ([LocalLlmAgent::infer_local_model_streaming]) and
reads per-phase timing recorded inside that same path — so the existing
F16/Q8 path and the future ternary/top-k paths are measured by one harness
rather than a forked benchmark loop (D22 “shared-improvement” rule). A speedup
that shows up here is a real, attributable, end-to-end number, not a kernel
microbenchmark.
What it reports (per model / weight policy):
- cold TTFT — model not resident: wall-clock from call to first token (bundles mmap load + pipeline create + prefill + first decode);
- warm TTFT — model resident (mmap adopted, pipelines still rebuilt per call in the current architecture — that cost is intentionally included, it is what A7 will attack);
- prefill / decode tok/s from the internal phase split;
- the load / prefill / decode wall-clock breakdown.
Honest scope of this increment (A0.1): timings are host wall-clock.
GPU timestamp-query kernel isolation (D17) — requesting TIMESTAMP_QUERY on
the shared device and wrapping passes with timestamp_writes — is the A0.2
follow-on; BenchResult::gpu_timestamp_supported is false until then.
Native-only: the WASM decode path is a different beast and is benchmarked in the browser harness.
Library-ized (CLAUDE.md §11) from a single inference_bench.rs into cohesive
submodules — pure code motion, no behaviour change. The public surface is
re-exported unchanged, so crate::inference::inference_bench::<Item> resolves
exactly as before.
Re-exports§
pub use raw_decode::*;
Modules§
- raw_
decode - Fixed-step raw decoder benchmark.
Structs§
- Bench
Config - One benchmark case: a model + prompt to drive through the real path.
- Bench
GpuMeta - Bench
Result - A single benchmark row — JSON/CSV serializable.
- LlmPhase
Snapshot - Snapshot of the phase counters (last completed inference).
- Model
Meta - Model metadata captured at residency mount (best-effort).
Enums§
- Gemm
Backend - GEMM backend the inference layer selects for a given matmul shape.
Constants§
- COOP_
GEMV_ ROWS - Rows per workgroup for multi-row coop GEMV (
coop_gemv_mrin fused_transformer.wgsl). Must stay in lock-step with WGSLCOOP_ROWS.
Functions§
- add_
decode_ attn_ ns - Accumulate one layer’s attention (QKV-proj + SDPA + O-proj) wall-clock.
- add_
decode_ ffn_ ns - Accumulate one layer’s FFN (pre-norm SwiGLU) wall-clock.
- add_
decode_ forward_ ns - Accumulate one token’s transformer-forward (32-layer) wall-clock.
- add_
decode_ output_ ns - Accumulate one token’s output-projection (argmax/top-k) wall-clock.
- attention_
o_ fuse_ enabled - attention_
preproject_ enabled - awq_
sweep_ blocking - AWQ α-sweep on the ternary FFN (AWQ steps 1–3 end to end): capture activation salience from the Q8
reference at
gguf_path, then for each α compile an AWQ-scaled ternary.q42(compile_gguf_to_q42_ternary_ffn_awq), evaluate its perplexity + unique-word coherence, and return(reference_ppl, [(alpha, ppl, uniq)]). α=0.0 is plain ternary (the baseline).max_tokcaps tokens/passage to bound the sweep. Honest: this measures whether AWQ rescues ternary — it does not assume it does. Needs a GPU. - capture_
kv_ gpu_ readback - GPU-readback KV capture for the W5b sparse-dictionary go/no-go — the independent route to the
CPU-reference hook. Loads the model with an f32 KV cache, runs the REAL fast GPU decode forward
over the eval corpus, and after each passage reads the KV arena back from VRAM
([
QTensorEngine::capture_kv_f32]), accumulating up tomax_per_layerK and V vectors per layer. Because it samples the actual decode-path vectors (not the CPU reference), it cross-checks the hook capture: if both agree, the measured KV geometry is trustworthy. Stops early once every layer’s cap is hit. Needs a GPU. - compare_
topk_ decode - A1a correctness: decode the same prompt with the GPU top-k path off then on (same resident model, deterministic argmax) and return both strings. Since k=1 top-k == argmax, the texts must be byte-identical — this verifies the GEMM→top-k wiring, not just the kernel (which is oracle-tested).
- compare_
topk_ decode_ blocking compare_topk_decodeinside a fresh multi-thread runtime (residency mount needsblock_in_place).- coop_
gemv_ enabled - Whether native GEMM should run the cooperative
coop_gemvkernel rather than the naive 1-thread/rowmain. Env forces either direction; otherwise the atomic flag (default OFF). - coop_
gemv_ workgroups - Workgroup count for coop GEMV dispatch:
ceil(n_out / COOP_GEMV_ROWS). - coopmat_
gemm_ enabled - Whether the coopmat GEMM seam is armed (env forces either direction; else the flag). Being armed
does not mean coopmat runs — see
coopmat_gemm_usable, which also requires the hardware probe. - coopmat_
gemm_ usable - Whether coopmat is BOTH armed and genuinely usable on this device right now (the forge runtime
probe passes — i.e. the wgpu #9741 fix is present).
falseon wgpu 29.0.3. Feature-guarded: withwgsl-forgeoff there is no probe, so coopmat is never usable. - cpu_
attention_ enabled - Whether native attention should use the CPU reference.
- cuda_
mega_ path_ counts - (successful CUDA mega-pass forwards, explicit CUDA fallbacks).
- decode_
attn_ ffn - Read the intra-layer attention/FFN accumulators as
(attn_ns, ffn_ns)(summed over the run). - decode_
budget_ fixed_ tokens - When budget override is active, ignore EOS so A/B runs a fixed token count (prevents early-stop from inflating/deflating tok/s on short prompts).
- decode_
budget_ override - Current decode-budget override (0 = none).
- decode_
sampled_ blocking - W2: decode with the exact CPU sampler installed for the duration of the call. Returns
(text, tok/s). Restores greedy (None) afterwards so it never leaks into other tests. - decode_
with_ metrics - A1b: mount a model (auto-detecting
P64vs GGUF by magic) and run ONE decode ofpromptfordecode_tokens, returning(text, decode_tok_s). For a ternary.q42the FFN routing follows the globalset_ternary_ffntoggle, so a caller can measure GPU-ON vs CPU-OFF on identical weights. Caller sets the toggle before invoking. (Use the_blockingwrapper from sync code.) - decode_
with_ metrics_ blocking decode_with_metricsinside a fresh multi-thread runtime (residency mount needsblock_in_place).- empty_
rt - Read the empty-round-trip baseline as
(total_ns, n). - ffn_
f16_ enabled - Whether FFN weights should be promoted to f16 in VRAM for decode/prefill GEMV.
- ffn_
fusion_ enabled - Whether the native FFN should run fused (one submit/layer) rather than three GEMM round-trips.
- ffn_
fusion_ in_ resident - True when the last-built resident plan wires fused FFN expansion (not just the flag).
- gemm_
parity_ probe_ blocking - W3 — GPU↔CPU GEMM parity probe (test/diagnostic). Builds a fresh engine, synthesizes a random
Q8_0 weight matrix (
n_outrows ×n_in;n_inmust be a multiple of 32) + input fromseed, runs the GPU kernel and the CPU reference on identical bytes, and returns(max_abs_err, mean_abs_err, max_ulp, gpu_gemm_passes_profiled). A non-zero pass count proves the GPU path actually executed — the engine readback falls back to CPU when no tokio handle is present, so thert.enter()below installs one to force the real GPU path. - gemm_
parity_ probe_ f16_ blocking - W3/F16 — GPU↔CPU parity for the new F16 GEMM path (
unpack2x16floatin the shader vs the CPUdequant_f16reference). Synthesizes a random F16 weight matrix (n_outrows ×n_in; no block constraint) + input fromseed, runs both on identical bytes, returns(max_abs_err, mean_abs_err, max_ulp, gpu_gemm_passes). Same witness rule as the Q8 probe. - gpu_
topk_ enabled - Whether the GPU top-k decode path is active. The env var overrides the flag in BOTH directions
(
0/false→ off,1/true→ on); otherwise the process default (ON) applies. - gpu_
wait_ count - Re-export: GPU
submit → poll(Wait)round-trips counted during the last run (seegguf_bridge). - inference_
timeout_ ms - Effective timeout: override if non-zero, else env
QUALIA_INFERENCE_TIMEOUT_MS, else 30s. - kv_
dict_ enabled - Whether the KV cache should use the installed sparse dictionary.
- kv_
int8_ enabled - Whether the KV cache should be int8-quantized.
- output_
path_ counts - (top-k hits, argmax fallbacks) since the last reset.
- perplexity_
eval_ blocking - W1 — teacher-forced perplexity of
model_pathover the eval corpus, run through Qualia’s native engine (never an external runtime). For each corpus passage:reset_kv_cache, then per position embed →dispatch_transformer_forward→apply_output_norm_inplace→dispatch_output_logits_into→ NLL of the true next token; PPL =exp(ΣNLL / Σtokens).max_tok= 0 scores the whole passage, - phase_
snapshot - Read the phase counters recorded by the last inference call.
- record_
argmax_ fallback - Decode loop: fell back to the full-logit-readback argmax path.
- record_
cuda_ mega_ fallback - Decode loop: CUDA mega-pass was explicitly requested but failed eligibility or execution and the ordinary fallback path ran.
- record_
cuda_ mega_ hit - Decode loop: the CUDA all-layer mega-pass completed this token forward.
- record_
decode - Record the autoregressive decode loop time + tokens generated.
- record_
empty_ rt - Record the empty-round-trip baseline:
total_nsmeasured overnempty submit→wait cycles. - record_
load_ ns - Record model load/mmap-adopt + pipeline-build time (engine ready → before prefill).
- record_
prefill - Record prefill (prompt KV population) time + tokens prefilled.
- record_
resident_ fallback - Decode loop: resident path was enabled but ineligible/failed — legacy ran instead.
- record_
resident_ hit - Decode loop: the resident single-fence path produced this token.
- record_
resident_ prefill_ fallback - Prefill: resident path was enabled but ineligible/failed — legacy chunk ran instead.
- record_
resident_ prefill_ hit - Prefill: the resident single-fence-per-chunk arena populated this chunk’s KV.
- record_
sampled_ token - Decode loop: the exact CPU sampler produced this token (non-greedy path).
- record_
spec_ step - One speculative step ran (a draft was proposed + verified).
- record_
topk_ hit - Decode loop: the GPU top-k path produced the next token.
- reset_
cuda_ mega_ path_ counts - Reset the native CUDA execution counters.
- reset_
output_ path_ counts - Reset the output-projection path counters.
- reset_
phase_ metrics - Clear the phase counters before a measured run.
- reset_
resident_ path_ counts - Reset the resident-path counters.
- reset_
resident_ prefill_ counts - Reset the resident-prefill path counters.
- reset_
sampled_ token_ count - Reset the sampled-token counter.
- reset_
spec_ decode_ counts - Reset the speculative-decode counters.
- resident_
decode_ enabled - Whether native decode should run the GPU-resident single-fence token path.
- resident_
path_ counts - (resident hits, resident fallbacks) since the last reset.
- resident_
prefill_ counts - (resident-prefill hits, resident-prefill fallbacks) since the last reset.
- resident_
prefill_ enabled - Whether native prefill should run the GPU-resident single-fence-per-chunk arena.
- resident_
weights_ enabled - Whether native GEMM should bind resident per-tensor weight buffers (upload-once) rather than re-uploading the weight every token. Env forces either direction; otherwise the atomic flag.
- results_
to_ csv - CSV (header + one row per result).
- results_
to_ json - Pretty-printed JSON for a result set.
- results_
to_ table - Human-readable table for stdout.
- run_
bench - Run one benchmark case end-to-end (cold then warm) against the real path.
- run_
suite - Run a suite of cases, skipping any whose model file is absent.
- run_
suite_ blocking - Run a suite inside a fresh multi-thread Tokio runtime.
- sampled_
token_ count - Sampled tokens since the last reset.
- sampler_
config - The active decode sampler config, if a non-greedy one is installed.
- select_
gemm_ backend - Select the GEMM backend for an
m×k×nmatmul: coopmat when armed+usable and all dims are 8-mult (the tensor-core tile — batched prefill, not the m=1 decode GEMV); else cooperative GEMV when enabled; else naive. Pure + total, so it is unit-tested without a GPU. - set_
attention_ o_ fuse - set_
attention_ preproject - set_
coop_ gemv - Enable/disable the cooperative GEMV decode path (
QUALIA_LLM_COOP_GEMV). - set_
coopmat_ gemm - Arm/disarm the coopmat (tensor-core) GEMM selection seam (
QUALIA_LLM_COOPMAT). - set_
cpu_ attention - Enable/disable the native CPU-attention reference path (
QUALIA_LLM_CPU_ATTENTION). - set_
decode_ budget_ override - Set a fixed decode-token budget for benchmarking (0 = production default).
- set_
ffn_ f16 - Enable/disable FFN quant→f16 promotion at resident-plan build (
QUALIA_LLM_FFN_F16). - set_
ffn_ fusion - Enable/disable the fused single-submit FFN path (
QUALIA_LLM_FFN_FUSION). - set_
ffn_ fusion_ in_ resident - set_
gpu_ topk - Enable/disable the GPU top-k decode path (
QUALIA_LLM_GPU_TOPK). - set_
inference_ timeout_ override_ ms - Set wall-clock decode timeout in ms (0 = production default 30_000).
- set_
kv_ dict - Enable/disable the sparse-dictionary KV cache (
QUALIA_LLM_KV_DICT). - set_
kv_ int8 - Enable/disable the int8 KV cache (
QUALIA_LLM_KV_INT8). - set_
resident_ decode - Enable/disable the resident-token single-fence decode (
QUALIA_LLM_RESIDENT_DECODE). - set_
resident_ prefill - Enable/disable the resident single-fence-per-chunk prefill path (
QUALIA_LLM_RESIDENT_PREFILL). - set_
resident_ weights - Enable/disable the resident per-tensor weight buffers (
QUALIA_LLM_RESIDENT_WEIGHTS). - set_
sampler_ config - Install the decode sampler config (
Nonerestores greedy argmax). - set_
spec_ decode - Enable/disable prompt-lookup speculative decode (
QUALIA_LLM_SPEC_DECODE). Runtime mode switch — the desktop UI / host calls this to flip between exact single-token decode and speculative decode. - set_
ternary_ ffn - Enable/disable the resident 2-bit GPU ternary-FFN path (
QUALIA_LLM_TERNARY_FFN). - spec_
decode_ counts - (spec steps, tokens drafted, draft tokens accepted) since the last reset.
- spec_
decode_ enabled - Whether the decode loop should run prompt-lookup speculative decode (the effective mode: env var wins if set, else the runtime flag). Read this to reflect the current mode in a UI.
- spec_
verify_ probe_ blocking - W6a — batched verify-primitive correctness probe. Prefills
prompt(positions[0, p),p = prompt_len-1), snapshots the KV cache, then: - ternary_
ffn_ enabled - Whether the GPU ternary-FFN path is active (atomic flag OR the env var). When false, ternary FFN GEMMs fall back to the CPU oracle (correct, slower) — the toggle’s OFF baseline.