diff --git a/.gitignore b/.gitignore
index e706a14847..9679195d83 100644
--- a/.gitignore
+++ b/.gitignore
@@ -25,12 +25,18 @@
/tests/cuda_long_context_smoke
/tests/test_layer_pack
/tests/test_metal_session_batch
+/tests/test_metal_indexer_q4
+/tests/test_metal_q4_qb_f16_cache
+/tests/test_metal_q4_prefill_pair
+/tests/test_metal_q4_streams
/tests/test_mxfp4_cuda
/tests/test_mxfp4_dot
/tests/test_mxfp4_metal
/tests/test_q4k_dot
/tests/test_sampling
/tests/test_glm53_kda
+/tests/test_quantizer_indexer_q4
+/tests/test_rocm_q4_dense_pair
/tests/test_deepseek4_vision_image
*.o
*.dSYM/
@@ -41,3 +47,8 @@ __pycache__/
/misc/
.*.swp
.DS_Store
+
+# Local speed benchmark outputs
+/speed-bench/*.csv
+/speed-bench/*_logprobs.json
+/speed-bench/*_logits/
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index f9bb07168b..f915b92629 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -25,6 +25,14 @@ The C test runner is `ds4_test`. Running it without arguments is equivalent to
make test
```
+If a change adds, renames, removes, or changes the parsing/default/effect of an
+environment variable, update `scripts/environment_variables.tsv`, regenerate
+the complete reference, and verify that it is current:
+
+```sh
+make environment-docs
+```
+
Useful narrower checks:
```sh
diff --git a/ENVIRONMENT_VARIABLES.md b/ENVIRONMENT_VARIABLES.md
new file mode 100644
index 0000000000..f169704b60
--- /dev/null
+++ b/ENVIRONMENT_VARIABLES.md
@@ -0,0 +1,1481 @@
+# Environment variables
+
+Command-line options are the supported interface for normal inference. The
+first part of this document is the curated, user-facing reference for switches
+used to isolate optimized paths, require test coverage, or collect diagnostics.
+The generated inventory below it lists every environment name consumed by the
+runtime, tests, and maintained tools. Inclusion in that complete inventory does
+not make an internal tuning knob a stable API.
+
+Run `make check-environment-docs` after adding, renaming, or removing an
+environment variable. Regenerate the inventory with
+`python3 scripts/generate_environment_variables.py`.
+
+Most backend switches are cached on first use. Start a new process when
+changing them. Unless a row says otherwise:
+
+- use the documented value `1`; many rollback switches are presence-based, so
+ setting them to `0` still enables the rollback and they must instead be unset;
+- `DISABLE` or `NO` is the rollback switch and takes precedence;
+- `REQUIRE` turns an eligible silent fallback into an error, so tests cannot
+ pass without exercising the intended path;
+- `STATS`, `PROFILE`, and `ORACLE` are diagnostic and may perturb timing;
+- benchmark controls and candidates in separate processes.
+
+## Greedy top-1 readback
+
+| Variable | Default behavior and purpose |
+| --- | --- |
+| `DS4_DISABLE_GREEDY_TOP1_READBACK=1` | Restore the legacy full-logits readback and CPU argmax. Unset uses device top-1 plus a four-byte readback for eligible single-tier greedy generation, including SSD streaming, on Metal, CUDA, and ROCm. |
+
+## Metal
+
+| Variable | Default behavior and purpose |
+| --- | --- |
+| `DS4_METAL_PREFILL_CHUNK=N` | Set the prefill cap when `--prefill-chunk` is absent; the CLI option takes precedence. This historical name is consumed by the shared graph planner rather than by a Metal kernel alone. |
+| `DS4_METAL_NO_RESIDENCY=1` | Skip creation and residency requests for the model-view residency set. Diagnostic rollback for resident, non-streaming models. |
+| `DS4_METAL_DISABLE_QUEUE_RESIDENCY_SET=1` | Still create, commit, and request the model residency set, but do not attach it to Metal command queues. This isolates queue-residency behavior without disabling the complete residency policy. |
+| `DS4_METAL_DISABLE_DECODE_ARGMAX_TOP1=1` | Restore the generic full argsort used by Metal argmax. Unset uses the dedicated two-stage top-1 reduction for eligible large decode rows. |
+| `DS4_METAL_REQUIRE_DECODE_ARGMAX_TOP1=1` | Fail closed instead of using generic argsort when a row of at least 4096 logits cannot execute the dedicated top-1 path. Intended for correctness and performance oracles. |
+| `DS4_METAL_STREAMING_EXPERT_NOCACHE=1` | Reopen the Metal SSD expert file with `F_NOCACHE` so streamed experts do not displace the dense working set from the page cache. Leave unset for cached `pread`. |
+| `DS4_METAL_STREAMING_EXPERT_PREAD_SPLIT=N` | Split each expert read into 1–8 aligned requests. The automatic value is 1 below 64 configured cache experts and 4 at 64 or more. |
+| `DS4_METAL_DISABLE_Q4_DENSE_PAIR=1` | Split the default Metal Q-A/KV Q4 pair back into two standalone projections. |
+| `DS4_METAL_ENABLE_Q4_PREFILL_PAIR_F16_RHS=1` | On Apple M1–M4, opt into the Q-A/KV prefill pair that materializes their shared F32 activation as F16 once for exact 32-token tiles through N=128. |
+| `DS4_METAL_DISABLE_Q4_PREFILL_PAIR_F16_RHS=1` | Dominant rollback to two standalone Q4_K/F32-RHS prefill projections. |
+| `DS4_METAL_REQUIRE_Q4_PREFILL_PAIR_F16_RHS=1` | Request the shared-F16-RHS pair and fail closed if its device, shape, storage, or buffer contract is unavailable. Intended for strict A/B oracles. |
+| `DS4_METAL_DISABLE_Q4_ATTN_OUT_A_DIRECT=1` | Restore the generic route-map/work-list Q4 attention output-A path. Unset uses the bit-identical fixed-route direct kernel by default for eligible Apple M1–M4 `4096 -> 1024`, eight-group prefills at N=512–4096. Any defined value, including `0`, disables the specialization. |
+| `DS4_METAL_REQUIRE_Q4_ATTN_OUT_A_DIRECT=1` | Require the fixed-route Q4 attention output-A kernel and fail closed before dispatch if its device, shape, concurrency, pipeline, or memory contract is unavailable. Intended for production-shape correctness and performance oracles; `DISABLE` wins. |
+| `DS4_METAL_DISABLE_M1_IQ2_MID_ONLY=1` | Restore the canonical IQ2 address-table gate/up producer on the exact M1 SSD-streaming decode shape. The specialization is automatic by default. |
+| `DS4_METAL_REQUIRE_M1_IQ2_MID_ONLY=1` | Fail closed when an otherwise eligible M1 IQ2 mid-only dispatch cannot use the specialization. |
+| `DS4_METAL_ENABLE_M1_IQ2_MID_ONLY=1` | Legacy spelling retained for migration notes only. The runtime does not read it; the path is automatic and this setting is ignored. |
+| `DS4_METAL_DISABLE_IQ2_XXS_SSD_PREFILL_MM=1` | Restore sparse matvec for an eligible grouped IQ2 SSD-prefill chunk. |
+| `DS4_METAL_REQUIRE_IQ2_XXS_SSD_PREFILL_MM=1` | Require grouped IQ2 SSD-prefill MM for eligible chunks and reject insufficient cache instead of silently falling back. |
+| `DS4_METAL_DISABLE_Q4_SSD_PREFILL_ATTN_OUT_SCALE_META=1` | Restore per-SIMDgroup Q4_K scale/min unpacking inside the opt-in SSD-prefill attention-output exact-N path. Shared scale metadata is automatic when that path is enabled and the PSO and threadgroup memory are available. |
+| `DS4_METAL_REQUIRE_Q4_SSD_PREFILL_ATTN_OUT_SCALE_META=1` | Enable the Q4_K SSD-prefill attention-output exact-N path and fail closed unless its shared scale/min metadata PSO is used. Intended for oracles and A/B tests. |
+| `DS4_METAL_ENABLE_STREAMING_PREFILL_EXPERT_READAHEAD=1` | Restore the historical `F_RDADVISE` plus parallel-`pread` sequence for cold-storage A/B tests. Normal grouped prefill skips the redundant hint. |
+
+The detailed Metal A/B contracts and expected oracle counters live in
+[`QA_BEFORE_RELEASES.md`](QA_BEFORE_RELEASES.md).
+
+## CUDA Q4 and Q8 diagnostics
+
+| Variable | Default behavior and purpose |
+| --- | --- |
+| `DS4_CUDA_DECODE_GRAPHS=0` | Disable CUDA decode graph capture. Unset, `1`, `on`, `yes`, or `true` enables capture; `0`, `off`, `no`, or `false` disables it. Oracle modes may also suppress capture. |
+| `DS4_CUDA_DISABLE_Q4_ATTN_Q_B_TRANSIENT_F16=1` | Restore native Q4_K `attn_q_b` for automatic long resident prefills. The transient path is otherwise eligible from 4096 tokens when the single-GPU model image is physically device-resident and retains only one reusable expanded matrix; explicit persistent-cache controls remain independent. |
+| `DS4_CUDA_Q4_ATTN_Q_B_TRANSIENT_F16_MIN_TOKENS=N` | Override the automatic transient Q4_K-to-F16 crossover (default 4096 tokens) for single-GPU, device-image-resident, non-SSD, non-quality prefills. |
+| `DS4_CUDA_DISABLE_Q4_DENSE_PAIR=1` | Split the Q-A/KV Q4 pair back into two standalone projections. |
+| `DS4_CUDA_NO_Q4_GB10_FAST=1` | Umbrella rollback for the GB10-specific Q4 choices; it does not disable the older cross-CUDA dense pair. |
+| `DS4_CUDA_ENABLE_Q4_GROUPED_ATTN_A_BATCH=1` | Enable grouped attention-A for two-to-eight-token GB10 verifier batches. |
+| `DS4_CUDA_REQUIRE_Q4_GROUPED_ATTN_A_BATCH=1` | Fail closed if that grouped batch path is unavailable. |
+| `DS4_CUDA_ENABLE_Q4_GROUPED_ATTN_A_PREFILL=0` | Compatibility opt-out for the default GB10 Q4 attention-A grouped prefill path above eight tokens; any other nonempty value explicitly requests it. |
+| `DS4_CUDA_NO_Q4_GROUPED_ATTN_A_PREFILL=1` | Dominant rollback from the default grouped Q4 attention-A prefill path to eight pack/MMQ/unpack projections. Any defined value disables the path. |
+| `DS4_CUDA_REQUIRE_Q4_GROUPED_ATTN_A_PREFILL=1` | Request the grouped Q4 attention-A prefill candidate and fail before enqueue when its GB10, shape, residency, or buffer contract is unavailable. |
+| `DS4_CUDA_NO_Q4_GROUPED_ATTN_A_Q81=1` | Narrow rollback from the default fixed-layout `K=4096`, `groups=8` Q8_1 producer to the canonical strided producer while retaining grouped prefill. Any defined value disables the specialized kernel. |
+| `DS4_CUDA_REQUIRE_Q4_GROUPED_ATTN_A_Q81=1` | Request the fixed-layout eight-warp Q8_1 producer and fail before enqueue on rollback or ineligibility. |
+| `DS4_CUDA_ENABLE_Q4_GROUPED_ATTN_A_SINGLE_GRID=1` | On eligible GB10 prefills, submit the eight grouped attention-A MMQs as one grid.z launch while retaining a separate stream-K coordinate and fixup slice per group. |
+| `DS4_CUDA_DISABLE_Q4_GROUPED_ATTN_A_SINGLE_GRID=1` | Dominant rollback from the single-grid experiment to the established one-MMQ-grid-per-group path. |
+| `DS4_CUDA_REQUIRE_Q4_GROUPED_ATTN_A_SINGLE_GRID=1` | Require the single-grid grouped attention-A submission and fail closed on rollback, ineligibility, or dispatch failure. |
+| `DS4_CUDA_Q4_GROUPED_ATTN_A_ORACLE=1` | Compare grouped attention-A with the canonical result and retain the canonical output. Disable graph capture for this diagnostic. |
+| `DS4_CUDA_ENABLE_Q4_K1024_PERSISTENT=1` | Enable the experimental persistent-CTA kernel for the exact `32768x1024` Q4 shape. |
+| `DS4_CUDA_NO_Q4_K1024_PERSISTENT=1` | Roll back the persistent K1024 experiment. |
+| `DS4_CUDA_REQUIRE_Q4_K1024_PERSISTENT=1` | Require the K1024 candidate before enqueue instead of silently using canonical MMVQ. |
+| `DS4_CUDA_Q4_MMQ_16WARP=1` | Request the experimental exact-integer m128n128 16-warp Q4_K kernel for eligible CUDA prefills. Standalone dense admits `M>=1024` and `K<=8192`, including attention output-B; dense-pair shares one Q8_1 activation, admits legs down to `M=512`, and remains bounded to `K<=4096`. Candidate grids require at least 80% whole-tile SM-wave efficiency; below the canonical 90% cutoff the kernel mirrors canonical Stream-K partitioning and fixup so the FP32 reduction tree is unchanged. Ineligible optional shapes fall back. |
+| `DS4_CUDA_NO_Q4_MMQ_16WARP=1` | Roll back the 16-warp Q4_K prefill experiment. This value-aware switch overrides request and require. |
+| `DS4_CUDA_REQUIRE_Q4_MMQ_16WARP=1` | Request the 16-warp Q4_K prefill kernel and fail closed instead of silently measuring another MMQ/Q8_K path; a dense-pair requires both legs to be eligible. Decode/speculative batches of at most eight tokens remain on MMVQ. |
+| `DS4_CUDA_ENABLE_Q8_FOLD=1` | Enable the experimental one-shot Q8_1 producer-to-consumer fold. |
+| `DS4_CUDA_NO_Q8_FOLD=1` | Dominant rollback for the Q8_1 fold. |
+| `DS4_CUDA_Q8_FOLD_ORACLE=1` | Compare fresh canonical Q8_1 bytes and consumer outputs. Use with `DS4_CUDA_DECODE_GRAPHS=0`; require nonzero calls and zero mismatches/skips. |
+| `DS4_CUDA_MOE_PROFILE=1` | Print `cudaEvent` stage timings for routed-MoE launches, including resident IQ2 pair/SwiGLU/Q2-down/sum and aligned SoA/direct-D2R fast paths. Profiling is diagnostic and synchronizes the measured stream; the added aligned-IQ2 recorder deliberately excludes one-token graph-captured decode. |
+
+## ROCm Q4 and IQ2/Q2 diagnostics
+
+| Variable | Default behavior and purpose |
+| --- | --- |
+| `DS4_ROCM_DISABLE_Q4_ATTN_Q_B_TRANSIENT_F16=1` | Restore native Q4_K `attn_q_b` for automatic long resident prefills. The transient path is otherwise eligible from 4096 tokens when every `attn_q_b` source is already in a device image or device-backed resident range and retains only one reusable expanded matrix; explicit persistent-cache controls remain independent. |
+| `DS4_ROCM_Q4_ATTN_Q_B_TRANSIENT_F16_MIN_TOKENS=N` | Override the automatic transient Q4_K-to-F16 crossover (default 4096 tokens) for device-resident, non-SSD, non-quality prefills. |
+| `DS4_ROCM_DISABLE_Q4_PREFILL_TILE8=1` | Restore the legacy Q4 prefill kernel. TILE8 is automatic for validated chunks of 9 through 4096 tokens. |
+| `DS4_ROCM_REQUIRE_Q4_PREFILL_TILE8=1` | Fail closed when an eligible Q4 prefill call cannot use TILE8. |
+| `DS4_ROCM_ENABLE_Q4_PREFILL_TILE8=1` | Legacy spelling retained for migration notes only. The runtime does not read it; TILE8 is automatic and this setting is ignored. |
+| `DS4_ROCM_ENABLE_Q4_PREFILL_Q8_K_WAVE32=1` | On gfx1151 wave32, opt into the no-LDS Q8_K activation quantizer that assigns one 256-value block to each wave before the exact Q4 prefill matmul. This exact path takes precedence over automatic direct-Q4 WMMA; `REQUIRE_Q4_PREFILL_WMMA` overrides an optional request, while dual REQUIRE fails closed. |
+| `DS4_ROCM_DISABLE_Q4_PREFILL_Q8_K_WAVE32=1` | Dominant rollback to the canonical one-workgroup-per-Q8_K-block quantizer. |
+| `DS4_ROCM_REQUIRE_Q4_PREFILL_Q8_K_WAVE32=1` | Require the wave32 quantizer for strict prefill A/B runs; unsupported scope/device, rollback, or an incompatible required F16/WMMA path fails closed. |
+| `DS4_ROCM_ENABLE_Q4_PREFILL_WMMA=0/1` | Compatibility control for the resident gfx1151 wave32 direct-Q4 WMMA prefill kernel at 256–4096 tokens. Unset keeps the automatic standalone and attention-output-A paths, while attention-output B stays on Q8_K+TILE8. A true value explicitly retains those eligible A paths but no longer opts B into direct WMMA; an explicit false value opts out unless `REQUIRE` is also set. Use `DISABLE=1` for an authoritative rollback. The kernel uses transient F16 register dequantization and F32 accumulation, with 64 rows below output dimension 1024, 128 rows below 8192, and 256 rows otherwise; aligned 256-row launches use K128/P144 and float4 activation staging by default. |
+| `DS4_ROCM_ENABLE_Q4_PREFILL_WMMA_K64=0/1` | Base staging control for an otherwise eligible direct-Q4 WMMA launch. Unset or true uses K64/P80 on 64/128-row or K128-incompatible launches and permits the K128/P144 default on aligned 256-row launches. `0`/`false`/`no`/`off` suppresses both wider stages and rolls back selectively to K32, while `DS4_ROCM_DISABLE_Q4_PREFILL_WMMA=1` rolls back direct WMMA entirely. |
+| `DS4_ROCM_DISABLE_Q4_PREFILL_WMMA_K128=1` | Value-aware opt-out for the default K128/P144 stage on aligned 256-row direct-Q4 WMMA launches, targeting resident `attn_q_b`. Unset or `0`/`false`/`no`/`off` keeps K128; empty or any other value rolls the same launch back to K64/P80. Incompatible alignment or row geometry also uses K64, while `DS4_ROCM_ENABLE_Q4_PREFILL_WMMA_K64=0` still rolls back to K32. This setting has no effect when the persistent or automatic transient F16 `attn_q_b` path owns the projection. |
+| `DS4_ROCM_Q4_PREFILL_WMMA_ROW_TILE=64|128|256` | Override the direct-Q4 WMMA output-row tile. The default uses 64 rows below output dimension 1024, 128 below 8192, and 256 otherwise; `64` also retains the prior kernel geometry as an A/B control. |
+| `DS4_ROCM_ENABLE_Q4_PREFILL_WMMA_SSD=1` | Explicitly allow direct-Q4 WMMA during SSD streaming only when each complete projection weight range is already backed by physical device storage. It opts attention-output A into WMMA while B remains on Q8_K+TILE8, and never treats mapped/registered host memory as resident. |
+| `DS4_ROCM_DISABLE_Q4_PREFILL_WMMA=1` | Dominant value-aware opt-out for the automatic direct-Q4 WMMA path, including explicit resident or SSD requests. |
+| `DS4_ROCM_REQUIRE_Q4_PREFILL_WMMA=1` | Require direct-Q4 WMMA for every selected projection and fail closed on an unsupported device/shape, quality mode, rollback, or SSD weight range that is not physically device-resident. In an all-Q4 attention-output batch this is the only control that selects the numerically compounded direct-WMMA B stage; it is a diagnostic assertion for strict kernel A/B oracles, not a quality-sensitive runtime setting. |
+| `DS4_ROCM_Q4_PREFILL_TILE8_STATS=1` | Report dense, pair, attention-batch, token, and direct-WMMA K32/K64/K128 dispatch counters at process exit. |
+| `DS4_ROCM_ENABLE_Q4_DENSE_PAIR=1` | Share one Q8_K activation quantization between the two Q4 dense projections. This pair remains opt-in. |
+| `DS4_ROCM_DISABLE_Q4_DENSE_PAIR=1` | Dominant rollback for the ROCm Q4 dense pair. |
+| `DS4_ROCM_ENABLE_Q4_GROUPED_ATTN_A=1` | Extend the two-launch grouped attention-A path outside its default scope. The exact caller-marked resident decode shape `groups=8, N=1, K=4096, M=1024` is automatic; row-at-a-time batch fallbacks are not. |
+| `DS4_ROCM_DISABLE_Q4_GROUPED_ATTN_A=1` | Dominant rollback to eight standalone Q4 attention-A projections, including for the resident default. |
+| `DS4_ROCM_REQUIRE_Q4_GROUPED_ATTN_A=1` | Request grouped attention-A for eligible non-default shapes and fail closed on fallback; `DISABLE` remains authoritative. |
+| `DS4_ROCM_Q4_GROUPED_ATTN_A_STATS=1` | Report grouped calls, dispatches, groups, fallbacks, and failures. |
+| `DS4_ROCM_ENABLE_IQ2_MOE_WMMA_TAIL_CULL=1` | Opt into inactive-tail wave culling in the resident IQ2 gate/up and Q2 down hot-list rocWMMA prefill kernels. Requires a runtime wave width of 32; default is off pending hardware benchmarks. |
+| `DS4_ROCM_DISABLE_IQ2_MOE_WMMA_TAIL_CULL=1` | Dominant value-aware rollback for the IQ2/Q2 rocWMMA tail-wave candidate. Use as the baseline arm even though the candidate is currently off by default. |
+| `DS4_ROCM_IQ2_MOE_WMMA_PROFILE=1` | Measure only the affected IQ2 gate/up and Q2 down rocWMMA kernels with GPU events. A profiled eligible call fails rather than reporting a partial or scalar-fallback measurement. |
+
+Run `make test-strix-rocm-q4-parity` and
+`make test-strix-rocm-q4-prefill` on a `gfx1151` Strix Halo host before making
+performance claims. The synthetic oracle proves layout and numerical parity;
+it does not by itself prove that a complete Q4 model fits safely in GTT.
+
+## Historical `DS4_METAL_*` graph controls
+
+The shared graph implementation predates the CUDA backend and retained a few
+`DS4_METAL_*` names. In a non-ROCm GPU build, these controls affect the shared
+Metal/CUDA graph policy; ROCm explicitly ignores them:
+
+- `DS4_METAL_DISABLE_HC_FUSION=1`
+- `DS4_METAL_DISABLE_HC_NORM_FUSION=1`
+- `DS4_METAL_DISABLE_KV_FUSION=1`
+- `DS4_METAL_DISABLE_QKV_NORM_FUSION=1`
+- `DS4_METAL_DISABLE_QKV_PAIR_PROJ=1`
+- `DS4_METAL_DISABLE_COMPRESSOR_PAIR_PROJ=1`
+- `DS4_METAL_DISABLE_ATTN_OUT_HC_FUSION=1`
+- `DS4_METAL_DISABLE_SHARED_DOWN_HC_FUSION=1`
+
+The prefix is historical rather than an indication that these particular
+switches are always Metal-only. New backend-specific controls should use the
+backend they actually configure (`DS4_CUDA_*` or `DS4_ROCM_*`) instead of
+extending this legacy naming.
+
+
+## Complete implementation inventory
+
+This section is generated by `scripts/generate_environment_variables.py`; do not edit it by hand.
+Human-reviewed value/default and purpose metadata lives in
+`scripts/environment_variables.tsv`; the generator verifies it against the source tree.
+It lists every `DS4_*` string consumed by production C/C++/Objective-C/CUDA/ROCm
+sources, including names passed indirectly through helper functions, macros, and
+source-specification arrays. Unless a variable appears in the user-facing reference
+above, it is an unstable internal diagnostic or tuning interface. The linked source
+remains normative for exact eligibility
+gates, bounds, and architecture-specific defaults.
+
+Inventory totals: **1083 `DS4_*` runtime variables** and
+**6 external runtime variables**.
+The auxiliary inventories contain **118 test/test-fixture entries**
+and **19 tool/wrapper entries**.
+
+
+Metal (447)
+
+| Variable | Accepted value and default | Effect | Source |
+| --- | --- | --- | --- |
+| `DS4_METAL_ARGSORT_SOURCE` | file path; unset/empty: use the in-tree Metal source file | Overrides the argsort Metal kernel source file loaded at runtime. | [ds4_metal.m:4943](ds4_metal.m#L4943) |
+| `DS4_METAL_ATTN_OUT_STAGE_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for attn out stage. | [ds4.c:65151](ds4.c#L65151) |
+| `DS4_METAL_BIN_SOURCE` | file path; unset/empty: use the in-tree Metal source file | Overrides the binary operations Metal kernel source file loaded at runtime. | [ds4_metal.m:4952](ds4_metal.m#L4952) |
+| `DS4_METAL_COMPRESSOR_PAIR_NR4` | presence control; unset: off/default; any value including 0 enables | Selects the NR4 compressor-pair variant. | [ds4_metal.m:2651](ds4_metal.m#L2651) |
+| `DS4_METAL_CONCAT_SOURCE` | file path; unset/empty: use the in-tree Metal source file | Overrides the concatenation Metal kernel source file loaded at runtime. | [ds4_metal.m:4945](ds4_metal.m#L4945) |
+| `DS4_METAL_CPY_SOURCE` | file path; unset/empty: use the in-tree Metal source file | Overrides the copy Metal kernel source file loaded at runtime. | [ds4_metal.m:4944](ds4_metal.m#L4944) |
+| `DS4_METAL_DECODE_INDEXER_SPARSE_THRESHOLD` | integer in {64,128,256,512,1024,2048,4096}; default 1024; invalid restores default | Sets the compressed-row crossover from dense to sparse indexed attention. | [ds4.c:20352](ds4.c#L20352) |
+| `DS4_METAL_DECODE_STAGE_PROFILE` | unset: off; 1/true/yes/on/all enables all layers; a layer index selects one; 0/false/no/off disables | Prints timing/profile diagnostics for decode stage. | [ds4.c:17568](ds4.c#L17568) |
+| `DS4_METAL_DECODE_STAGE_PROFILE_LAYER` | single unsigned layer index; unset/empty: all layers enabled by the parent profile; invalid matches no layer | Restricts the corresponding shared graph stage profiler to one layer. | [ds4.c:29120](ds4.c#L29120) |
+| `DS4_METAL_DENSE_SOURCE` | file path; unset/empty: use the in-tree Metal source file | Overrides the dense matmul Metal kernel source file loaded at runtime. | [ds4_metal.m:4936](ds4_metal.m#L4936) |
+| `DS4_METAL_DISABLE_AFFINE_ROPE_PAIR` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables affine RoPE pair. | [ds4_metal.m:25171](ds4_metal.m#L25171) |
+| `DS4_METAL_DISABLE_ATTN_OUT_HC_FUSION` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Disables attn out HC fusion. | [ds4.c:20477](ds4.c#L20477) |
+| `DS4_METAL_DISABLE_ATTN_OUT_IDS_CACHE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables attn out ids cache. | [ds4_metal.m:27771](ds4_metal.m#L27771) |
+| `DS4_METAL_DISABLE_ATTN_OUT_LOW_DIRECT` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables attn out low direct. | [ds4_metal.m:27760](ds4_metal.m#L27760) |
+| `DS4_METAL_DISABLE_BATCH_HC_NORM_FUSION` | nonempty value other than exact 0 disables; unset/empty/0 leaves the default enabled path | Dominant rollback for batched HC norm fusion. | [ds4.c:20457](ds4.c#L20457) |
+| `DS4_METAL_DISABLE_COMPRESSOR_APE_ADD` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables compressor APE add. | [ds4_metal.m:25393](ds4_metal.m#L25393) |
+| `DS4_METAL_DISABLE_COMPRESSOR_EXACT_POOL_RATIO4` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables compressor exact pool ratio4. | [ds4_metal.m:26379](ds4_metal.m#L26379) |
+| `DS4_METAL_DISABLE_COMPRESSOR_PAIR_PROJ` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Disables compressor pair proj. | [ds4_metal.m:23248](ds4_metal.m#L23248) |
+| `DS4_METAL_DISABLE_COMPRESSOR_QUAD_STORE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables compressor quad store. | [ds4.c:23534](ds4.c#L23534) |
+| `DS4_METAL_DISABLE_COMPRESSOR_RATIO4_DIRECT_POOL` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables compressor ratio4 direct pool. | [ds4_metal.m:26245](ds4_metal.m#L26245) |
+| `DS4_METAL_DISABLE_COMPRESSOR_RATIO4_PACK_FUSION` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables compressor ratio4 pack fusion. | [ds4_metal.m:26199](ds4_metal.m#L26199) |
+| `DS4_METAL_DISABLE_COMPRESSOR_STORE_ONE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables compressor store one. | [ds4_metal.m:23249](ds4_metal.m#L23249) |
+| `DS4_METAL_DISABLE_CONTIG_F16_F16_COPY` | value-aware boolean; unset: off; empty/1/true/yes/on enables; 0/false/no/off disables | Disables contig F16 F16 copy. | [ds4_metal.m:29562](ds4_metal.m#L29562) |
+| `DS4_METAL_DISABLE_CONTIG_F32_F16_COPY` | value-aware boolean; unset: off; empty/1/true/yes/on enables; 0/false/no/off disables | Disables contig F32 F16 copy. | [ds4_metal.m:29338](ds4_metal.m#L29338) |
+| `DS4_METAL_DISABLE_DECODE_ARGMAX_TOP1` | presence rollback; unset uses the dedicated two-dispatch top-1 reduction for eligible large Metal rows; any defined value including empty or 0 restores the generic full argsort | Restore the generic indexer argsort for decode argmax A/B and emergency rollback. | [ds4_metal.m:21517](ds4_metal.m#L21517) |
+| `DS4_METAL_DISABLE_DECODE_NORM_EXACT_VIEWS` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables decode norm exact views. | [ds4_metal.m:36207](ds4_metal.m#L36207) |
+| `DS4_METAL_DISABLE_DECODE_RAW_GATHERED_ATTN` | presence rollback; unset: raw-only decode uses gathered attention; any value including 0 restores the legacy raw path | Restores the separate raw-only attention path instead of gathered staging and attention. | [ds4_metal.m:32968](ds4_metal.m#L32968) |
+| `DS4_METAL_DISABLE_DECODE_RAW_PACKED32` | presence rollback; unset: raw-only gathered attention may use packed32; any value including 0 disables it for raw-only layers | Disables the packed32 reduce kernel for raw-only gathered attention while leaving compressed layers unchanged. | [ds4_metal.m:31464](ds4_metal.m#L31464) |
+| `DS4_METAL_DISABLE_DECODE_ROUTER_BIAS_EXACT_VIEWS` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables decode router bias exact views. | [ds4_metal.m:39397](ds4_metal.m#L39397) |
+| `DS4_METAL_DISABLE_DSPARK_CAPTURE_FUSED_LAST` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Disables DSpark capture fused last. | [ds4.c:28361](ds4.c#L28361) |
+| `DS4_METAL_DISABLE_DSPARK_EXACTN_BATCH_HEAD` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Disables DSpark exactn batch head. | [ds4.c:37728](ds4.c#L37728) |
+| `DS4_METAL_DISABLE_EXACT_ROWS_PERSISTENT_CACHE` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Disables exact rows persistent cache. | [ds4_metal.m:13000](ds4_metal.m#L13000) |
+| `DS4_METAL_DISABLE_GATHERED_KV_PAD_FUSION` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables gathered KV pad fusion. | [ds4_metal.m:29706](ds4_metal.m#L29706) |
+| `DS4_METAL_DISABLE_GATHERED_KV_STAGE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables gathered KV stage. | [ds4_metal.m:29677](ds4_metal.m#L29677) |
+| `DS4_METAL_DISABLE_GLM_DECODE_KV_GROUP4` | value-aware boolean; unset: off; empty/1/true/yes/on enables; 0/false/no/off disables | Disables GLM decode KV group4. | [ds4_metal.m:36742](ds4_metal.m#L36742) |
+| `DS4_METAL_DISABLE_GLM_QKLOW_SG` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables GLM qklow sg. | [ds4_metal.m:37865](ds4_metal.m#L37865) |
+| `DS4_METAL_DISABLE_GLM_STREAMING_EXPERT_EARLY_LOAD` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables GLM streaming expert early load. | [ds4_metal.m:18058](ds4_metal.m#L18058) |
+| `DS4_METAL_DISABLE_GLM_STREAMING_EXPERT_SPLIT` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables GLM streaming expert split. | [ds4_metal.m:39796](ds4_metal.m#L39796) |
+| `DS4_METAL_DISABLE_GLM_STREAMING_PREFILL_FULL_LAYER` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables GLM streaming prefill full layer. | [ds4.c:42710](ds4.c#L42710) |
+| `DS4_METAL_DISABLE_GLM_STREAMING_PREFILL_FULL_LAYER_PREPARE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables GLM streaming prefill full layer prepare. | [ds4.c:42728](ds4.c#L42728) |
+| `DS4_METAL_DISABLE_GLM_STREAMING_PREFILL_SELECTED_ASYNC_LOAD` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables GLM streaming prefill selected async load. | [ds4.c:46421](ds4.c#L46421) |
+| `DS4_METAL_DISABLE_GLM_STREAMING_SELECTED_ASYNC_LOAD` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables GLM streaming selected async load. | [ds4.c:44329](ds4.c#L44329) |
+| `DS4_METAL_DISABLE_HC_FUSION` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Disables HC fusion. | [ds4.c:20406](ds4.c#L20406) |
+| `DS4_METAL_DISABLE_HC_NORM_FUSION` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Disables HC norm fusion. | [ds4.c:20450](ds4.c#L20450) |
+| `DS4_METAL_DISABLE_HC_PRODUCER_PRE_NORM_FUSE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables HC producer pre norm fuse. | [ds4_metal.m:46541](ds4_metal.m#L46541) |
+| `DS4_METAL_DISABLE_HC_RMS_SCALE_PROJ` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables HC RMS scale proj. | [ds4_metal.m:24148](ds4_metal.m#L24148) |
+| `DS4_METAL_DISABLE_HOT_PIPELINE_STATICS` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables hot pipeline statics. | [ds4_metal.m:2634](ds4_metal.m#L2634) |
+| `DS4_METAL_DISABLE_INPLACE_ROPE_PAIR` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables inplace RoPE pair. | [ds4_metal.m:25170](ds4_metal.m#L25170) |
+| `DS4_METAL_DISABLE_IQ2_SELECTED_EXPERT_VIEWS` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables IQ2 selected expert views. | [ds4.c:21080](ds4.c#L21080) |
+| `DS4_METAL_DISABLE_IQ2_SELECTED_SHARED_OVERLAP` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables IQ2 selected shared overlap. | [ds4.c:20996](ds4.c#L20996) |
+| `DS4_METAL_DISABLE_IQ2_STREAM_ADDR_TABLE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables IQ2 stream address table. | [ds4_metal.m:42402](ds4_metal.m#L42402) |
+| `DS4_METAL_DISABLE_IQ2_XXS_SSD_PREFILL_MM` | value-aware boolean; default off; true disables and dominates ENABLE; false leaves automatic policy | Rolls grouped IQ2_XXS/Q2_K SSD-prefill MM back to sparse matvec. | [ds4_metal.m:44784](ds4_metal.m#L44784) |
+| `DS4_METAL_DISABLE_KV_FUSION` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Disables KV fusion. | [ds4.c:20430](ds4.c#L20430) |
+| `DS4_METAL_DISABLE_M1_IQ2_MID_ONLY` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables M1 IQ2 mid only. | [ds4_metal.m:14592](ds4_metal.m#L14592) |
+| `DS4_METAL_DISABLE_M3_COMPRESSOR_EXACT_POOL_RATIO4` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables M3 compressor exact pool ratio4. | [ds4_metal.m:26381](ds4_metal.m#L26381) |
+| `DS4_METAL_DISABLE_M3_COMPRESSOR_PAIR_STATE_STORE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables M3 compressor pair state store. | [ds4_metal.m:23247](ds4_metal.m#L23247) |
+| `DS4_METAL_DISABLE_M3_GATHERED_KV_STAGE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables M3 gathered KV stage. | [ds4_metal.m:29678](ds4_metal.m#L29678) |
+| `DS4_METAL_DISABLE_M5_COMPRESSOR_EXACT_POOL_RATIO4` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables M5 compressor exact pool ratio4. | [ds4_metal.m:26384](ds4_metal.m#L26384) |
+| `DS4_METAL_DISABLE_M5_COMP_FINALIZE_FUSE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables M5 comp finalize fuse. | [ds4.c:23647](ds4.c#L23647) |
+| `DS4_METAL_DISABLE_M5_FLASH_ATTN_PACKED32_REDUCE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables M5 flash attn packed32 reduce. | [ds4_metal.m:31519](ds4_metal.m#L31519) |
+| `DS4_METAL_DISABLE_M5_HC_NORM_MIX_CLUSTER2` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables M5 HC norm mix cluster2. | [ds4_metal.m:46496](ds4_metal.m#L46496) |
+| `DS4_METAL_DISABLE_M5_HC_PRODUCER_PRE_NORM_FUSE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables M5 HC producer pre norm fuse. | [ds4_metal.m:46548](ds4_metal.m#L46548) |
+| `DS4_METAL_DISABLE_M5_IQ2_PAIR_PACK2` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables M5 IQ2 pair pack2. | [ds4_metal.m:42020](ds4_metal.m#L42020) |
+| `DS4_METAL_DISABLE_M5_PACKED_ZERO_MASK` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables M5 packed zero mask. | [ds4_metal.m:31475](ds4_metal.m#L31475) |
+| `DS4_METAL_DISABLE_M5_PARALLEL_FULL_FFN` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables M5 parallel full FFN. | [ds4.c:22707](ds4.c#L22707) |
+| `DS4_METAL_DISABLE_M5_PERSISTENT_ZERO_ATTN_MASK` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables M5 persistent zero attn mask. | [ds4_metal.m:31473](ds4_metal.m#L31473) |
+| `DS4_METAL_DISABLE_M5_Q8_HC_VEC` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables M5 Q8 HC vec. | [ds4_metal.m:47580](ds4_metal.m#L47580) |
+| `DS4_METAL_DISABLE_M5_QKV_PAIR_COMPRESSOR_FUSE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables M5 QKV pair compressor fuse. | [ds4.c:23043](ds4.c#L23043) |
+| `DS4_METAL_DISABLE_M5_QKV_PAIR_QUAD_FUSE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables M5 QKV pair quad fuse. | [ds4.c:23039](ds4.c#L23039) |
+| `DS4_METAL_DISABLE_M5_ROUTER_PROJECT_SELECT_FUSE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables M5 router project select fuse. | [ds4.c:24762](ds4.c#L24762) |
+| `DS4_METAL_DISABLE_METAL4` | value-aware boolean; unset: off; empty/1/true/yes/on enables; 0/false/no/off disables | Disables metal4. | [ds4_metal.m:2995](ds4_metal.m#L2995) |
+| `DS4_METAL_DISABLE_MOE_MM_ID_PAIR_SWIGLU` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables MoE MM ID pair SwiGLU. | [ds4_metal.m:44968](ds4_metal.m#L44968) |
+| `DS4_METAL_DISABLE_MOE_MM_ID_USE_RESOURCES` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables MoE MM ID use resources. | [ds4_metal.m:35169](ds4_metal.m#L35169) |
+| `DS4_METAL_DISABLE_MXFP4_SELECTED_EXPERT_VIEWS` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables MXFP4 selected expert views. | [ds4.c:21173](ds4.c#L21173) |
+| `DS4_METAL_DISABLE_PERSISTENT_ZERO_ATTN_MASK` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables persistent zero attn mask. | [ds4_metal.m:31480](ds4_metal.m#L31480) |
+| `DS4_METAL_DISABLE_PRE_M5_ATTN_INV_ROPE_FUSE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 attn inv RoPE fuse. | [ds4.c:22638](ds4.c#L22638) |
+| `DS4_METAL_DISABLE_PRE_M5_ATTN_OUT_LOW_Q8_STATIC` | presence rollback; unset: exact fixed-shape kernel is automatic on eligible pre-M5 Flash decode; any value including 0 disables | Restores the generic Q8 attention-output low projection kernel. | [ds4_metal.m:27987](ds4_metal.m#L27987) |
+| `DS4_METAL_DISABLE_PRE_M5_BATCH_INDEXER_QUERY_PRUNE` | presence rollback; unset: unused zero-prefix indexer queries are pruned before compressed rows exceed top-k; any value including 0 disables | Restores transient indexer query and weight dispatches during eligible pre-M5 prefill. | [ds4.c:30086](ds4.c#L30086) |
+| `DS4_METAL_DISABLE_PRE_M5_COMPRESSOR_EXACT_POOL_RATIO4` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 compressor exact pool ratio4. | [ds4_metal.m:26383](ds4_metal.m#L26383) |
+| `DS4_METAL_DISABLE_PRE_M5_COMPRESSOR_EXACT_REDUCTION_FUSION` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 compressor exact reduction fusion. | [ds4_metal.m:25907](ds4_metal.m#L25907) |
+| `DS4_METAL_DISABLE_PRE_M5_COMPRESSOR_QUAD_STORE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 compressor quad store. | [ds4.c:23535](ds4.c#L23535) |
+| `DS4_METAL_DISABLE_PRE_M5_COMPRESSOR_RATIO4_DECODE_PACK_FUSION` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 compressor ratio4 decode pack fusion. | [ds4_metal.m:26214](ds4_metal.m#L26214) |
+| `DS4_METAL_DISABLE_PRE_M5_COMP_FINALIZE_FUSE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 comp finalize fuse. | [ds4.c:23646](ds4.c#L23646) |
+| `DS4_METAL_DISABLE_PRE_M5_DECODE_EARLY_PIPELINE_FAST_LOOKUP` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 decode early pipeline fast lookup. | [ds4.c:28003](ds4.c#L28003) |
+| `DS4_METAL_DISABLE_PRE_M5_DECODE_EARLY_SECOND_SPLIT12` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 decode early second split12. | [ds4.c:28087](ds4.c#L28087) |
+| `DS4_METAL_DISABLE_PRE_M5_DECODE_EARLY_SPLIT3` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 decode early split3. | [ds4.c:27961](ds4.c#L27961) |
+| `DS4_METAL_DISABLE_PRE_M5_DECODE_EARLY_SPLIT5` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 decode early split5. | [ds4.c:27973](ds4.c#L27973) |
+| `DS4_METAL_DISABLE_PRE_M5_DECODE_PIPELINE_FAST_LOOKUP` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 decode pipeline fast lookup. | [ds4.c:28015](ds4.c#L28015) |
+| `DS4_METAL_DISABLE_PRE_M5_DECODE_PORTS` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 decode ports. | [ds4.c:22613](ds4.c#L22613) |
+| `DS4_METAL_DISABLE_PRE_M5_DECODE_RAW_ZERO_ATTN_MASK` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 decode raw zero attn mask. | [ds4_metal.m:29920](ds4_metal.m#L29920) |
+| `DS4_METAL_DISABLE_PRE_M5_DECODE_SECOND_SPLIT16` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 decode second split16. | [ds4.c:28095](ds4.c#L28095) |
+| `DS4_METAL_DISABLE_PRE_M5_FLASH_ATTN_BATCHED_MEMO` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 flash attn batched memo. | [ds4_metal.m:3752](ds4_metal.m#L3752) |
+| `DS4_METAL_DISABLE_PRE_M5_FLASH_ATTN_PACKED32_REDUCE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 flash attn packed32 reduce. | [ds4_metal.m:31460](ds4_metal.m#L31460) |
+| `DS4_METAL_DISABLE_PRE_M5_FLASH_ATTN_PAD_BLK_MEMO` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 flash attn pad blk memo. | [ds4_metal.m:3610](ds4_metal.m#L3610) |
+| `DS4_METAL_DISABLE_PRE_M5_HC_NORM_MIX_FUSE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 HC norm mix fuse. | [ds4.c:22867](ds4.c#L22867) |
+| `DS4_METAL_DISABLE_PRE_M5_HC_PRODUCER_PRE_NORM_FUSE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 HC producer pre norm fuse. | [ds4_metal.m:46546](ds4_metal.m#L46546) |
+| `DS4_METAL_DISABLE_PRE_M5_HEAD_RMS_ROPE_PIPELINE_STATIC` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 head RMS RoPE pipeline static. | [ds4_metal.m:10026](ds4_metal.m#L10026) |
+| `DS4_METAL_DISABLE_PRE_M5_KV_ROPE_FP8_FUSE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 KV RoPE fp8 fuse. | [ds4.c:23455](ds4.c#L23455) |
+| `DS4_METAL_DISABLE_PRE_M5_MXFP4_MM_ID_PAIR_HALF_SCALE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 MXFP4 MM ID pair half scale. | [ds4_metal.m:45129](ds4_metal.m#L45129) |
+| `DS4_METAL_DISABLE_PRE_M5_MXFP4_MOE_DECODE_FIXED_ROUTE_PAIR` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 MXFP4 MoE decode fixed route pair. | [ds4_metal.m:41948](ds4_metal.m#L41948) |
+| `DS4_METAL_DISABLE_PRE_M5_MXFP4_MOE_DECODE_FIXED_ROUTE_SUM6` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 MXFP4 MoE decode fixed route sum6. | [ds4_metal.m:41961](ds4_metal.m#L41961) |
+| `DS4_METAL_DISABLE_PRE_M5_MXFP4_MOE_DECODE_NSG1` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 MXFP4 MoE decode nsg1. | [ds4_metal.m:41719](ds4_metal.m#L41719) |
+| `DS4_METAL_DISABLE_PRE_M5_MXFP4_MOE_DECODE_STATIC_TRIP` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 MXFP4 MoE decode static trip. | [ds4_metal.m:41987](ds4_metal.m#L41987) |
+| `DS4_METAL_DISABLE_PRE_M5_MXFP4_MOE_DECODE_SUM6_FULL_ROWS` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 MXFP4 MoE decode sum6 full rows. | [ds4_metal.m:41974](ds4_metal.m#L41974) |
+| `DS4_METAL_DISABLE_PRE_M5_MXFP4_MOE_DECODE_TG_MULTIPLE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 MXFP4 MoE decode tg multiple. | [ds4_metal.m:41936](ds4_metal.m#L41936) |
+| `DS4_METAL_DISABLE_PRE_M5_MXFP4_MOE_MM_ID_DOWN_HALF_LUT` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 MXFP4 MoE MM ID down half lut. | [ds4_metal.m:45047](ds4_metal.m#L45047) |
+| `DS4_METAL_DISABLE_PRE_M5_MXFP4_MOE_MM_ID_DOWN_TAIL_SIMDGROUP_CULL` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 MXFP4 MoE MM ID down tail simdgroup cull. | [ds4_metal.m:45030](ds4_metal.m#L45030) |
+| `DS4_METAL_DISABLE_PRE_M5_MXFP4_MOE_MM_ID_MAP_SCATTER` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 MXFP4 MoE MM ID map scatter. | [ds4_metal.m:44997](ds4_metal.m#L44997) |
+| `DS4_METAL_DISABLE_PRE_M5_MXFP4_MOE_MM_ID_PAIR_SWIGLU_COMPACT_TILE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 MXFP4 MoE MM ID pair SwiGLU compact tile. | [ds4_metal.m:44981](ds4_metal.m#L44981) |
+| `DS4_METAL_DISABLE_PRE_M5_MXFP4_MOE_MM_ID_PAIR_TAIL_SIMDGROUP_CULL` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 MXFP4 MoE MM ID pair tail simdgroup cull. | [ds4_metal.m:45018](ds4_metal.m#L45018) |
+| `DS4_METAL_DISABLE_PRE_M5_PARALLEL_FULL_FFN` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 parallel full FFN. | [ds4.c:22706](ds4.c#L22706) |
+| `DS4_METAL_DISABLE_PRE_M5_Q2_DECODE_SPLIT2_32` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 q2 decode split2 32. | [ds4.c:27876](ds4.c#L27876) |
+| `DS4_METAL_DISABLE_PRE_M5_QKV_NORM_KV_STORE_FUSE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 QKV norm KV store fuse. | [ds4.c:23314](ds4.c#L23314) |
+| `DS4_METAL_DISABLE_PRE_M5_QKV_PAIR_COMPRESSOR_FUSE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 QKV pair compressor fuse. | [ds4.c:23042](ds4.c#L23042) |
+| `DS4_METAL_DISABLE_PRE_M5_QKV_PAIR_QUAD_FUSE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 QKV pair quad fuse. | [ds4.c:23038](ds4.c#L23038) |
+| `DS4_METAL_DISABLE_PRE_M5_ROUTER_SHARED_FUSE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 router shared fuse. | [ds4.c:24755](ds4.c#L24755) |
+| `DS4_METAL_DISABLE_PRE_M5_ROUTER_SIMD_FINALIZE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 router simd finalize. | [ds4_metal.m:35827](ds4_metal.m#L35827) |
+| `DS4_METAL_DISABLE_PRE_M5_ROUTER_SIMD_WEIGHTS_FUSION` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 router simd weights fusion. | [ds4_metal.m:35836](ds4_metal.m#L35836) |
+| `DS4_METAL_DISABLE_PRE_M5_ROUTER_TRANSFORM_FINALIZE_FUSION` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pre M5 router transform finalize fusion. | [ds4_metal.m:35840](ds4_metal.m#L35840) |
+| `DS4_METAL_DISABLE_PRO_Q4_EXPERT_ADDRESS_AUTO` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pro Q4 expert address auto. | [ds4_metal.m:19710](ds4_metal.m#L19710) |
+| `DS4_METAL_DISABLE_PRO_Q4_EXPERT_TABLE_AUTO` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pro Q4 expert table auto. | [ds4.c:21568](ds4.c#L21568) |
+| `DS4_METAL_DISABLE_PRO_Q4_EXPERT_TABLE_PRELOAD` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables pro Q4 expert table preload. | [ds4.c:63088](ds4.c#L63088) |
+| `DS4_METAL_DISABLE_Q4_ATTN_OUT_A_DIRECT` | presence rollback; unset enables the automatic fixed-route path for eligible Apple M1-M4 long prefills; any defined value including 0 disables | Restore the generic route-map/work-list Q4 attention output-A path instead of the bit-identical fixed-route direct kernel. | [ds4_metal.m:31562](ds4_metal.m#L31562) |
+| `DS4_METAL_DISABLE_Q4_ATTN_OUT_HC_FUSE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables Q4 attn out HC fuse. | [ds4_metal.m:47624](ds4_metal.m#L47624) |
+| `DS4_METAL_DISABLE_Q4_ATTN_OUT_TINY_BATCH` | value-aware boolean; unset: off; empty/1/true/yes/on enables; 0/false/no/off disables | Disables Q4 attn out tiny batch. | [ds4_metal.m:28396](ds4_metal.m#L28396) |
+| `DS4_METAL_DISABLE_Q4_BATCH_EXPERT_TABLE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables Q4 batch expert table. | [ds4_metal.m:44883](ds4_metal.m#L44883) |
+| `DS4_METAL_DISABLE_Q4_DENSE_PAIR` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables Q4 dense pair. | [ds4_metal.m:21990](ds4_metal.m#L21990) |
+| `DS4_METAL_DISABLE_Q4_EXACT_BOUNDARY` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables Q4 exact boundary. | [ds4_metal.m:42239](ds4_metal.m#L42239) |
+| `DS4_METAL_DISABLE_Q4_EXACT_TENSOR_ID` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables Q4 exact tensor ID. | [ds4_metal.m:42219](ds4_metal.m#L42219) |
+| `DS4_METAL_DISABLE_Q4_EXPERT_ADDRESS_TABLE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables Q4 expert address table. | [ds4_metal.m:19711](ds4_metal.m#L19711) |
+| `DS4_METAL_DISABLE_Q4_EXPERT_TABLE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables Q4 expert table. | [ds4.c:21041](ds4.c#L21041) |
+| `DS4_METAL_DISABLE_Q4_GATHER_SLOTS` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables Q4 gather slots. | [ds4_metal.m:42321](ds4_metal.m#L42321) |
+| `DS4_METAL_DISABLE_Q4_GROUP24_EXPERT_TABLE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables Q4 group24 expert table. | [ds4_metal.m:42201](ds4_metal.m#L42201) |
+| `DS4_METAL_DISABLE_Q4_GROUP6_EXPERT_TABLE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables Q4 group6 expert table. | [ds4_metal.m:42167](ds4_metal.m#L42167) |
+| `DS4_METAL_DISABLE_Q4_GROUP8_EXPERT_TABLE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables Q4 group8 expert table. | [ds4_metal.m:42184](ds4_metal.m#L42184) |
+| `DS4_METAL_DISABLE_Q4_GROUPED_BOUNDARY` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables Q4 grouped boundary. | [ds4_metal.m:42149](ds4_metal.m#L42149) |
+| `DS4_METAL_DISABLE_Q4_GROUPED_EXPERTS` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables Q4 grouped experts. | [ds4_metal.m:42130](ds4_metal.m#L42130) |
+| `DS4_METAL_DISABLE_Q4_MV_CLASSIC` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables Q4 MV classic. | [ds4_metal.m:21571](ds4_metal.m#L21571) |
+| `DS4_METAL_DISABLE_Q4_PREFILL_TAIL_SIMDGROUP_CULL` | presence rollback; unset: automatic on Apple M1-M4 for Q4_K single-tile prefill N=9..16 and production attn_q_b tails through N=65; any value including 0 disables | Restores the legacy four-SIMDgroup Q4_K prefill kernel on the measured short-prefill scopes. | [ds4_metal.m:22088](ds4_metal.m#L22088) |
+| `DS4_METAL_DISABLE_Q4_QKV_COMPRESSOR_FUSE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables Q4 QKV compressor fuse. | [ds4_metal.m:22083](ds4_metal.m#L22083) |
+| `DS4_METAL_DISABLE_Q4_SELECTED_EXPERT_VIEWS` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables Q4 selected expert views. | [ds4.c:21136](ds4.c#L21136) |
+| `DS4_METAL_DISABLE_Q4_SSD_PREFILL_ATTN_OUT_EXACTN` | value-aware boolean; unset: off; empty/1/true/yes/on enables; 0/false/no/off disables | Disables Q4 SSD prefill attn out exactn. | [ds4_metal.m:28095](ds4_metal.m#L28095) |
+| `DS4_METAL_DISABLE_Q4_SSD_PREFILL_ATTN_OUT_SCALE_META` | value-aware boolean; unset: off; empty/1/true/yes/on enables; 0/false/no/off disables | Disables shared scale/min metadata in the Q4 SSD prefill attention-output exact-N kernel. | [ds4_metal.m:28220](ds4_metal.m#L28220) |
+| `DS4_METAL_DISABLE_Q4_SSD_SESSION_UNION` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Disables Q4 SSD session union. | [ds4.c:65160](ds4.c#L65160) |
+| `DS4_METAL_DISABLE_Q4_STREAM_OVERLAP` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Disables Q4 stream overlap. | [ds4.c:65082](ds4.c#L65082) |
+| `DS4_METAL_DISABLE_Q4_TABLE_BOUNDARY` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables Q4 table boundary. | [ds4_metal.m:42318](ds4_metal.m#L42318) |
+| `DS4_METAL_DISABLE_Q8_DECODE_EXACT_VIEWS` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables Q8 decode exact views. | [ds4_metal.m:12851](ds4_metal.m#L12851) |
+| `DS4_METAL_DISABLE_QKV_NORM_FUSION` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Disables QKV norm fusion. | [ds4.c:20435](ds4.c#L20435) |
+| `DS4_METAL_DISABLE_QKV_PAIR_PROJ` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Disables QKV pair proj. | [ds4.c:20440](ds4.c#L20440) |
+| `DS4_METAL_DISABLE_QUEUE_RESIDENCY_SET` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables queue residency set. | [ds4_metal.m:2124](ds4_metal.m#L2124) |
+| `DS4_METAL_DISABLE_ROUTED_PAIR_SWIGLU_FUSION` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables routed pair SwiGLU fusion. | [ds4.c:18529](ds4.c#L18529) |
+| `DS4_METAL_DISABLE_ROUTER_SELECT_FUSION` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables router select fusion. | [ds4_metal.m:35816](ds4_metal.m#L35816) |
+| `DS4_METAL_DISABLE_ROUTER_WEIGHTS_BATCH_FUSION` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables router weights batch fusion. | [ds4_metal.m:36068](ds4_metal.m#L36068) |
+| `DS4_METAL_DISABLE_SHARED_DOWN_HC_FUSION` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Disables shared down HC fusion. | [ds4.c:20472](ds4.c#L20472) |
+| `DS4_METAL_DISABLE_SHARED_GATE_UP_SWIGLU_FUSION` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables shared gate up SwiGLU fusion. | [ds4.c:17567](ds4.c#L17567) |
+| `DS4_METAL_DISABLE_SHARED_KV_PAD` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables shared KV pad. | [ds4_metal.m:31510](ds4_metal.m#L31510) |
+| `DS4_METAL_DISABLE_SHARED_ROPE_COEFF` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables shared RoPE coeff. | [ds4_metal.m:6341](ds4_metal.m#L6341) |
+| `DS4_METAL_DISABLE_STREAMING_COLD_DECODE_PREFILL` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming cold decode prefill. | [ds4.c:32007](ds4.c#L32007) |
+| `DS4_METAL_DISABLE_STREAMING_COMPACT_ADDR` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming compact address. | [ds4_metal.m:14598](ds4_metal.m#L14598) |
+| `DS4_METAL_DISABLE_STREAMING_DECODE_PREFILL` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming decode prefill. | [ds4.c:31956](ds4.c#L31956) |
+| `DS4_METAL_DISABLE_STREAMING_EXPERT_ADDR_TABLE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming expert address table. | [ds4.c:18525](ds4.c#L18525) |
+| `DS4_METAL_DISABLE_STREAMING_EXPERT_COMBINED_BUFFER` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming expert combined buffer. | [ds4_metal.m:14023](ds4_metal.m#L14023) |
+| `DS4_METAL_DISABLE_STREAMING_EXPERT_EARLY_LOAD` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming expert early load. | [ds4_metal.m:17232](ds4_metal.m#L17232) |
+| `DS4_METAL_DISABLE_STREAMING_EXPERT_EVICT_DONTNEED` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming expert evict dontneed. | [ds4_metal.m:14395](ds4_metal.m#L14395) |
+| `DS4_METAL_DISABLE_STREAMING_EXPERT_HIT_VALIDATOR` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming expert hit validator. | [ds4_metal.m:14634](ds4_metal.m#L14634) |
+| `DS4_METAL_DISABLE_STREAMING_EXPERT_HOTLIST` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming expert hotlist. | [ds4.c:21290](ds4.c#L21290) |
+| `DS4_METAL_DISABLE_STREAMING_EXPERT_LIVE_INDEX` | value-aware boolean; default off; true disables and dominates ENABLE | Disables dense live-entry index and uses authoritative cache matrix. | [ds4_metal.m:15443](ds4_metal.m#L15443) |
+| `DS4_METAL_DISABLE_STREAMING_EXPERT_MASKED_ADDR` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming expert masked address. | [ds4_metal.m:14628](ds4_metal.m#L14628) |
+| `DS4_METAL_DISABLE_STREAMING_EXPERT_READAHEAD` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming expert readahead. | [ds4_metal.m:13196](ds4_metal.m#L13196) |
+| `DS4_METAL_DISABLE_STREAMING_EXPERT_SLABS` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming expert slabs. | [ds4_metal.m:14028](ds4_metal.m#L14028) |
+| `DS4_METAL_DISABLE_STREAMING_EXPERT_TIMING_SUMMARY` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming expert timing summary. | [ds4_metal.m:13062](ds4_metal.m#L13062) |
+| `DS4_METAL_DISABLE_STREAMING_FULL_EXPERT_ADDR_TABLE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming full expert address table. | [ds4_metal.m:14716](ds4_metal.m#L14716) |
+| `DS4_METAL_DISABLE_STREAMING_IQ2_CPU_ROUTER` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming IQ2 CPU router. | [ds4.c:20939](ds4.c#L20939) |
+| `DS4_METAL_DISABLE_STREAMING_LAYER_BATCH` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming layer batch. | [ds4.c:18239](ds4.c#L18239) |
+| `DS4_METAL_DISABLE_STREAMING_MADVISE_WILLNEED` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming madvise willneed. | [ds4.c:18212](ds4.c#L18212) |
+| `DS4_METAL_DISABLE_STREAMING_PREFILL_BATCH_SELECTED_ADDR` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming prefill batch selected address. | [ds4.c:18523](ds4.c#L18523) |
+| `DS4_METAL_DISABLE_STREAMING_PREFILL_LAYER_MADVISE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming prefill layer madvise. | [ds4.c:18466](ds4.c#L18466) |
+| `DS4_METAL_DISABLE_STREAMING_PREFILL_LAYER_PAGEIN` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming prefill layer pagein. | [ds4.c:18434](ds4.c#L18434) |
+| `DS4_METAL_DISABLE_STREAMING_PREFILL_LAYER_PAGEIN_OVERLAP` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming prefill layer pagein overlap. | [ds4.c:19321](ds4.c#L19321) |
+| `DS4_METAL_DISABLE_STREAMING_PREFILL_LAYER_PREAD` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming prefill layer pread. | [ds4.c:18454](ds4.c#L18454) |
+| `DS4_METAL_DISABLE_STREAMING_PREFILL_LAYER_PREPARE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming prefill layer prepare. | [ds4.c:18446](ds4.c#L18446) |
+| `DS4_METAL_DISABLE_STREAMING_PREFILL_LAYER_PREPARE_OVERLAP` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming prefill layer prepare overlap. | [ds4.c:19319](ds4.c#L19319) |
+| `DS4_METAL_DISABLE_STREAMING_PREFILL_LAYER_READAHEAD` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming prefill layer readahead. | [ds4.c:18444](ds4.c#L18444) |
+| `DS4_METAL_DISABLE_STREAMING_PREFILL_SELECTED_ASYNC_LOAD` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming prefill selected async load. | [ds4.c:46424](ds4.c#L46424) |
+| `DS4_METAL_DISABLE_STREAMING_PREFILL_SELECTED_MADVISE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming prefill selected madvise. | [ds4.c:18424](ds4.c#L18424) |
+| `DS4_METAL_DISABLE_STREAMING_PREFILL_SELECTED_PAGEIN` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming prefill selected pagein. | [ds4.c:18414](ds4.c#L18414) |
+| `DS4_METAL_DISABLE_STREAMING_PREFILL_SELECTED_PROFILE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming prefill selected profile. | [ds4.c:18908](ds4.c#L18908) |
+| `DS4_METAL_DISABLE_STREAMING_PREFILL_SELECTED_READAHEAD` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming prefill selected readahead. | [ds4.c:19960](ds4.c#L19960) |
+| `DS4_METAL_DISABLE_STREAMING_PREFILL_SELECTED_READAHEAD_SHARED` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming prefill selected readahead shared. | [ds4.c:19970](ds4.c#L19970) |
+| `DS4_METAL_DISABLE_STREAMING_READAHEAD` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming readahead. | [ds4.c:18205](ds4.c#L18205) |
+| `DS4_METAL_DISABLE_STREAMING_SELECTED_ASYNC_EARLY_COMMIT` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming selected async early commit. | [ds4.c:21019](ds4.c#L21019) |
+| `DS4_METAL_DISABLE_STREAMING_SELECTED_ASYNC_LOAD` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming selected async load. | [ds4.c:21003](ds4.c#L21003) |
+| `DS4_METAL_DISABLE_STREAMING_SELECTED_READAHEAD_SHARED_DELAY` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming selected readahead shared delay. | [ds4.c:21720](ds4.c#L21720) |
+| `DS4_METAL_DISABLE_STREAMING_SELECTED_SHARED_OVERLAP` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming selected shared overlap. | [ds4.c:20995](ds4.c#L20995) |
+| `DS4_METAL_DISABLE_STREAMING_STATIC_DECODE_MAP` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming static decode map. | [ds4.c:18217](ds4.c#L18217) |
+| `DS4_METAL_DISABLE_STREAMING_STATIC_MAP_STATE_CACHE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming static map state cache. | [ds4.c:18230](ds4.c#L18230) |
+| `DS4_METAL_DISABLE_SUPPORT_Q8_DECODE_EXACT_VIEWS` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables support Q8 decode exact views. | [ds4_metal.m:12858](ds4_metal.m#L12858) |
+| `DS4_METAL_DISABLE_TINY_PAIR_SWIGLU_FUSION` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables tiny pair SwiGLU fusion. | [ds4_metal.m:44920](ds4_metal.m#L44920) |
+| `DS4_METAL_DISABLE_TOKEN_EMBED_EXACT_VIEW` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables token embed exact view. | [ds4_metal.m:11907](ds4_metal.m#L11907) |
+| `DS4_METAL_DISABLE_ZERO_PREFIX_PREFILL_MASK_CACHE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables zero prefix prefill mask cache. | [ds4_metal.m:2404](ds4_metal.m#L2404) |
+| `DS4_METAL_DSPARK_ACCEPTANCE_ONLY_VERIFY` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Verifies only the draft rows still needed for acceptance after the base target logit. | [ds4.c:52499](ds4.c#L52499) |
+| `DS4_METAL_DSPARK_DEVICE_PROPOSER` | boolean true values enable; false values/unset disable; NO_DEVICE_PROPOSER presence dominates | Keeps DSpark Q8 confidence/Markov proposal work on Metal and reads one compact result. | [ds4.c:34884](ds4.c#L34884) |
+| `DS4_METAL_DSPARK_EXACT2` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Enables the resident single-GPU Metal exact-2 verifier. | [ds4.c:52290](ds4.c#L52290) |
+| `DS4_METAL_DSPARK_EXACTN` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Enables the single-GPU Metal exact-N verifier. | [ds4.c:52311](ds4.c#L52311) |
+| `DS4_METAL_DSPARK_EXACTN_BATCH_HEAD` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Batches the output head across exact-N verifier rows. | [ds4.c:37726](ds4.c#L37726) |
+| `DS4_METAL_DSPARK_EXACTN_UNION` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Loads the union of experts for exact-N verifier rows once. | [ds4.c:52332](ds4.c#L52332) |
+| `DS4_METAL_DSPARK_EXACT_ROWS_ASYNC_TAILS` | presence control; unset: off/default; any value including 0 enables | Runs exact-row routed tails asynchronously after union routing. | [ds4.c:37932](ds4.c#L37932) |
+| `DS4_METAL_DSPARK_EXACT_ROWS_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for DSpark exact rows. | [ds4.c:37930](ds4.c#L37930) |
+| `DS4_METAL_DSPARK_HEADLESS_REPLAY` | unset/empty: enabled; exact 0 disables; every other nonempty value enables | Skips output heads for accepted intermediate DSpark replay tokens. | [ds4.c:52479](ds4.c#L52479) |
+| `DS4_METAL_DSPARK_NO_DEVICE_PROPOSER` | presence rollback; unset: automatic/default path; any value including 0 disables | Dominant presence-based rollback for the Metal DSpark device proposer. | [ds4.c:34886](ds4.c#L34886) |
+| `DS4_METAL_DSPARK_PIN_MAIN_PROJ` | nonempty value other than exact 0 enables; unset/empty/0 disables | mlock-pins only DSpark stage-0 main_norm/main_proj in Metal SSD streaming. | [ds4.c:39443](ds4.c#L39443) |
+| `DS4_METAL_DSPARK_PROPOSER_BLOCK_MAX` | uint32; unset: automatic cache/verifier cap; 0 or invalid: native width; positive: clamped to DSpark/native maximum | Caps rows proposed by single-device Metal DSpark. | [ds4.c:52430](ds4.c#L52430) |
+| `DS4_METAL_DSPARK_SAFE_EXPERT_COUNT` | exact 1 enables; unset or any other value disables | Caps an explicit expert-count cache request to the safe Metal working-set budget for DSpark SSD streaming. | [ds4.c:4880](ds4.c#L4880) |
+| `DS4_METAL_DSV4_HC_SOURCE` | file path; unset/empty: use the in-tree Metal source file | Overrides the DeepSeek hidden-context Metal kernel source file loaded at runtime. | [ds4_metal.m:4938](ds4_metal.m#L4938) |
+| `DS4_METAL_DSV4_KV_SOURCE` | file path; unset/empty: use the in-tree Metal source file | Overrides the DeepSeek KV Metal kernel source file loaded at runtime. | [ds4_metal.m:4940](ds4_metal.m#L4940) |
+| `DS4_METAL_DSV4_MISC_SOURCE` | file path; unset/empty: use the in-tree Metal source file | Overrides the DeepSeek miscellaneous Metal kernel source file loaded at runtime. | [ds4_metal.m:4942](ds4_metal.m#L4942) |
+| `DS4_METAL_DSV4_ROPE_SOURCE` | file path; unset/empty: use the in-tree Metal source file | Overrides the DeepSeek RoPE Metal kernel source file loaded at runtime. | [ds4_metal.m:4941](ds4_metal.m#L4941) |
+| `DS4_METAL_DUMP_PREFILL_LOGITS` | file path; unset/empty: no dump | Writes final GPU prefill logits as f32 binary. | [ds4.c:51347](ds4.c#L51347) |
+| `DS4_METAL_ENABLE_BATCH_HC_NORM_FUSION` | legacy value-aware alias; default enabled; exact 0 disables; unset/empty/every other value enables unless DISABLE is active | Legacy control for the now-default batched HC norm fusion. | [ds4.c:20462](ds4.c#L20462) |
+| `DS4_METAL_ENABLE_COMPRESSOR_EXACT_POOL_RATIO4` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables compressor exact pool ratio4. | [ds4_metal.m:26385](ds4_metal.m#L26385) |
+| `DS4_METAL_ENABLE_COMPRESSOR_PAIR_STATE_STORE` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables compressor pair state store. | [ds4_metal.m:23243](ds4_metal.m#L23243) |
+| `DS4_METAL_ENABLE_COMPRESSOR_QUAD_STORE` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables compressor quad store. | [ds4.c:23527](ds4.c#L23527) |
+| `DS4_METAL_ENABLE_DSPARK_CAPTURE_FUSED_LAST` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Enables DSpark capture fused last. | [ds4.c:28359](ds4.c#L28359) |
+| `DS4_METAL_ENABLE_GATHERED_KV_STAGE` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables gathered KV stage. | [ds4_metal.m:29675](ds4_metal.m#L29675) |
+| `DS4_METAL_ENABLE_GLM_STREAMING_SELECTED_ASYNC_LOAD` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables GLM streaming selected async load. | [ds4.c:44335](ds4.c#L44335) |
+| `DS4_METAL_ENABLE_HC_NORM_MIX_FUSE` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables HC norm mix fuse. | [ds4.c:22870](ds4.c#L22870) |
+| `DS4_METAL_ENABLE_HC_PRODUCER_PRE_NORM_FUSE` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables HC producer pre norm fuse. | [ds4_metal.m:46552](ds4_metal.m#L46552) |
+| `DS4_METAL_ENABLE_IQ2_SELECTED_ASYNC_EARLY_COMMIT` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables IQ2 selected async early commit. | [ds4.c:21018](ds4.c#L21018) |
+| `DS4_METAL_ENABLE_IQ2_XXS_SSD_PREFILL_MM` | value-aware boolean; default automatic/on for eligible shape; explicit 0 turns request off unless REQUIRE=1 | Overrides automatic IQ2_XXS/Q2_K grouped address-MM selection for SSD prefill. | [ds4_metal.m:44780](ds4_metal.m#L44780) |
+| `DS4_METAL_ENABLE_PRO_Q4_EXPERT_ADDRESS_AUTO` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables pro Q4 expert address auto. | [ds4.c:20982](ds4.c#L20982) |
+| `DS4_METAL_ENABLE_PRO_Q4_EXPERT_TABLE_AUTO` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables pro Q4 expert table auto. | [ds4.c:20981](ds4.c#L20981) |
+| `DS4_METAL_ENABLE_PRO_Q4_SELECTED_EXPERT_VIEWS` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables pro Q4 selected expert views. | [ds4.c:20978](ds4.c#L20978) |
+| `DS4_METAL_ENABLE_Q4_ATTN_OUT_TINY_BATCH` | value-aware boolean; unset: off; empty/1/true/yes/on enables; 0/false/no/off disables | Enables Q4 attn out tiny batch. | [ds4_metal.m:28405](ds4_metal.m#L28405) |
+| `DS4_METAL_ENABLE_Q4_BATCH_EXPERT_TABLE` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables Q4 batch expert table. | [ds4_metal.m:44869](ds4_metal.m#L44869) |
+| `DS4_METAL_ENABLE_Q4_EXACT_TENSOR_ID` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables Q4 exact tensor ID. | [ds4_metal.m:42218](ds4_metal.m#L42218) |
+| `DS4_METAL_ENABLE_Q4_EXPERT_ADDRESS_TABLE` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables Q4 expert address table. | [ds4.c:20980](ds4.c#L20980) |
+| `DS4_METAL_ENABLE_Q4_EXPERT_TABLE` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables Q4 expert table. | [ds4.c:20979](ds4.c#L20979) |
+| `DS4_METAL_ENABLE_Q4_GATHER_SLOTS` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables Q4 gather slots. | [ds4_metal.m:42320](ds4_metal.m#L42320) |
+| `DS4_METAL_ENABLE_Q4_GROUP24_EXPERT_TABLE` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables Q4 group24 expert table. | [ds4_metal.m:42200](ds4_metal.m#L42200) |
+| `DS4_METAL_ENABLE_Q4_GROUP6_EXPERT_TABLE` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables Q4 group6 expert table. | [ds4_metal.m:42166](ds4_metal.m#L42166) |
+| `DS4_METAL_ENABLE_Q4_GROUP8_EXPERT_TABLE` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables Q4 group8 expert table. | [ds4_metal.m:42183](ds4_metal.m#L42183) |
+| `DS4_METAL_ENABLE_Q4_GROUPED_EXPERTS` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables Q4 grouped experts. | [ds4_metal.m:42129](ds4_metal.m#L42129) |
+| `DS4_METAL_ENABLE_Q4_QKV_COMPRESSOR_FUSE` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables Q4 QKV compressor fuse. | [ds4.c:23140](ds4.c#L23140) |
+| `DS4_METAL_ENABLE_Q4_SELECTED_EXPERT_VIEWS` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables Q4 selected expert views. | [ds4.c:20977](ds4.c#L20977) |
+| `DS4_METAL_ENABLE_Q4_SSD_PREFILL_ATTN_OUT_EXACTN` | value-aware boolean; unset: off; empty/1/true/yes/on enables; 0/false/no/off disables | Enables Q4 SSD prefill attn out exactn. | [ds4_metal.m:28097](ds4_metal.m#L28097) |
+| `DS4_METAL_ENABLE_Q4_SSD_SESSION_UNION` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Enables Q4 SSD session union. | [ds4.c:65171](ds4.c#L65171) |
+| `DS4_METAL_ENABLE_Q4_STREAM_OVERLAP` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Enables Q4 stream overlap. | [ds4.c:65080](ds4.c#L65080) |
+| `DS4_METAL_ENABLE_Q8_DECODE_EXACT_VIEWS` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables Q8 decode exact views. | [ds4_metal.m:12865](ds4_metal.m#L12865) |
+| `DS4_METAL_ENABLE_Q8_QKV_COMPRESSOR_FUSE` | nonempty boolean; unset/empty/exact 0: no streamed/union opt-in; other values enable; eligible resident full-decode remains automatic | Extends the automatic resident Q8 QKV/compressor compound fusion to SSD streaming or exact-N union scope. | [ds4.c:23027](ds4.c#L23027) |
+| `DS4_METAL_ENABLE_STREAMING_COMPACT_ADDR` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables streaming compact address. | [ds4_metal.m:14597](ds4_metal.m#L14597) |
+| `DS4_METAL_ENABLE_STREAMING_EXPERT_ADDR_TABLE` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables streaming expert address table. | [ds4_metal.m:14604](ds4_metal.m#L14604) |
+| `DS4_METAL_ENABLE_STREAMING_EXPERT_EVICT_DONTNEED` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables streaming expert evict dontneed. | [ds4_metal.m:14394](ds4_metal.m#L14394) |
+| `DS4_METAL_ENABLE_STREAMING_EXPERT_HIT_VALIDATOR` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables streaming expert hit validator. | [ds4_metal.m:14605](ds4_metal.m#L14605) |
+| `DS4_METAL_ENABLE_STREAMING_EXPERT_LIVE_INDEX` | value-aware boolean; default automatic/on for validated IQ2 cache shape; explicit 0 disables | Overrides automatic dense live-entry index selection. | [ds4_metal.m:15442](ds4_metal.m#L15442) |
+| `DS4_METAL_ENABLE_STREAMING_EXPERT_MASKED_ADDR` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables streaming expert masked address. | [ds4_metal.m:14606](ds4_metal.m#L14606) |
+| `DS4_METAL_ENABLE_STREAMING_FULL_EXPERT_ADDR_TABLE` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables streaming full expert address table. | [ds4_metal.m:14715](ds4_metal.m#L14715) |
+| `DS4_METAL_ENABLE_STREAMING_IQ2_CPU_ROUTER` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables streaming IQ2 CPU router. | [ds4.c:20938](ds4.c#L20938) |
+| `DS4_METAL_ENABLE_STREAMING_MADVISE_WILLNEED` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables streaming madvise willneed. | [ds4.c:18210](ds4.c#L18210) |
+| `DS4_METAL_ENABLE_STREAMING_PREFILL_BATCH_SELECTED_ADDR` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables streaming prefill batch selected address. | [ds4_metal.m:14609](ds4_metal.m#L14609) |
+| `DS4_METAL_ENABLE_STREAMING_PREFILL_CACHE_SEED` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables streaming prefill cache seed. | [ds4.c:21259](ds4.c#L21259) |
+| `DS4_METAL_ENABLE_STREAMING_PREFILL_EXPERT_READAHEAD` | value-aware boolean; for batches <32 readahead is automatic; for batches >=32 unset/false disables and true enables; global READHEAD rollback and F_NOCACHE still dominate | Restores F_RDADVISE immediately before parallel pread for large SSD-prefill batches. | [ds4_metal.m:13212](ds4_metal.m#L13212) |
+| `DS4_METAL_ENABLE_STREAMING_PREFILL_LAYER_PAGEIN` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables streaming prefill layer pagein. | [ds4.c:18432](ds4.c#L18432) |
+| `DS4_METAL_ENABLE_STREAMING_PREFILL_LAYER_READAHEAD` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables streaming prefill layer readahead. | [ds4.c:18442](ds4.c#L18442) |
+| `DS4_METAL_ENABLE_STREAMING_PREFILL_SELECTED_MADVISE` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables streaming prefill selected madvise. | [ds4.c:18422](ds4.c#L18422) |
+| `DS4_METAL_ENABLE_STREAMING_PREFILL_SELECTED_PAGEIN` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables streaming prefill selected pagein. | [ds4.c:18412](ds4.c#L18412) |
+| `DS4_METAL_ENABLE_STREAMING_PREFILL_SELECTED_READAHEAD` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables streaming prefill selected readahead. | [ds4.c:19956](ds4.c#L19956) |
+| `DS4_METAL_ENABLE_STREAMING_PREFILL_SELECTED_READAHEAD_SHARED` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables streaming prefill selected readahead shared. | [ds4.c:19958](ds4.c#L19958) |
+| `DS4_METAL_ENABLE_STREAMING_READAHEAD` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables streaming readahead. | [ds4.c:18203](ds4.c#L18203) |
+| `DS4_METAL_ENABLE_STREAMING_SELECTED_READAHEAD_SHARED_DELAY` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables streaming selected readahead shared delay. | [ds4.c:21719](ds4.c#L21719) |
+| `DS4_METAL_ENABLE_STREAMING_STATIC_DECODE_MAP` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables streaming static decode map. | [ds4.c:18222](ds4.c#L18222) |
+| `DS4_METAL_ENABLE_TOKEN_EMBED_EXACT_VIEW` | presence opt-in; unset: off/automatic; any value including 0 enables | Enables token embed exact view. | [ds4_metal.m:12219](ds4_metal.m#L12219) |
+| `DS4_METAL_EXACT_VIEW_CACHE_GIB` | unsigned GiB; default 64; 0 disables size-triggered eviction; MIB overrides it | Sets the cached exact-model-view eviction threshold. | [ds4_metal.m:1333](ds4_metal.m#L1333) |
+| `DS4_METAL_EXACT_VIEW_CACHE_MIB` | unsigned MiB; unset: inherit GIB/default; 0 disables size-triggered eviction; overrides GIB | Sets the cached exact-model-view eviction threshold with MiB precision. | [ds4_metal.m:1342](ds4_metal.m#L1342) |
+| `DS4_METAL_EXACT_VIEW_CACHE_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for exact view cache. | [ds4_metal.m:1377](ds4_metal.m#L1377) |
+| `DS4_METAL_FLASH_ATTN_SOURCE` | file path; unset/empty: use the in-tree Metal source file | Overrides the FlashAttention Metal kernel source file loaded at runtime. | [ds4_metal.m:4935](ds4_metal.m#L4935) |
+| `DS4_METAL_FLASH_ATTN_STAGE_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for flash attn stage. | [ds4.c:65152](ds4.c#L65152) |
+| `DS4_METAL_FLASH_ATTN_STAGE_PROFILE_FILTER` | substring; unset/empty: all profiled modes/stages | Filters FlashAttention stage-profile output by mode or stage substring. | [ds4_metal.m:11178](ds4_metal.m#L11178) |
+| `DS4_METAL_GET_ROWS_SOURCE` | file path; unset/empty: use the in-tree Metal source file | Overrides the get-rows Metal kernel source file loaded at runtime. | [ds4_metal.m:4946](ds4_metal.m#L4946) |
+| `DS4_METAL_GLM_DISABLE_STREAMING_EXPERT_CACHE` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming expert cache for GLM. | [ds4_metal.m:39667](ds4_metal.m#L39667) |
+| `DS4_METAL_GLM_DISABLE_STREAMING_GROUPED_ADDR_PREFILL` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming grouped address prefill for GLM. | [ds4_metal.m:41081](ds4_metal.m#L41081) |
+| `DS4_METAL_GLM_DISABLE_STREAMING_SEED_BEFORE_PREFILL` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming seed before prefill for GLM. | [ds4.c:51074](ds4.c#L51074) |
+| `DS4_METAL_GLM_DISABLE_STREAMING_TOKEN_PREFILL` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables streaming token prefill for GLM. | [ds4.c:49704](ds4.c#L49704) |
+| `DS4_METAL_GLM_MOE_ONE_STAGE_PROFILE` | unset: off; 1/true/yes/on/all enables all layers; accepts layer lists/ranges; 0/false/no/off disables | Prints timing/profile diagnostics for GLM MoE one stage. | [ds4_metal.m:39964](ds4_metal.m#L39964) |
+| `DS4_METAL_GLM_MOE_ONE_STAGE_PROFILE_LAYER` | layer index/list/ranges or all; unset: all layers selected by profiler | Restricts GLM one-stage MoE profiling to selected layers. | [ds4_metal.m:39965](ds4_metal.m#L39965) |
+| `DS4_METAL_GLM_MOE_STAGE_PROFILE_FILTER` | substring; unset/empty: all profiled stages | Filters GLM MoE stage-profile output. | [ds4_metal.m:39968](ds4_metal.m#L39968) |
+| `DS4_METAL_GLM_QKLOW_DEBUG` | presence diagnostic; unset: off; any value including 0 enables | Enables debug diagnostics for GLM qklow. | [ds4_metal.m:37868](ds4_metal.m#L37868) |
+| `DS4_METAL_GLM_STREAMING_ASYNC_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for GLM streaming async. | [ds4.c:44362](ds4.c#L44362) |
+| `DS4_METAL_GLM_STREAMING_DECODE_FULL_LAYER_MAP` | presence control; unset: off/default; any value including 0 enables | Maps complete GLM layers during SSD-streaming decode instead of decode-only spans. | [ds4.c:42616](ds4.c#L42616) |
+| `DS4_METAL_GLM_STREAMING_DECODE_SYNC_EACH_LAYER` | boolean text; Metal runtime always synchronizes and does not consult it; legacy fallback name read only in ROCm builds | Controls per-layer GLM streaming decode synchronization only as a legacy ROCm fallback alias. | [ds4.c:49780](ds4.c#L49780) |
+| `DS4_METAL_GLM_STREAMING_PREFILL_FULL_LAYER` | presence control; unset: off/default; any value including 0 enables | Forces full-layer GLM SSD prefill regardless of the token crossover. | [ds4_metal.m:14710](ds4_metal.m#L14710) |
+| `DS4_METAL_GLM_STREAMING_PREFILL_FULL_LAYER_MIN_TOKENS` | positive uint32; default 64 on Metal, 1024 when used as ROCm fallback; 0/invalid restores default | Sets the token crossover for GLM full-layer SSD prefill. | [ds4.c:42693](ds4.c#L42693) |
+| `DS4_METAL_GLM_STREAMING_PREFILL_SYNC_EACH_LAYER` | boolean text; Metal runtime always synchronizes and does not consult it; legacy fallback name read only in ROCm builds | Controls per-layer GLM streaming prefill synchronization only as a legacy ROCm fallback alias. | [ds4.c:42396](ds4.c#L42396) |
+| `DS4_METAL_GLM_STREAMING_TOKEN_PREFILL_MAX` | uint32; default 64 on Metal, 0 when used as ROCm fallback; 0 disables; invalid restores default | Sets largest GLM SSD prefill handled token-major by the decode graph. | [ds4.c:49683](ds4.c#L49683) |
+| `DS4_METAL_GLU_SOURCE` | file path; unset/empty: use the in-tree Metal source file | Overrides the GLU Metal kernel source file loaded at runtime. | [ds4_metal.m:4950](ds4_metal.m#L4950) |
+| `DS4_METAL_GPU_BATCH_EMBED_MIN` | uint32 token threshold; default 512; invalid restores default | Sets the batch size at which prompt embedding moves from CPU upload to Metal kernels. | [ds4.c:28867](ds4.c#L28867) |
+| `DS4_METAL_GPU_BUSY_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for GPU busy. | [ds4_metal.m:1293](ds4_metal.m#L1293) |
+| `DS4_METAL_GRAPH_DUMP_LAYER` | unsigned layer index or all; unset: every layer | Restricts graph tensor dumps to one layer. | [ds4.c:16863](ds4.c#L16863) |
+| `DS4_METAL_GRAPH_DUMP_LOGITS` | file path; unset/empty: no graph-logit dump | Writes Metal graph-test logits as f32 binary. | [ds4.c:39080](ds4.c#L39080) |
+| `DS4_METAL_GRAPH_DUMP_NAME` | substring; unset/empty: every tensor name | Restricts graph tensor dumps by tensor-name substring. | [ds4.c:16859](ds4.c#L16859) |
+| `DS4_METAL_GRAPH_DUMP_POS` | unsigned token position; unset: every position | Restricts graph tensor dumps to one token position. | [ds4.c:16870](ds4.c#L16870) |
+| `DS4_METAL_GRAPH_DUMP_PREFIX` | path/prefix; unset/empty: tensor dumping disabled | Enables graph tensor dumps and supplies the filename prefix. | [ds4.c:65148](ds4.c#L65148) |
+| `DS4_METAL_GRAPH_DUMP_TRACE` | presence diagnostic; unset: off; any value including 0 enables | Emits trace diagnostics for graph dump. | [ds4.c:16900](ds4.c#L16900) |
+| `DS4_METAL_GRAPH_OUTPUT_ROW` | zero-based row smaller than current batch; default final row; invalid restores final row | Chooses which prefill output row is projected to logits. | [ds4.c:35846](ds4.c#L35846) |
+| `DS4_METAL_GRAPH_PREFILL_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for graph prefill. | [ds4.c:35523](ds4.c#L35523) |
+| `DS4_METAL_GRAPH_PREFILL_SPLIT_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for graph prefill split. | [ds4.c:66204](ds4.c#L66204) |
+| `DS4_METAL_GRAPH_PROMPT_TOKENS` | integer 1..prompt length; default full prompt | Limits prompt length used by the Metal graph parity test. | [ds4.c:39023](ds4.c#L39023) |
+| `DS4_METAL_GRAPH_RAW_CAP` | positive rows; default from SWA window+prefill; clamped to [raw_window,min(ctx,8192)] | Overrides raw sliding-window KV ring capacity. | [ds4.c:38390](ds4.c#L38390) |
+| `DS4_METAL_GRAPH_TEACHER_FORCE` | presence control; unset: off/default; any value including 0 enables | Feeds CPU reference state back into the first-token graph trace at each layer. | [ds4.c:27742](ds4.c#L27742) |
+| `DS4_METAL_GRAPH_TOKEN_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for graph token. | [ds4.c:32382](ds4.c#L32382) |
+| `DS4_METAL_GRAPH_TOKEN_SECOND_SPLIT_LAYERS` | integer 0..layer count; default 0 plus eligible automatic pre-M5 schedules; explicit value wins | Overrides second command-buffer split layer for token decode. | [ds4.c:28029](ds4.c#L28029) |
+| `DS4_METAL_GRAPH_TOKEN_SPLIT_LAYERS` | integer 0..layer count; default 4 on Apple and 0 elsewhere, with eligible pre-M5 adaptive override | Overrides first command-buffer split layer for token decode. | [ds4.c:27915](ds4.c#L27915) |
+| `DS4_METAL_GRAPH_TRACE_CACHE` | presence control; unset: off/default; any value including 0 enables | Prints raw KV cache parity diagnostics in the graph prompt test. | [ds4.c:39092](ds4.c#L39092) |
+| `DS4_METAL_GRAPH_TRACE_COMP` | presence control; unset: off/default; any value including 0 enables | Prints compressed-cache parity diagnostics in the graph prompt test. | [ds4.c:39093](ds4.c#L39093) |
+| `DS4_METAL_GRAPH_TRACE_LAYERS` | presence control; unset: off/default; any value including 0 enables | Enables per-layer first-token CPU/GPU graph tracing. | [ds4.c:27739](ds4.c#L27739) |
+| `DS4_METAL_GRAPH_TRACE_STAGE_LAYER` | signed layer index; unset gives -1/no stage-layer selection | Selects the layer used by first-token stage tracing. | [ds4.c:27743](ds4.c#L27743) |
+| `DS4_METAL_HC_NORM_FUSION_CHECK` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Compares fused HC normalization against the reference result. | [ds4.c:20521](ds4.c#L20521) |
+| `DS4_METAL_HC_NORM_FUSION_CHECK_TOL` | positive finite float; default 2e-4; invalid/nonpositive restores default | Sets the numerical tolerance for the HC norm-fusion oracle. | [ds4.c:20530](ds4.c#L20530) |
+| `DS4_METAL_HC_STABLE` | boolean empty/1/true/yes/on vs 0/false/no/off; default on | Compiles stable hidden-context drift arithmetic into the Metal library. | [ds4_metal.m:7047](ds4_metal.m#L7047) |
+| `DS4_METAL_INDEXER_STAGE_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for indexer stage. | [ds4.c:17569](ds4.c#L17569) |
+| `DS4_METAL_IQ2_XXS_SSD_PREFILL_MM_STATS` | value-aware boolean; unset: off; empty/1/true/yes/on enables; 0/false/no/off disables | Collects/prints statistics for IQ2 XXS SSD prefill MM. | [ds4_metal.m:6980](ds4_metal.m#L6980) |
+| `DS4_METAL_KV_RAW_F32` | boolean empty/1/true/yes/on vs 0/false/no/off; default off | Compiles raw KV storage as F32 for drift diagnosis. | [ds4_metal.m:7049](ds4_metal.m#L7049) |
+| `DS4_METAL_LAYER_STAGE_PROFILE` | unset: off; 1/true/yes/on/all enables all layers; a layer index selects one; 0/false/no/off disables | Prints timing/profile diagnostics for layer stage. | [ds4.c:65150](ds4.c#L65150) |
+| `DS4_METAL_LAYER_STAGE_PROFILE_LAYER` | single unsigned layer index; unset/empty: all layers enabled by the parent profile; invalid matches no layer | Restricts the corresponding shared graph stage profiler to one layer. | [ds4.c:29109](ds4.c#L29109) |
+| `DS4_METAL_MATH_SAFE` | boolean empty/1/true/yes/on vs 0/false/no/off; default off | Compiles Metal shaders with strict/safe IEEE math instead of fast math. | [ds4_metal.m:7051](ds4_metal.m#L7051) |
+| `DS4_METAL_MEMORY_REPORT` | presence control; unset: off/default; any value including 0 enables | Prints Metal allocation/cache/residency memory reports. | [ds4.c:39047](ds4.c#L39047) |
+| `DS4_METAL_MODEL_UNTRACKED` | presence control; unset: off/default; any value including 0 enables | Creates mapped model buffers with untracked Metal hazard tracking. | [ds4_metal.m:1547](ds4_metal.m#L1547) |
+| `DS4_METAL_MODEL_VIEW_MAX_GIB` | positive integer GiB; default device maximum (128-GiB cap for already-split span maps); cannot exceed device maximum | Caps each no-copy mapped Metal model view. | [ds4_metal.m:2216](ds4_metal.m#L2216) |
+| `DS4_METAL_MODEL_WARMUP_STRIDE_KB` | integer 1..1048576 KiB, at least one page; unset inherits MB/default; overrides STRIDE_MB | Sets the model-view warmup touch stride with KiB precision. | [ds4_metal.m:3057](ds4_metal.m#L3057) |
+| `DS4_METAL_MODEL_WARMUP_STRIDE_MB` | integer 1..1024 MiB; default 1 MiB; STRIDE_KB overrides | Sets the model-view warmup touch stride. | [ds4_metal.m:3049](ds4_metal.m#L3049) |
+| `DS4_METAL_MOE_MM_ID_USE_RESOURCES` | presence control; unset: off/default; any value including 0 enables | Declares MM-ID MoE resource usage explicitly on the command encoder. | [ds4_metal.m:35168](ds4_metal.m#L35168) |
+| `DS4_METAL_MOE_ONE_STAGE_PROFILE` | unset: off; 1/true/yes/on/all enables all layers; accepts layer lists/ranges; 0/false/no/off disables | Prints timing/profile diagnostics for MoE one stage. | [ds4.c:22714](ds4.c#L22714) |
+| `DS4_METAL_MOE_ONE_STAGE_PROFILE_LAYER` | layer index/list/ranges or all; unset: all profiler-selected layers | Restricts one-stage MoE profiling to selected layers. | [ds4_metal.m:43436](ds4_metal.m#L43436) |
+| `DS4_METAL_MOE_SOURCE` | file path; unset/empty: use the in-tree Metal source file | Overrides the MoE Metal kernel source file loaded at runtime. | [ds4_metal.m:4937](ds4_metal.m#L4937) |
+| `DS4_METAL_MOE_STAGE_PROFILE` | unset: off; 1/true/yes/on/all enables all layers; accepts layer lists/ranges; 0/false/no/off disables | Prints timing/profile diagnostics for MoE stage. | [ds4.c:65154](ds4.c#L65154) |
+| `DS4_METAL_MOE_STAGE_PROFILE_FILTER` | substring; unset/empty: all profiled stages | Filters MoE stage-profile output. | [ds4_metal.m:43438](ds4_metal.m#L43438) |
+| `DS4_METAL_MOE_STAGE_PROFILE_LAYER` | layer index/list/ranges or all; unset: all profiler-selected layers | Restricts batched MoE stage profiling to selected layers. | [ds4_metal.m:45346](ds4_metal.m#L45346) |
+| `DS4_METAL_MOE_WRITE_CLAMPED_ACT` | presence control; unset: off/default; any value including 0 enables | Makes routed MoE write the clamped activation diagnostic. | [ds4.c:18527](ds4.c#L18527) |
+| `DS4_METAL_NORM_RSQRT_DISABLE` | boolean empty/1/true/yes/on vs 0/false/no/off; default on | Compiles unified normalization-rsqrt arithmetic into the Metal library. | [ds4_metal.m:7048](ds4_metal.m#L7048) |
+| `DS4_METAL_NORM_SOURCE` | file path; unset/empty: use the in-tree Metal source file | Overrides the normalization Metal kernel source file loaded at runtime. | [ds4_metal.m:4951](ds4_metal.m#L4951) |
+| `DS4_METAL_NO_MODEL_WARMUP` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables model warmup. | [ds4_metal.m:2309](ds4_metal.m#L2309) |
+| `DS4_METAL_NO_PREFILL_KERNEL_WARMUP` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables prefill kernel warmup. | [ds4.c:28965](ds4.c#L28965) |
+| `DS4_METAL_NO_RESIDENCY` | presence rollback; unset: automatic/default path; any value including 0 disables | Disables residency. | [ds4_metal.m:2092](ds4_metal.m#L2092) |
+| `DS4_METAL_OUTPUT_STAGE_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for output stage. | [ds4.c:17570](ds4.c#L17570) |
+| `DS4_METAL_PREFILL_CHUNK` | positive token count used only when CLI chunk is absent; default full prompt, or 4096 for long non-PRO and 8192 for long PRO prompts; <=0 keeps automatic/full prompt | Provides the historical environment fallback for prefill chunk size. | [ds4.c:12802](ds4.c#L12802) |
+| `DS4_METAL_PRO_Q4_CPU_ROUTER` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Uses the CPU router for PRO Q4 selected-expert decode. | [ds4.c:20934](ds4.c#L20934) |
+| `DS4_METAL_PRO_Q4_CPU_ROUTER_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for pro Q4 CPU router. | [ds4.c:21644](ds4.c#L21644) |
+| `DS4_METAL_Q4_ADDR_USE_RESOURCES` | presence control; unset: off/default; any value including 0 enables | Declares Q4 address-table resources explicitly on encoders. | [ds4_metal.m:20259](ds4_metal.m#L20259) |
+| `DS4_METAL_Q4_EXPERT_GROUP_SIZE` | positive uint32; default 32; clamped to total expert count | Sets experts processed per grouped Q4 dispatch. | [ds4_metal.m:34088](ds4_metal.m#L34088) |
+| `DS4_METAL_Q4_EXPERT_TABLE_GROUP_SIZE` | integer 2..total experts; default/invalid 1 (ungrouped) | Sets grouped exact-view width while building Q4 expert tables. | [ds4_metal.m:19604](ds4_metal.m#L19604) |
+| `DS4_METAL_Q4_EXPERT_TABLE_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for Q4 expert table. | [ds4_metal.m:20103](ds4_metal.m#L20103) |
+| `DS4_METAL_Q4_GROUP24_BASE_VIEWS` | presence control; unset: off/default; any value including 0 enables | Uses broad base model views for Q4 group-24 instead of exact views. | [ds4_metal.m:42205](ds4_metal.m#L42205) |
+| `DS4_METAL_Q4_GROUP24_EXACT_VIEWS` | presence control; unset: off/default; any value including 0 enables | Uses exact mapped views for Q4 group-24 experts. | [ds4_metal.m:42204](ds4_metal.m#L42204) |
+| `DS4_METAL_Q4_GROUPED_CACHE_VIEWS` | presence control; unset: off/default; any value including 0 enables | Caches exact Q4 grouped expert views. | [ds4_metal.m:42151](ds4_metal.m#L42151) |
+| `DS4_METAL_Q4_PRO_MAP_GROUPS` | positive divisor of 384 in 1..384; default/invalid 1 | Splits each 384-expert PRO Q4 tensor into this many mapped views. | [ds4.c:6276](ds4.c#L6276) |
+| `DS4_METAL_Q4_SELECTED_EXACT_VIEWS` | presence control; unset: off/default; any value including 0 enables | Forces exact/cached views for selected Q4 experts instead of base views. | [ds4_metal.m:42528](ds4_metal.m#L42528) |
+| `DS4_METAL_Q4_SELECTED_OVERLAP_SHARED` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Overlaps selected Q4 expert preparation with the shared expert. | [ds4.c:20962](ds4.c#L20962) |
+| `DS4_METAL_Q4_SELECTED_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for Q4 selected. | [ds4.c:37944](ds4.c#L37944) |
+| `DS4_METAL_Q4_SELECTED_PROFILE_LAYER` | single nonnegative layer index; unset: every layer | Restricts legacy Q4 selected-expert profiling to one layer. | [ds4_metal.m:42509](ds4_metal.m#L42509) |
+| `DS4_METAL_Q4_SELECTED_SHARED_EVENT` | presence control; unset: off/default; any value including 0 enables | Coordinates selected Q4 work with a shared Metal event. | [ds4_metal.m:42524](ds4_metal.m#L42524) |
+| `DS4_METAL_Q4_SELECTED_TRANSIENT_VIEWS` | presence control; unset: off/default; any value including 0 enables | Uses transient exact views for selected Q4 experts. | [ds4_metal.m:42532](ds4_metal.m#L42532) |
+| `DS4_METAL_Q4_SELECTED_USE_BASE_VIEWS` | presence control; unset: off/default; any value including 0 enables | Uses broad base model views for selected Q4 experts. | [ds4_metal.m:42527](ds4_metal.m#L42527) |
+| `DS4_METAL_Q4_TABLE_BIND_ANCHORS` | presence control; unset: off/default; any value including 0 enables | Binds anchor buffers alongside the Q4 expert address table. | [ds4_metal.m:19716](ds4_metal.m#L19716) |
+| `DS4_METAL_Q4_TABLE_MODEL_RESIDENCY_SET` | presence control; unset: off/default; any value including 0 enables | Adds Q4 expert table allocations to the model residency set. | [ds4_metal.m:19657](ds4_metal.m#L19657) |
+| `DS4_METAL_Q4_TABLE_PER_TENSOR_RESIDENCY_SET` | presence control; unset: off/default; any value including 0 enables | Builds separate residency sets per Q4 expert tensor. | [ds4_metal.m:19760](ds4_metal.m#L19760) |
+| `DS4_METAL_Q4_TABLE_QUEUE_RESIDENCY_SET` | presence control; unset: off/default; any value including 0 enables | Attaches Q4 expert table residency sets to command queues. | [ds4_metal.m:19615](ds4_metal.m#L19615) |
+| `DS4_METAL_Q4_TABLE_RESIDENCY_SET` | presence control; unset: off/default; any value including 0 enables | Enables Q4 expert table residency-set handling. | [ds4_metal.m:19759](ds4_metal.m#L19759) |
+| `DS4_METAL_Q4_TABLE_USE_RESOURCES` | presence control; unset: off/default; any value including 0 enables | Declares Q4 table resources explicitly on encoders. | [ds4_metal.m:20258](ds4_metal.m#L20258) |
+| `DS4_METAL_Q8_DECODE_EXACT_VIEW_MAX_MIB` | integer 1..4096 MiB; default 1024; above max clamps, below min/invalid restores default | Caps weight ranges eligible for Q8 exact model views. | [ds4_metal.m:12876](ds4_metal.m#L12876) |
+| `DS4_METAL_Q8_MV_EXT_MAX_TOKENS` | integer 2..128; default 16; above max clamps, below min/invalid restores default | Sets largest batch handled by extended Q8 matvec. | [ds4_metal.m:21126](ds4_metal.m#L21126) |
+| `DS4_METAL_Q8_MV_NSG` | integer 1..8 simdgroups; default 4, or 2 with TP world=2; above max clamps, below min/invalid restores default | Overrides simdgroups per Q8 matvec threadgroup. | [ds4.c:22730](ds4.c#L22730) |
+| `DS4_METAL_Q8_PREFILL_PROFILE` | value-aware boolean; unset: off; empty/1/true/yes/on enables; 0/false/no/off disables | Prints timing/profile diagnostics for Q8 prefill. | [ds4_metal.m:21280](ds4_metal.m#L21280) |
+| `DS4_METAL_Q8_PREFILL_PROFILE_FILTER` | substring matched against generated operation label; unset/empty: all eligible calls | Filters Q8 prefill profiling. | [ds4_metal.m:21295](ds4_metal.m#L21295) |
+| `DS4_METAL_Q_STAGE_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for q stage. | [ds4.c:29270](ds4.c#L29270) |
+| `DS4_METAL_REPEAT_SOURCE` | file path; unset/empty: use the in-tree Metal source file | Overrides the repeat Metal kernel source file loaded at runtime. | [ds4_metal.m:4949](ds4_metal.m#L4949) |
+| `DS4_METAL_REQUIRE_COMPRESSOR_EXACT_POOL_RATIO4` | presence strict check; unset: fallback allowed; any value including 0 requires the path | Requires compressor exact pool ratio4 and makes eligible fallback fail closed. | [ds4_metal.m:26387](ds4_metal.m#L26387) |
+| `DS4_METAL_REQUIRE_DECODE_ARGMAX_TOP1` | presence fail-closed assertion for rows of at least 4096 logits; unset permits generic fallback; any defined value including empty or 0 rejects disabled, ineligible, or failed dedicated top-1 preflight | Require the dedicated Metal top-1 reduction so correctness and performance oracles cannot silently exercise generic argsort. | [ds4_metal.m:21515](ds4_metal.m#L21515) |
+| `DS4_METAL_REQUIRE_EXACT_ROWS_PERSISTENT_CACHE` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Requires exact rows persistent cache and makes eligible fallback fail closed. | [ds4_metal.m:13002](ds4_metal.m#L13002) |
+| `DS4_METAL_REQUIRE_GATHERED_KV_STAGE` | presence strict check; unset: fallback allowed; any value including 0 requires the path | Requires gathered KV stage and makes eligible fallback fail closed. | [ds4_metal.m:29680](ds4_metal.m#L29680) |
+| `DS4_METAL_REQUIRE_IQ2_XXS_SSD_PREFILL_MM` | value-aware boolean; default implicit fail-closed only with complete selected-address domain; explicit 1 is strict, 0 permits fallback | Makes eligible IQ2_XXS/Q2_K grouped SSD-prefill MM fail closed. | [ds4_metal.m:44782](ds4_metal.m#L44782) |
+| `DS4_METAL_REQUIRE_M1_IQ2_MID_ONLY` | presence strict check; unset: fallback allowed; any value including 0 requires the path | Requires M1 IQ2 mid only and makes eligible fallback fail closed. | [ds4_metal.m:42074](ds4_metal.m#L42074) |
+| `DS4_METAL_REQUIRE_OUTPUT_HC_WEIGHTS4` | presence strict check; unset: fallback allowed; any value including 0 requires the path | Requires output HC weights4 and makes eligible fallback fail closed. | [ds4_metal.m:46789](ds4_metal.m#L46789) |
+| `DS4_METAL_REQUIRE_Q4_ATTN_OUT_A_DIRECT` | presence strict check; unset permits the automatic path or fallback; any defined value including 0 requires the direct kernel and DISABLE wins | Require the bit-identical fixed-route Q4 attention output-A kernel and fail closed before dispatch when its production contract is unavailable. | [ds4_metal.m:31560](ds4_metal.m#L31560) |
+| `DS4_METAL_REQUIRE_Q4_ATTN_OUT_TINY_BATCH` | value-aware boolean; unset: off; empty/1/true/yes/on enables; 0/false/no/off disables | Requires Q4 attn out tiny batch and makes eligible fallback fail closed. | [ds4_metal.m:28373](ds4_metal.m#L28373) |
+| `DS4_METAL_REQUIRE_Q4_SSD_PREFILL_ATTN_OUT_EXACTN` | value-aware boolean; unset: off; empty/1/true/yes/on enables; 0/false/no/off disables | Requires Q4 SSD prefill attn out exactn and makes eligible fallback fail closed. | [ds4_metal.m:28089](ds4_metal.m#L28089) |
+| `DS4_METAL_REQUIRE_Q4_SSD_PREFILL_ATTN_OUT_SCALE_META` | value-aware boolean; unset: off; empty/1/true/yes/on enables; 0/false/no/off disables | Requires shared scale/min metadata in the Q4 SSD prefill attention-output exact-N kernel and makes fallback fail closed. | [ds4_metal.m:28209](ds4_metal.m#L28209) |
+| `DS4_METAL_REQUIRE_Q4_SSD_SESSION_UNION` | nonempty boolean; unset/empty or exact 0: off; every other value: on | Requires Q4 SSD session union and makes eligible fallback fail closed. | [ds4.c:65164](ds4.c#L65164) |
+| `DS4_METAL_REQUIRE_Q8_QKV_COMPRESSOR_FUSE` | nonempty boolean; unset/empty/exact 0: fallback allowed; other values require and imply the streamed/union enable | Requires eligible Q8 QKV/compressor compound fusion and fails closed. | [ds4.c:23023](ds4.c#L23023) |
+| `DS4_METAL_RESUME_PREFILL_MIN` | integer token threshold; default 4; <=0 disables resume-prefill | Sets the minimum shared-prefix suffix that uses batched resume-prefill. | [ds4.c:38419](ds4.c#L38419) |
+| `DS4_METAL_ROPE_EXP2_LOG2` | boolean empty/1/true/yes/on vs 0/false/no/off; default off | Compiles the exp2/log2 RoPE drift variant. | [ds4_metal.m:7050](ds4_metal.m#L7050) |
+| `DS4_METAL_SELECTED_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for selected. | [ds4.c:37943](ds4.c#L37943) |
+| `DS4_METAL_SELECTED_PROFILE_LAYER` | single nonnegative layer index; unset: every layer | Restricts selected-expert profiling to one layer. | [ds4_metal.m:42507](ds4_metal.m#L42507) |
+| `DS4_METAL_SESSION_BATCH_LOG` | presence diagnostic; unset: off; any value including 0 enables | Logs session batch decisions. | [ds4.c:66168](ds4.c#L66168) |
+| `DS4_METAL_SESSION_BATCH_QKV` | default enabled; exact 0 disables; every other value/unset leaves enabled | Controls native batched QKV work for multi-session decode. | [ds4.c:65482](ds4.c#L65482) |
+| `DS4_METAL_SESSION_BATCH_SHARED` | default enabled; exact 0 disables; every other value/unset leaves enabled | Controls native batched shared-expert work for multi-session decode. | [ds4.c:65432](ds4.c#L65432) |
+| `DS4_METAL_SET_ROWS_SOURCE` | file path; unset/empty: use the in-tree Metal source file | Overrides the set-rows Metal kernel source file loaded at runtime. | [ds4_metal.m:4953](ds4_metal.m#L4953) |
+| `DS4_METAL_SOFTMAX_SOURCE` | file path; unset/empty: use the in-tree Metal source file | Overrides the softmax Metal kernel source file loaded at runtime. | [ds4_metal.m:4948](ds4_metal.m#L4948) |
+| `DS4_METAL_STREAMING_DECODE_PREFILL_MAX` | integer token maximum; default 64 for wide Flash Q4/MXFP4, 18 for other PRO/Flash, 0 otherwise; <=0 disables | Sets maximum SSD-streaming micro-prefill width that reuses decode. | [ds4.c:31962](ds4.c#L31962) |
+| `DS4_METAL_STREAMING_EXPERT_AUTO_PRELOAD_CAP` | uint32 expert cap; default 4096; 0 means unlimited; invalid restores default | Caps automatic streaming-expert hotlist preload. | [ds4.c:21455](ds4.c#L21455) |
+| `DS4_METAL_STREAMING_EXPERT_BUFFER_MLOCK_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for streaming expert buffer mlock. | [ds4_metal.m:13997](ds4_metal.m#L13997) |
+| `DS4_METAL_STREAMING_EXPERT_EARLY_LOAD_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for streaming expert early load. | [ds4_metal.m:17059](ds4_metal.m#L17059) |
+| `DS4_METAL_STREAMING_EXPERT_EVICT_DONTNEED_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for streaming expert evict dontneed. | [ds4_metal.m:14436](ds4_metal.m#L14436) |
+| `DS4_METAL_STREAMING_EXPERT_HOTLIST` | hotlist file path; unset/empty: built-in model hotlist | Loads the streaming-expert preload order from a file. | [ds4.c:21495](ds4.c#L21495) |
+| `DS4_METAL_STREAMING_EXPERT_HOTLIST_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for streaming expert hotlist. | [ds4.c:32245](ds4.c#L32245) |
+| `DS4_METAL_STREAMING_EXPERT_LAYER_STATS` | presence diagnostic; unset: off; any value including 0 enables | Collects/prints statistics for streaming expert layer. | [ds4_metal.m:4638](ds4_metal.m#L4638) |
+| `DS4_METAL_STREAMING_EXPERT_LAYER_STATS_DELTA` | presence control; unset: off/default; any value including 0 enables | Prints delta statistics for streaming expert layer. | [ds4_metal.m:4675](ds4_metal.m#L4675) |
+| `DS4_METAL_STREAMING_EXPERT_NOCACHE` | nonempty value whose first character is not 0 enables; unset/empty/0 disables | Uses a reopened F_NOCACHE descriptor for SSD expert preads. | [ds4_metal.m:12602](ds4_metal.m#L12602) |
+| `DS4_METAL_STREAMING_EXPERT_PREAD_POOL` | default enabled; exact 0 disables; every other value/unset keeps enabled | Controls reuse of persistent expert-pread worker threads. | [ds4_metal.m:13433](ds4_metal.m#L13433) |
+| `DS4_METAL_STREAMING_EXPERT_PREAD_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for streaming expert pread. | [ds4_metal.m:17005](ds4_metal.m#L17005) |
+| `DS4_METAL_STREAMING_EXPERT_PREAD_SPLIT` | integer clamped 1..8; unset: automatic 1 below 64 cache experts, 4 at 64+ | Sets aligned requests per expert pread. | [ds4_metal.m:13701](ds4_metal.m#L13701) |
+| `DS4_METAL_STREAMING_EXPERT_PREAD_THREADS` | unsigned integer clamped 1..18; default 9; invalid restores 9 | Sets expert-pread worker limit. | [ds4_metal.m:13337](ds4_metal.m#L13337) |
+| `DS4_METAL_STREAMING_EXPERT_PROFILE_SUMMARY` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for streaming expert. | [ds4_metal.m:13061](ds4_metal.m#L13061) |
+| `DS4_METAL_STREAMING_EXPERT_SLAB_MB` | positive unsigned MiB; default 4096; 0/invalid restores default | Sets target allocation size for streaming-expert slabs. | [ds4_metal.m:14039](ds4_metal.m#L14039) |
+| `DS4_METAL_STREAMING_EXPERT_SPLIT_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for streaming expert split. | [ds4_metal.m:43810](ds4_metal.m#L43810) |
+| `DS4_METAL_STREAMING_EXPERT_TIMING_SUMMARY` | presence control; unset: off/default; any value including 0 enables | Prints timing/profile diagnostics for streaming expert. | [ds4_metal.m:13060](ds4_metal.m#L13060) |
+| `DS4_METAL_STREAMING_IQ2_CPU_ROUTER_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for streaming IQ2 CPU router. | [ds4.c:21645](ds4.c#L21645) |
+| `DS4_METAL_STREAMING_MAP_TRACE` | nonempty value other than exact 0 enables; unset/empty/0 disables | Emits SSD model-map decisions. | [ds4_metal.m:4849](ds4_metal.m#L4849) |
+| `DS4_METAL_STREAMING_PREFILL_BATCH_SELECTED_ADDR_MAX` | integer token maximum; default 800 for 384 experts, 760 for 256, 0 otherwise; <=0 disables automatic selection | Sets automatic maximum batch width for selected-address SSD prefill. | [ds4_metal.m:14639](ds4_metal.m#L14639) |
+| `DS4_METAL_STREAMING_PREFILL_BATCH_SELECTED_ADDR_MIN` | integer token minimum; default 2 for 256/384 experts, 0 otherwise; <=0 disables automatic selection | Sets automatic minimum batch width for selected-address SSD prefill. | [ds4_metal.m:14656](ds4_metal.m#L14656) |
+| `DS4_METAL_STREAMING_PREFILL_BATCH_SELECTED_ADDR_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for streaming prefill batch selected address. | [ds4_metal.m:18493](ds4_metal.m#L18493) |
+| `DS4_METAL_STREAMING_PREFILL_CACHE_SEED_K` | uint32 seed rows; default 1; 0 disables; above 64 clamps to 64 | Sets how many prefill routing rows seed the decode expert cache. | [ds4.c:21268](ds4.c#L21268) |
+| `DS4_METAL_STREAMING_PREFILL_CACHE_SEED_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for streaming prefill cache seed. | [ds4_metal.m:17899](ds4_metal.m#L17899) |
+| `DS4_METAL_STREAMING_PREFILL_LAYER_MADVISE_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for streaming prefill layer madvise. | [ds4.c:19610](ds4.c#L19610) |
+| `DS4_METAL_STREAMING_PREFILL_LAYER_PAGEIN_NO_OVERLAP` | presence rollback; unset: automatic/default path; any value including 0 disables | Prevents full-layer page-in preparation from overlapping compute. | [ds4.c:19317](ds4.c#L19317) |
+| `DS4_METAL_STREAMING_PREFILL_LAYER_PAGEIN_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for streaming prefill layer pagein. | [ds4.c:19606](ds4.c#L19606) |
+| `DS4_METAL_STREAMING_PREFILL_LAYER_PAGEIN_THREADS` | integer 1..16; default 8; invalid/0 becomes 1; PREPARE_THREADS takes precedence | Sets worker count for full-layer page-in preparation. | [ds4.c:19275](ds4.c#L19275) |
+| `DS4_METAL_STREAMING_PREFILL_LAYER_PREAD_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for streaming prefill layer pread. | [ds4.c:19608](ds4.c#L19608) |
+| `DS4_METAL_STREAMING_PREFILL_LAYER_PREPARE_AHEAD` | integer 1..4 layers; default 1; invalid/0 becomes 1 | Sets number of future layers prepared concurrently. | [ds4.c:19329](ds4.c#L19329) |
+| `DS4_METAL_STREAMING_PREFILL_LAYER_PREPARE_NO_OVERLAP` | presence rollback; unset: automatic/default path; any value including 0 disables | Prevents generic full-layer preparation from overlapping compute. | [ds4.c:19315](ds4.c#L19315) |
+| `DS4_METAL_STREAMING_PREFILL_LAYER_PREPARE_THREADS` | integer 1..16; default 8; invalid/0 becomes 1; preferred over PAGEIN_THREADS | Sets worker count for full-layer preparation. | [ds4.c:19271](ds4.c#L19271) |
+| `DS4_METAL_STREAMING_PREFILL_LAYER_READAHEAD_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for streaming prefill layer readahead. | [ds4.c:19612](ds4.c#L19612) |
+| `DS4_METAL_STREAMING_PREFILL_SELECTED_MADVISE_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for streaming prefill selected madvise. | [ds4.c:19356](ds4.c#L19356) |
+| `DS4_METAL_STREAMING_PREFILL_SELECTED_MADVISE_THREADS` | integer 1..16; default inherits layer prepare threads; invalid/0 becomes 1; PREPARE_THREADS preferred | Sets worker count for selected-expert madvise preparation. | [ds4.c:19293](ds4.c#L19293) |
+| `DS4_METAL_STREAMING_PREFILL_SELECTED_PAGEIN_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for streaming prefill selected pagein. | [ds4.c:19354](ds4.c#L19354) |
+| `DS4_METAL_STREAMING_PREFILL_SELECTED_PREPARE_GAP` | integer 0..8 layers; default 0; above 8 clamps; invalid restores 0 | Sets lookahead gap for selected-expert preparation. | [ds4.c:19305](ds4.c#L19305) |
+| `DS4_METAL_STREAMING_PREFILL_SELECTED_PREPARE_THREADS` | integer 1..16 for madvise preparation; default inherits layer prepare threads; invalid/0 becomes 1 | Sets worker count for selected-expert preparation. | [ds4.c:19289](ds4.c#L19289) |
+| `DS4_METAL_STREAMING_PREFILL_SELECTED_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for streaming prefill selected. | [ds4.c:18906](ds4.c#L18906) |
+| `DS4_METAL_STREAMING_PREFILL_SELECTED_READAHEAD_GAP` | integer 0..8 layers; default 0; above 8 clamps; invalid restores 0 | Sets lookahead gap for selected-expert readahead. | [ds4.c:19978](ds4.c#L19978) |
+| `DS4_METAL_STREAMING_PREFILL_SELECTED_READAHEAD_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for streaming prefill selected readahead. | [ds4.c:20063](ds4.c#L20063) |
+| `DS4_METAL_STREAMING_SELECTED_READAHEAD_PROFILE` | presence diagnostic; unset: off; any value including 0 enables | Prints timing/profile diagnostics for streaming selected readahead. | [ds4.c:21737](ds4.c#L21737) |
+| `DS4_METAL_SUM_ROWS_SOURCE` | file path; unset/empty: use the in-tree Metal source file | Overrides the sum-rows Metal kernel source file loaded at runtime. | [ds4_metal.m:4947](ds4_metal.m#L4947) |
+| `DS4_METAL_TEST_POISON_COMPRESSOR_EXACT_REDUCTION_SCRATCH` | internal test presence flag; unset: off; any value including 0 poisons scratch before the exact reduction | Validates that compressor exact-reduction kernels overwrite all scratch state. | [ds4_metal.m:25925](ds4_metal.m#L25925) |
+| `DS4_METAL_TP_SESSION_BATCH` | default enabled; exact 0 disables; every other value/unset leaves enabled | Controls batched session evaluation with Metal TP. | [ds4.c:65310](ds4.c#L65310) |
+| `DS4_METAL_TRACE_ALLOCS` | presence diagnostic; unset: off; any value including 0 enables | Emits trace diagnostics for allocs. | [ds4_metal.m:4057](ds4_metal.m#L4057) |
+| `DS4_METAL_TRACE_M5_FLASH_ATTN_PACKED32_REDUCE` | presence diagnostic; unset: off; any value including 0 enables | Emits trace diagnostics for M5 flash attn packed32 reduce. | [ds4_metal.m:31535](ds4_metal.m#L31535) |
+| `DS4_METAL_UNARY_SOURCE` | file path; unset/empty: use the in-tree Metal source file | Overrides the unary operations Metal kernel source file loaded at runtime. | [ds4_metal.m:4939](ds4_metal.m#L4939) |
+| `DS4_METAL_UNRETAINED_COMMAND_BUFFERS` | presence control; unset: off/default; any value including 0 enables | Creates Metal command buffers with unretained references. | [ds4_metal.m:1315](ds4_metal.m#L1315) |
+| `DS4_METAL_USE_QUEUE_RESIDENCY_SET` | presence control; unset: off/default; any value including 0 enables | Allows queue-residency state to trigger Q4 expert address/table paths. | [ds4_metal.m:42280](ds4_metal.m#L42280) |
+
+
+
+
+CUDA (336)
+
+| Variable | Accepted value and default | Effect | Source |
+| --- | --- | --- | --- |
+| `DS4_CUDA_ATTENTION_OUTPUT_A_CUBLAS_MIN` | integer tokens; default 2; accepted range 2..4095, otherwise 2 | Set the token-count threshold for using cuBLAS on attention output-A. | [ds4_cuda.cu:23925](ds4_cuda.cu#L23925) |
+| `DS4_CUDA_ATTENTION_OUTPUT_PRELOAD` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Allow attention-output Q8 weights to be preloaded into the selective F16 cache. | [ds4_cuda.cu:2402](ds4_cuda.cu#L2402) |
+| `DS4_CUDA_ATTN_OUTPUT_PROFILE` | presence diagnostic flag; default off; any defined value including 0 enables | Measure and print CUDA attention-output stage timings. | [ds4_cuda.cu:23910](ds4_cuda.cu#L23910) |
+| `DS4_CUDA_ATTN_Q_B_F32_CACHE` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Enable an F32-derived-weight cache for attention Q-B weights. | [ds4_cuda.cu:2414](ds4_cuda.cu#L2414) |
+| `DS4_CUDA_BUILD_ARTIFACTS` | boolean-ish, default on for eligible derived artifacts; only exact 0 disables | Control construction of eligible CUDA derived/repacked weight artifacts. | [ds4_cuda.cu:8440](ds4_cuda.cu#L8440) |
+| `DS4_CUDA_COPY_MODEL` | nonempty-string opt-in (but mere presence also suppresses prefetch); default off; value 0 is nonempty and requests a full copy | Copy the complete mapped model image into device memory. | [ds4_cuda.cu:2740](ds4_cuda.cu#L2740) |
+| `DS4_CUDA_COPY_MODEL_CHUNKED` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Use range-by-range model prefetch/copy preparation instead of the normal bulk preparation. | [ds4_cuda.cu:37740](ds4_cuda.cu#L37740) |
+| `DS4_CUDA_DECODE_GRAPHS` | boolean, default on; any value starting with 0, or exact off/no/false in listed case variants, disables; oracle flags force off; effective only on one GPU | Control CUDA Graph capture and replay for decode. | [ds4_cuda.cu:1468](ds4_cuda.cu#L1468) |
+| `DS4_CUDA_DECODE_GRAPH_LOG` | presence diagnostic flag; default off; any defined value including 0 enables | Log CUDA decode-graph cache misses, capture failures, and lifecycle events. | [ds4_cuda.cu:1580](ds4_cuda.cu#L1580) |
+| `DS4_CUDA_DECODE_HEADS8_ONLINE` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Force the eight-head online CUDA decode-attention kernel when eligible. | [ds4_cuda.cu:371](ds4_cuda.cu#L371) |
+| `DS4_CUDA_DECODE_SCORE4` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Select four score lanes in the CUDA decode-attention fallback kernel. | [ds4_cuda.cu:372](ds4_cuda.cu#L372) |
+| `DS4_CUDA_DECODE_SCORE8` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Select eight score lanes in the CUDA decode-attention fallback kernel. | [ds4_cuda.cu:373](ds4_cuda.cu#L373) |
+| `DS4_CUDA_DIRECT_MODEL` | mixed presence/nonempty flag, default off; any defined value bypasses host caching, while backend direct lookup requires nonempty; value 0 therefore still changes behavior | Use the mapped model directly and bypass selective CUDA weight caching. | [ds4.c:3058](ds4.c#L3058); [ds4_cuda.cu:1250](ds4_cuda.cu#L1250) |
+| `DS4_CUDA_DISABLE_DSPARK_EXACTN` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Disable the CUDA DSpark exactn optimization. | [ds4.c:52270](ds4.c#L52270) |
+| `DS4_CUDA_DISABLE_DSPARK_EXACTN_BATCH_HEAD` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Disable the CUDA DSpark exactn batch head optimization. | [ds4.c:37285](ds4.c#L37285) |
+| `DS4_CUDA_DISABLE_DSPARK_EXACTN_GRAPHS` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Disable the CUDA DSpark exactn graphs optimization. | [ds4.c:37251](ds4.c#L37251) |
+| `DS4_CUDA_DISABLE_DSPARK_NONCAUSAL_ONLINE` | value-aware flag, default off; unset/empty/exact 0 is off, any other nonempty value is on | Disable the noncausal online-attention DSpark experiment. | [ds4_cuda.cu:21691](ds4_cuda.cu#L21691) |
+| `DS4_CUDA_DISABLE_HC_NORM_MIX_FUSE` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable fused HC RMSNorm-plus-mix. | [ds4_cuda.cu:20905](ds4_cuda.cu#L20905) |
+| `DS4_CUDA_DISABLE_HC_SPLIT_NORM_FUSED` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the fused HC split/weighted-sum/norm kernel. | [ds4_cuda.cu:31785](ds4_cuda.cu#L31785) |
+| `DS4_CUDA_DISABLE_IQ2_XXS_SSD_PREFILL_MMQ` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, any other nonempty value is on; disable flags dominate | Disable the CUDA IQ2 XXS SSD prefill MMQ optimization/path. | [ds4_cuda.cu:4627](ds4_cuda.cu#L4627) |
+| `DS4_CUDA_DISABLE_Q4_ATTN_OUT_HC_FUSE` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable fused Q4 attention-output/HC expansion. | [ds4_cuda.cu:37357](ds4_cuda.cu#L37357) |
+| `DS4_CUDA_DISABLE_Q4_DENSE_PAIR` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the Q4 dense pair CUDA Q4 optimization. | [ds4_cuda.cu:20402](ds4_cuda.cu#L20402) |
+| `DS4_CUDA_DISABLE_Q8_HC_EXPAND_FUSED` | false-like-aware flag, default off; 0/false/no/off is off, other nonempty values request split; force-fused wins | Request the split Q8 shared-down/HC path when safe. | [ds4_cuda.cu:2086](ds4_cuda.cu#L2086) |
+| `DS4_CUDA_DISABLE_QKV_RMS_FUSED` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the CUDA QKV RMS fused optimization/path. | [ds4_cuda.cu:369](ds4_cuda.cu#L369); [ds4.c:17428](ds4.c#L17428) |
+| `DS4_CUDA_DISABLE_SHARED_GATE_UP_PAIR` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the CUDA shared gate up pair optimization/path. | [ds4_cuda.cu:24293](ds4_cuda.cu#L24293) |
+| `DS4_CUDA_DISABLE_STREAMING_EXPERT_PERSISTENT_CACHE` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, any other nonempty value is on; disable flags dominate | Disable streaming expert persistent cache in CUDA SSD streaming. | [ds4_cuda.cu:4113](ds4_cuda.cu#L4113) |
+| `DS4_CUDA_DISABLE_STREAMING_PREFILL_BATCH_SELECTED_ADDR` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable streaming prefill batch selected addr in CUDA SSD streaming. | [ds4.c:18592](ds4.c#L18592) |
+| `DS4_CUDA_DISABLE_STREAMING_PREFILL_BATCH_SELECTED_LOAD` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable streaming prefill batch selected load in CUDA SSD streaming. | [ds4.c:21917](ds4.c#L21917) |
+| `DS4_CUDA_DISABLE_STREAMING_SELECTED_BATCH_IO` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, any other nonempty value is on; disable flags dominate | Disable streaming selected batch I/O in CUDA SSD streaming. | [ds4_cuda.cu:4734](ds4_cuda.cu#L4734) |
+| `DS4_CUDA_DISABLE_STREAMING_SELECTED_EVENT_PIPELINE` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, any other nonempty value is on; disable flags dominate | Disable streaming selected event pipeline in CUDA SSD streaming. | [ds4_cuda.cu:4866](ds4_cuda.cu#L4866) |
+| `DS4_CUDA_DISABLE_STREAMING_SELECTED_SHARED_OVERLAP` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable streaming selected shared overlap in CUDA SSD streaming. | [ds4.c:20969](ds4.c#L20969) |
+| `DS4_CUDA_DSPARK_DEVICE_PROPOSER` | value-aware opt-in, default off; 0/off/no/false (lowercase only) disable; other nonempty enables unless rollback set | Enable the CUDA-resident DSpark proposer. | [ds4.c:34889](ds4.c#L34889); [ds4_cuda.cu:19035](ds4_cuda.cu#L19035) |
+| `DS4_CUDA_DSPARK_EXACT2` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Enable the exact two-draft CUDA DSpark support path. | [ds4.c:52247](ds4.c#L52247) |
+| `DS4_CUDA_DSPARK_EXACTN` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Enable the exact multi-draft CUDA DSpark support path. | [ds4.c:52268](ds4.c#L52268) |
+| `DS4_CUDA_DSPARK_EXACTN_BATCH_HEAD` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Enable the batched output-head stage for exact-N DSpark verification. | [ds4.c:37283](ds4.c#L37283) |
+| `DS4_CUDA_DSPARK_EXACTN_GRAPHS` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Enable CUDA Graph capture for stable exact-N DSpark islands. | [ds4.c:37249](ds4.c#L37249) |
+| `DS4_CUDA_DSPARK_NO_DEVICE_PROPOSER` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the CUDA-resident DSpark proposer. | [ds4.c:34899](ds4.c#L34899); [ds4_cuda.cu:19040](ds4_cuda.cu#L19040) |
+| `DS4_CUDA_DSPARK_NO_PADDED_HEAD` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the padded CUDA output-head optimization used by DSpark. | [ds4.c:34247](ds4.c#L34247) |
+| `DS4_CUDA_DSPARK_NO_Q_NORM_ROPE_FUSION` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable fused Q RMSNorm plus RoPE in DSpark support stages. | [ds4.c:33623](ds4.c#L33623) |
+| `DS4_CUDA_DSPARK_PROPOSER_BLOCK_MAX` | integer 0..UINT32_MAX; 0/invalid keeps native size; unset uses auto caps for exact-N/exact2; positive values cap the block and are limited by DS4_DSPARK_MAX_BLOCK_SIZE | Cap the CUDA DSpark proposal block length. | [ds4.c:52354](ds4.c#L52354) |
+| `DS4_CUDA_DSPARK_TINY_ALIGNED_VEC` | value-aware flag, default off; unset/empty/exact 0 is off, any other nonempty value is on | Use aligned routed-MoE vector kernels for tiny DSpark batches. | [ds4_cuda.cu:29523](ds4_cuda.cu#L29523) |
+| `DS4_CUDA_ENABLE_DSPARK_NONCAUSAL_ONLINE` | value-aware flag, default off; unset/empty/exact 0 is off, any other nonempty value is on | Enable the small-batch noncausal online-attention DSpark experiment. | [ds4_cuda.cu:21690](ds4_cuda.cu#L21690) |
+| `DS4_CUDA_ENABLE_HC_NORM_MIX_FUSE` | nonempty opt-in, default off; only exact 0 disables; the F32/F16 activation mode follows the selected standalone matmul path; disable/serial/alternate flags can veto | Enable and select the fused HC RMSNorm-plus-mix one-token implementation. | [ds4_cuda.cu:20902](ds4_cuda.cu#L20902) |
+| `DS4_CUDA_ENABLE_IQ2_XXS_SSD_PREFILL_MMQ` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, any other nonempty value is on; disable flags dominate | Enable the CUDA IQ2 XXS SSD prefill MMQ experimental path. | [ds4_cuda.cu:4625](ds4_cuda.cu#L4625) |
+| `DS4_CUDA_ENABLE_Q4_ATTN_OUT_HC_FUSE` | value-aware flag, default off; unset/empty/exact 0 is off, any other nonempty value is on | Opt in to the fused Q4 attention-output/HC expansion path. | [ds4_cuda.cu:37375](ds4_cuda.cu#L37375) |
+| `DS4_CUDA_ENABLE_Q4_GROUPED_ATTN_A_BATCH` | value-aware opt-in, default off; nonempty value other than exact 0 enables; rollback wins | Enable flattened grouped attention-A MMQ for two-to-eight-token GB10 batches. | [cuda/mmq/ds4_mmq.cu:4303](cuda/mmq/ds4_mmq.cu#L4303) |
+| `DS4_CUDA_ENABLE_Q4_GROUPED_ATTN_A_PREFILL` | value-aware compatibility switch, default on; unset/empty uses the default, exact 0 opts out, any other nonempty value requests the path; REQUIRE also requests it; local/global rollback wins | Control direct-strided grouped Q4_K attention-A MMQ for GB10 prefill widths above eight tokens, removing per-group pack/unpack copies while preserving the per-group reduction tree. | [ds4_cuda.cu:41928](ds4_cuda.cu#L41928) |
+| `DS4_CUDA_ENABLE_Q4_K1024_PERSISTENT` | presence flag, default off; any defined value including 0 requests the path; rollback wins | Enable the GB10 persistent-CTA kernel for M=32768, N=1, K=1024 Q4. | [cuda/mmq/ds4_mmq.cu:3905](cuda/mmq/ds4_mmq.cu#L3905) |
+| `DS4_CUDA_ENABLE_Q8_FOLD` | strict flag, default off; only exact value 1 enables; overridden by DS4_CUDA_NO_Q8_FOLD | Enable one-shot producer-to-consumer reuse of freshly quantized Q8_1 data. | [ds4_cuda.cu:785](ds4_cuda.cu#L785) |
+| `DS4_CUDA_ENABLE_STREAMING_EXPERT_PERSISTENT_CACHE` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, any other nonempty value is on; disable flags dominate | Enable streaming expert persistent cache in CUDA SSD streaming. | [ds4_cuda.cu:4111](ds4_cuda.cu#L4111) |
+| `DS4_CUDA_ENABLE_STREAMING_SELECTED_BATCH_IO` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, any other nonempty value is on; disable flags dominate | Enable streaming selected batch I/O in CUDA SSD streaming. | [ds4_cuda.cu:4732](ds4_cuda.cu#L4732) |
+| `DS4_CUDA_ENABLE_STREAMING_SELECTED_EVENT_PIPELINE` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, any other nonempty value is on; disable flags dominate | Enable streaming selected event pipeline in CUDA SSD streaming. | [ds4_cuda.cu:4864](ds4_cuda.cu#L4864) |
+| `DS4_CUDA_END_STREAM_SYNC` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Synchronize only CUDA stream 0 at command-batch end instead of synchronizing the whole device. | [ds4_cuda.cu:376](ds4_cuda.cu#L376) |
+| `DS4_CUDA_EXACT_SCORE_SPLIT_CHUNK` | integer scores/chunk; default 512; clamped 1..8192 | Tune exact score split chunk for exact score-split CUDA decode attention. | [ds4_cuda.cu:13669](ds4_cuda.cu#L13669) |
+| `DS4_CUDA_EXACT_SCORE_SPLIT_DECODE` | value-aware boolean, default on; exact 0 disables; a nonzero explicit setting also takes precedence over split-KV selection | Control the exact score-split decode-attention implementation. | [ds4_cuda.cu:13631](ds4_cuda.cu#L13631) |
+| `DS4_CUDA_EXACT_SCORE_SPLIT_DIM2` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Tune exact score split dim2 for exact score-split CUDA decode attention. | [ds4_cuda.cu:387](ds4_cuda.cu#L387) |
+| `DS4_CUDA_EXACT_SCORE_SPLIT_FUSE_INV_ROPE` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Tune exact score split fuse inv rope for exact score-split CUDA decode attention. | [ds4_cuda.cu:390](ds4_cuda.cu#L390) |
+| `DS4_CUDA_EXACT_SCORE_SPLIT_GRAPH` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Tune exact score split graph for exact score-split CUDA decode attention. | [ds4_cuda.cu:379](ds4_cuda.cu#L379) |
+| `DS4_CUDA_EXACT_SCORE_SPLIT_LDG` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Tune exact score split ldg for exact score-split CUDA decode attention. | [ds4_cuda.cu:381](ds4_cuda.cu#L381) |
+| `DS4_CUDA_EXACT_SCORE_SPLIT_MIN_SCORE` | integer score count; default 1; clamped 0..8192 | Set the minimum visible-score count for exact score-split decode. | [ds4_cuda.cu:13665](ds4_cuda.cu#L13665) |
+| `DS4_CUDA_EXACT_SCORE_SPLIT_S` | integer exact split count; unset/invalid = automatic; valid value clamped 1..16 | Tune exact score split s for exact score-split CUDA decode attention. | [ds4_cuda.cu:13679](ds4_cuda.cu#L13679) |
+| `DS4_CUDA_EXACT_SCORE_SPLIT_S_FLOOR` | integer split count; default 6; clamped 1..16 | Tune exact score split s floor for exact score-split CUDA decode attention. | [ds4_cuda.cu:13672](ds4_cuda.cu#L13672) |
+| `DS4_CUDA_EXACT_SCORE_SPLIT_S_MAX` | integer split count; default 16; clamped 1..16 | Tune exact score split s max for exact score-split CUDA decode attention. | [ds4_cuda.cu:13675](ds4_cuda.cu#L13675) |
+| `DS4_CUDA_EXACT_SCORE_SPLIT_VEC4` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Tune exact score split vec4 for exact score-split CUDA decode attention. | [ds4_cuda.cu:383](ds4_cuda.cu#L383) |
+| `DS4_CUDA_EXACT_SCORE_SPLIT_VEC4_PLAIN` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Tune exact score split vec4 plain for exact score-split CUDA decode attention. | [ds4_cuda.cu:385](ds4_cuda.cu#L385) |
+| `DS4_CUDA_F16_CUBLAS_ONE` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Control the F16 cuBLAS one CUDA F16 matmul path. | [ds4_cuda.cu:20852](ds4_cuda.cu#L20852) |
+| `DS4_CUDA_F16_SMALL_BATCH` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Control the F16 small batch CUDA F16 matmul path. | [ds4_cuda.cu:20837](ds4_cuda.cu#L20837) |
+| `DS4_CUDA_F16_SMALL_OUT` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Control the F16 small out CUDA F16 matmul path. | [ds4_cuda.cu:20819](ds4_cuda.cu#L20819) |
+| `DS4_CUDA_GLM_VERIFY_NO_Q8_TOK2` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Control or tune the CUDA glm verify no Q8 tok2 path. | [ds4_cuda.cu:19824](ds4_cuda.cu#L19824) |
+| `DS4_CUDA_GREEDY_SPLITKV` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Enable greedy split-KV fast attention. | [ds4.c:17235](ds4.c#L17235) |
+| `DS4_CUDA_GREEDY_SPLITKV_FALLBACK_LOG` | presence diagnostic flag; default off; any defined value including 0 enables | Control greedy splitkv fallback log in CUDA greedy fast decode. | [ds4.c:55663](ds4.c#L55663) |
+| `DS4_CUDA_GREEDY_SPLITKV_MARGIN` | nonnegative finite float; default 0.25; invalid value warns and uses 0.25; 0 disables margin fallback | Control greedy splitkv margin in CUDA greedy fast decode. | [ds4.c:17313](ds4.c#L17313) |
+| `DS4_CUDA_GREEDY_SPLITKV_MAX_SEGMENT` | integer 0..INT32_MAX; default/invalid 0 (segment cap disabled) | Control greedy splitkv max segment in CUDA greedy fast decode. | [ds4.c:17389](ds4.c#L17389) |
+| `DS4_CUDA_GREEDY_SPLITKV_PAIR_REPLAY` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Replay greedy split-KV tokens in pairs. | [ds4.c:17363](ds4.c#L17363) |
+| `DS4_CUDA_GREEDY_SPLITKV_TOP2` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Use top-2 output margins with greedy split-KV. | [ds4.c:17345](ds4.c#L17345) |
+| `DS4_CUDA_GREEDY_SPLITKV_TRACE` | presence diagnostic flag; default off; any defined value including 0 enables | Control greedy splitkv trace in CUDA greedy fast decode. | [ds4.c:55698](ds4.c#L55698) |
+| `DS4_CUDA_GREEDY_SPLITKV_TRUST_REPLAY` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Trust replayed greedy split-KV results without the normal confirmation policy. | [ds4.c:17353](ds4.c#L17353) |
+| `DS4_CUDA_GREEDY_SPLIT_TOP1` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Enable split top-1 selection in greedy CUDA decode. | [ds4.c:17207](ds4.c#L17207) |
+| `DS4_CUDA_GREEDY_TOP1` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control greedy top1 in CUDA greedy fast decode. | [ds4.c:56126](ds4.c#L56126) |
+| `DS4_CUDA_GREEDY_VEC4` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Enable greedy vec4 fast attention. | [ds4.c:17245](ds4.c#L17245) |
+| `DS4_CUDA_GREEDY_VEC4_FALLBACK_LOG` | presence diagnostic flag; default off; any defined value including 0 enables | Control greedy vec4 fallback log in CUDA greedy fast decode. | [ds4.c:55664](ds4.c#L55664) |
+| `DS4_CUDA_GREEDY_VEC4_MARGIN` | nonnegative finite float; default 0.25; invalid value warns and uses 0.25; 0 disables margin fallback | Control greedy vec4 margin in CUDA greedy fast decode. | [ds4.c:17283](ds4.c#L17283) |
+| `DS4_CUDA_GREEDY_VEC4_MAX_SEGMENT` | integer 0..INT32_MAX; default/invalid 0 (segment cap disabled) | Control greedy vec4 max segment in CUDA greedy fast decode. | [ds4.c:17397](ds4.c#L17397) |
+| `DS4_CUDA_GREEDY_VEC4_TRACE` | presence diagnostic flag; default off; any defined value including 0 enables | Control greedy vec4 trace in CUDA greedy fast decode. | [ds4.c:55727](ds4.c#L55727) |
+| `DS4_CUDA_INDEXED_TWOPASS` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Force the two-pass indexed-attention path instead of the fused heads8 online kernel. | [ds4_cuda.cu:23587](ds4_cuda.cu#L23587) |
+| `DS4_CUDA_IQ2_XXS_SSD_PREFILL_MMQ_STATS` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, any other nonempty value is on; disable flags dominate | Print CUDA IQ2 XXS SSD prefill MMQ counters. | [ds4_cuda.cu:4633](ds4_cuda.cu#L4633) |
+| `DS4_CUDA_KEEP_MODEL_PAGES` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Keep source model pages resident instead of advising the OS to discard copied pages. | [ds4_cuda.cu:2840](ds4_cuda.cu#L2840) |
+| `DS4_CUDA_MIXED_PREFILL_DECODE` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control native mixed prefill/decode scheduling. | [ds4.c:70701](ds4.c#L70701) |
+| `DS4_CUDA_MIXED_ROUTED_MAX_PREFILL` | integer rows 0..UINT32_MAX; default/invalid 512 | Set the maximum prefill rows admitted to the mixed routed-MoE path. | [ds4.c:70190](ds4.c#L70190) |
+| `DS4_CUDA_MIXED_ROUTED_SCATTER` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Use scattered row handling in mixed routed-MoE execution. | [ds4.c:69651](ds4.c#L69651) |
+| `DS4_CUDA_MMQ` | boolean-ish, default on; any value beginning with 0 disables; quality mode and multi-GPU disable normal MMQ tier (MXFP4 path differs) | Control the vendored CUDA MMQ prefill tier. | [ds4_cuda.cu:1722](ds4_cuda.cu#L1722) |
+| `DS4_CUDA_MMQ_Q81_PERSISTENT` | strict boolean, default off; accepts 1/on/true/yes and 0/off/false/no in listed lower/upper-case forms; unknown values are off | Reuse a persistent Q8_1 MMQ scratch arena on supported GB10 devices. | [cuda/mmq/ds4_mmq.cu:152](cuda/mmq/ds4_mmq.cu#L152) |
+| `DS4_CUDA_MMQ_X_MAX` | integer >=8; rounded down to multiple of 8 and only lowers the hardware base; invalid/unset = hardware base | Cap the MMQ X tile-width selector for architecture tuning. | [cuda/mmq/mmq.cuh:127](cuda/mmq/mmq.cuh#L127) |
+| `DS4_CUDA_MODEL_COPY_CHUNK_MB` | positive integer MiB; default 64; clamped 16..4096 | Set the chunk size used for CUDA model copying. | [ds4_cuda.cu:2827](ds4_cuda.cu#L2827) |
+| `DS4_CUDA_MODEL_COPY_VERBOSE` | presence diagnostic flag; default off; any defined value including 0 enables | Print periodic progress while copying the model to device memory. | [ds4_cuda.cu:6537](ds4_cuda.cu#L6537) |
+| `DS4_CUDA_MODEL_PREFETCH_SYNC` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Synchronize after each CUDA model prefetch range for diagnostics. | [ds4_cuda.cu:2808](ds4_cuda.cu#L2808) |
+| `DS4_CUDA_MOE_ATOMIC_DOWN` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Select or tune the atomic down variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30086](ds4_cuda.cu#L30086) |
+| `DS4_CUDA_MOE_DECODE_GRAPH` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Select or tune the decode graph variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:391](ds4_cuda.cu#L391) |
+| `DS4_CUDA_MOE_DIRECT_MIDQ` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Select or tune the direct midq variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30140](ds4_cuda.cu#L30140) |
+| `DS4_CUDA_MOE_DOWN_ROW1024` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Select or tune the down row1024 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30109](ds4_cuda.cu#L30109) |
+| `DS4_CUDA_MOE_DOWN_ROW128` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Select or tune the down row128 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30128](ds4_cuda.cu#L30128) |
+| `DS4_CUDA_MOE_DOWN_ROW2048` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Select or tune the down row2048 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30110](ds4_cuda.cu#L30110) |
+| `DS4_CUDA_MOE_DOWN_ROW256` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Select or tune the down row256 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30127](ds4_cuda.cu#L30127) |
+| `DS4_CUDA_MOE_DOWN_ROW512` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Select or tune the down row512 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30108](ds4_cuda.cu#L30108) |
+| `DS4_CUDA_MOE_DOWN_ROW64` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Select or tune the down row64 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30129](ds4_cuda.cu#L30129) |
+| `DS4_CUDA_MOE_GATE_ROW1024` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Select or tune the gate row1024 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30120](ds4_cuda.cu#L30120) |
+| `DS4_CUDA_MOE_GATE_ROW128` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Select or tune the gate row128 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30093](ds4_cuda.cu#L30093) |
+| `DS4_CUDA_MOE_GATE_ROW2048` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Select or tune the gate row2048 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30091](ds4_cuda.cu#L30091) |
+| `DS4_CUDA_MOE_GATE_ROW256` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Select or tune the gate row256 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30092](ds4_cuda.cu#L30092) |
+| `DS4_CUDA_MOE_MIDQ_SIDECAR` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Select or tune the midq sidecar variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30169](ds4_cuda.cu#L30169) |
+| `DS4_CUDA_MOE_NO_ATOMIC_DOWN` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the atomic down variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30087](ds4_cuda.cu#L30087) |
+| `DS4_CUDA_MOE_NO_DECODE_LUT_GATE` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the decode lut gate variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30117](ds4_cuda.cu#L30117) |
+| `DS4_CUDA_MOE_NO_DIRECT_DOWN_SUM6` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the direct down sum6 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30137](ds4_cuda.cu#L30137) |
+| `DS4_CUDA_MOE_NO_DIRECT_MIDQ` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the direct midq variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30141](ds4_cuda.cu#L30141) |
+| `DS4_CUDA_MOE_NO_DOWN_ROW128` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the down row128 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30133](ds4_cuda.cu#L30133) |
+| `DS4_CUDA_MOE_NO_DOWN_ROW2048` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the down row2048 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30131](ds4_cuda.cu#L30131) |
+| `DS4_CUDA_MOE_NO_DOWN_ROW256` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the down row256 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30132](ds4_cuda.cu#L30132) |
+| `DS4_CUDA_MOE_NO_DOWN_ROW64` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the down row64 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30134](ds4_cuda.cu#L30134) |
+| `DS4_CUDA_MOE_NO_DOWN_TILE16` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the down tile16 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30102](ds4_cuda.cu#L30102) |
+| `DS4_CUDA_MOE_NO_EXPERT_TILES` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the expert tiles variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30062](ds4_cuda.cu#L30062) |
+| `DS4_CUDA_MOE_NO_GATE_ROW128` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the gate row128 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30097](ds4_cuda.cu#L30097) |
+| `DS4_CUDA_MOE_NO_GATE_ROW2048` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the gate row2048 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30095](ds4_cuda.cu#L30095) |
+| `DS4_CUDA_MOE_NO_GATE_ROW256` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the gate row256 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30096](ds4_cuda.cu#L30096) |
+| `DS4_CUDA_MOE_NO_IQ2_ALIGNED` | value-aware kill switch, default off; nonempty value other than exact 0 disables aligned IQ2 path | Disable the IQ2 aligned variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:1011](ds4_cuda.cu#L1011) |
+| `DS4_CUDA_MOE_NO_MIDQ_SIDECAR` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the midq sidecar variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30170](ds4_cuda.cu#L30170) |
+| `DS4_CUDA_MOE_NO_OWNED_SPARSE_BUFFERS` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the owned sparse buffers variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30089](ds4_cuda.cu#L30089) |
+| `DS4_CUDA_MOE_NO_P2` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the p2 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30084](ds4_cuda.cu#L30084) |
+| `DS4_CUDA_MOE_NO_Q2K_ALIGNED` | value-aware kill switch, default off; nonempty value other than exact 0 disables aligned Q2_K path | Disable the q2k aligned variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:1016](ds4_cuda.cu#L1016) |
+| `DS4_CUDA_MOE_NO_Q4_DOWN_ROWSPAN` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the Q4 down rowspan variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30114](ds4_cuda.cu#L30114) |
+| `DS4_CUDA_MOE_NO_Q4_DOWN_SLOT3` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the Q4 down slot3 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30164](ds4_cuda.cu#L30164) |
+| `DS4_CUDA_MOE_NO_Q4_GATE_H16` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the Q4 gate H16 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30149](ds4_cuda.cu#L30149) |
+| `DS4_CUDA_MOE_NO_Q4_GATE_H16R8` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the Q4 gate H16R8 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30145](ds4_cuda.cu#L30145) |
+| `DS4_CUDA_MOE_NO_Q4_GATE_W32` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the Q4 gate W32 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30157](ds4_cuda.cu#L30157) |
+| `DS4_CUDA_MOE_NO_Q4_GATE_W32R16` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the Q4 gate W32R16 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30153](ds4_cuda.cu#L30153) |
+| `DS4_CUDA_MOE_NO_Q4_GATE_W32_NOAUX` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the Q4 gate W32 no-aux variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30160](ds4_cuda.cu#L30160) |
+| `DS4_CUDA_MOE_NO_Q4_MMA` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the Q4 MMA variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:312](ds4_cuda.cu#L312) |
+| `DS4_CUDA_MOE_NO_Q4_MMA_TILE16` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the Q4 MMA tile16 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30100](ds4_cuda.cu#L30100) |
+| `DS4_CUDA_MOE_NO_Q4_SORTED` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the Q4 sorted variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30061](ds4_cuda.cu#L30061) |
+| `DS4_CUDA_MOE_NO_SMALL_SORTED_PREP` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Disable the small sorted prep variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30106](ds4_cuda.cu#L30106) |
+| `DS4_CUDA_MOE_PROFILE` | presence diagnostic flag; default off; any defined value including 0 enables | Measure and print routed-MoE CUDA kernel-stage timings. | [ds4_cuda.cu:30045](ds4_cuda.cu#L30045) |
+| `DS4_CUDA_MOE_Q4_DOWN_SLOT3` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Select or tune the Q4 down slot3 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30163](ds4_cuda.cu#L30163) |
+| `DS4_CUDA_MOE_Q4_GATE_H16` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Select or tune the Q4 gate H16 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30148](ds4_cuda.cu#L30148) |
+| `DS4_CUDA_MOE_Q4_GATE_H16R8` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Select or tune the Q4 gate H16R8 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30144](ds4_cuda.cu#L30144) |
+| `DS4_CUDA_MOE_Q4_GATE_W32R16` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Select or tune the Q4 gate W32R16 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30152](ds4_cuda.cu#L30152) |
+| `DS4_CUDA_MOE_TILE4` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Select or tune the tile4 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30063](ds4_cuda.cu#L30063) |
+| `DS4_CUDA_MOE_TILE8` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Select or tune the tile8 variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30079](ds4_cuda.cu#L30079) |
+| `DS4_CUDA_MOE_WRITE_GATE_UP` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Select or tune the write gate up variant in CUDA routed-MoE dispatch. | [ds4_cuda.cu:30081](ds4_cuda.cu#L30081) |
+| `DS4_CUDA_NO_ATTENTION_OUTPUT_F16_CACHE` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the attention output F16 cache CUDA F16 path. | [ds4_cuda.cu:2364](ds4_cuda.cu#L2364) |
+| `DS4_CUDA_NO_ATTN_A_TOK2` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the CUDA attn a tok2 optimization/path. | [ds4_cuda.cu:24024](ds4_cuda.cu#L24024) |
+| `DS4_CUDA_NO_ATTN_Q_B_F16_CACHE` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the attn q b F16 cache CUDA F16 path. | [ds4_cuda.cu:2367](ds4_cuda.cu#L2367) |
+| `DS4_CUDA_NO_COMPRESSOR_PREFILL_BATCH` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the CUDA compressor prefill batch optimization/path. | [ds4.c:29890](ds4.c#L29890) |
+| `DS4_CUDA_NO_CUBLAS_ATTENTION` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the CUDA cuBLAS attention optimization/path. | [ds4_cuda.cu:23067](ds4_cuda.cu#L23067) |
+| `DS4_CUDA_NO_CUBLAS_ATTENTION_OUTPUT_A` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the CUDA cuBLAS attention output a optimization/path. | [ds4_cuda.cu:23934](ds4_cuda.cu#L23934) |
+| `DS4_CUDA_NO_DECODE_VALUE512` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the 512-thread CUDA decode value/finalize specialization. | [ds4_cuda.cu:374](ds4_cuda.cu#L374) |
+| `DS4_CUDA_NO_DERIVED_WEIGHTS` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the CUDA derived weights optimization/path. | [ds4_cuda.cu:1034](ds4_cuda.cu#L1034) |
+| `DS4_CUDA_NO_DIRECT_IO` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the CUDA direct I/O optimization/path. | [cuda/mmq/ds4_repack.cu:68](cuda/mmq/ds4_repack.cu#L68) |
+| `DS4_CUDA_NO_DIRECT_Q2_PREFILL` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the CUDA direct q2 prefill optimization/path. | [ds4_cuda.cu:395](ds4_cuda.cu#L395) |
+| `DS4_CUDA_NO_EXACT_SCORE_SPLIT_DECODE` | value-aware kill switch, default off; exact 0 is off, other nonempty values disable | Disable exact score split decode for exact score-split CUDA decode attention. | [ds4_cuda.cu:13629](ds4_cuda.cu#L13629); [ds4.c:68110](ds4.c#L68110) |
+| `DS4_CUDA_NO_EXACT_SCORE_SPLIT_DIM2` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable exact score split dim2 for exact score-split CUDA decode attention. | [ds4_cuda.cu:388](ds4_cuda.cu#L388) |
+| `DS4_CUDA_NO_F16_CUBLAS_BATCH` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the F16 cuBLAS batch CUDA F16 path. | [ds4_cuda.cu:20854](ds4_cuda.cu#L20854) |
+| `DS4_CUDA_NO_F16_CUBLAS_ONE` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the F16 cuBLAS one CUDA F16 path. | [ds4_cuda.cu:20851](ds4_cuda.cu#L20851) |
+| `DS4_CUDA_NO_F16_PAIR_COMPRESSOR_STORE` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the F16 pair compressor store CUDA F16 path. | [ds4_cuda.cu:399](ds4_cuda.cu#L399) |
+| `DS4_CUDA_NO_F16_PAIR_COMPRESSOR_TRANSPOSE` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the F16 pair compressor transpose CUDA F16 path. | [ds4_cuda.cu:21343](ds4_cuda.cu#L21343) |
+| `DS4_CUDA_NO_F16_PAIR_COMPRESSOR_TRANSPOSE_PREFETCH8` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the F16 pair compressor transpose prefetch8 CUDA F16 path. | [ds4_cuda.cu:21349](ds4_cuda.cu#L21349) |
+| `DS4_CUDA_NO_F16_PAIR_MATMUL` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the F16 pair matmul CUDA F16 path. | [ds4_cuda.cu:21130](ds4_cuda.cu#L21130) |
+| `DS4_CUDA_NO_F16_SMALL_BATCH` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the F16 small batch CUDA F16 path. | [ds4_cuda.cu:20838](ds4_cuda.cu#L20838) |
+| `DS4_CUDA_NO_F16_SMALL_OUT` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the F16 small out CUDA F16 path. | [ds4_cuda.cu:20821](ds4_cuda.cu#L20821) |
+| `DS4_CUDA_NO_FD_CACHE` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the CUDA fd cache optimization/path. | [ds4_cuda.cu:1274](ds4_cuda.cu#L1274) |
+| `DS4_CUDA_NO_GREEDY_SPLITKV` | value-aware kill switch; default off; nonempty value other than exact 0 disables | Disable greedy splitkv in CUDA greedy fast decode. | [ds4.c:17233](ds4.c#L17233) |
+| `DS4_CUDA_NO_GREEDY_SPLITKV_FALLBACK` | value-aware kill switch; default off; nonempty value other than exact 0 disables margin fallback | Disable greedy splitkv fallback in CUDA greedy fast decode. | [ds4.c:17333](ds4.c#L17333) |
+| `DS4_CUDA_NO_GREEDY_SPLITKV_PAIR_REPLAY` | value-aware kill switch; default off; nonempty value other than exact 0 disables | Disable greedy splitkv pair replay in CUDA greedy fast decode. | [ds4.c:17361](ds4.c#L17361) |
+| `DS4_CUDA_NO_GREEDY_SPLITKV_TOP2` | value-aware kill switch; default off; nonempty value other than exact 0 disables | Disable greedy splitkv top2 in CUDA greedy fast decode. | [ds4.c:17343](ds4.c#L17343) |
+| `DS4_CUDA_NO_GREEDY_SPLIT_TOP1` | value-aware kill switch; default off; nonempty value other than exact 0 disables | Disable greedy split top1 in CUDA greedy fast decode. | [ds4.c:17205](ds4.c#L17205) |
+| `DS4_CUDA_NO_GREEDY_VEC4` | value-aware kill switch; default off; nonempty value other than exact 0 disables | Disable greedy vec4 in CUDA greedy fast decode. | [ds4.c:17243](ds4.c#L17243) |
+| `DS4_CUDA_NO_GREEDY_VEC4_FALLBACK` | value-aware kill switch; default off; nonempty value other than exact 0 disables margin fallback | Disable greedy vec4 fallback in CUDA greedy fast decode. | [ds4.c:17303](ds4.c#L17303) |
+| `DS4_CUDA_NO_HC_SPLIT_NORM_SPLIT4096` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the split partial-reduction specialization for one-row, 4096-wide HC normalization. | [ds4_cuda.cu:31826](ds4_cuda.cu#L31826) |
+| `DS4_CUDA_NO_INDEXED_HEADS8` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the CUDA indexed heads8 optimization/path. | [ds4_cuda.cu:23586](ds4_cuda.cu#L23586) |
+| `DS4_CUDA_NO_INDEXED_TOPK_SORT` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the CUDA indexed topk sort optimization/path. | [ds4_cuda.cu:23577](ds4_cuda.cu#L23577) |
+| `DS4_CUDA_NO_INDEXER_DIRECT_ONE` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the indexer direct one CUDA indexer kernel/path. | [ds4_cuda.cu:18881](ds4_cuda.cu#L18881) |
+| `DS4_CUDA_NO_INDEXER_MXF4` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the indexer MXF4 CUDA indexer kernel/path. | [ds4_cuda.cu:17774](ds4_cuda.cu#L17774) |
+| `DS4_CUDA_NO_INDEXER_WMMA` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the indexer WMMA CUDA indexer kernel/path. | [ds4_cuda.cu:18891](ds4_cuda.cu#L18891) |
+| `DS4_CUDA_NO_INDEXER_WMMA128` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the indexer wmma128 CUDA indexer kernel/path. | [ds4_cuda.cu:18892](ds4_cuda.cu#L18892) |
+| `DS4_CUDA_NO_INDEXER_WMMA32` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the indexer wmma32 CUDA indexer kernel/path. | [ds4_cuda.cu:18910](ds4_cuda.cu#L18910) |
+| `DS4_CUDA_NO_INDEXER_WMMA64` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the indexer wmma64 CUDA indexer kernel/path. | [ds4_cuda.cu:18901](ds4_cuda.cu#L18901) |
+| `DS4_CUDA_NO_IQ2_XXS_SSD_PREFILL_MMQ` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, any other nonempty value is on; disable flags dominate | Disable the CUDA IQ2 XXS SSD prefill MMQ optimization/path. | [ds4_cuda.cu:4629](ds4_cuda.cu#L4629) |
+| `DS4_CUDA_NO_MODEL_COPY` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the CUDA model copy optimization/path. | [ds4_cuda.cu:6472](ds4_cuda.cu#L6472) |
+| `DS4_CUDA_NO_MODEL_PREFETCH` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the CUDA model prefetch optimization/path. | [ds4_cuda.cu:2739](ds4_cuda.cu#L2739) |
+| `DS4_CUDA_NO_MOE_DEDUP` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the CUDA MoE dedup optimization/path. | [cuda/mmq/ds4_mmq.cu:6172](cuda/mmq/ds4_mmq.cu#L6172) |
+| `DS4_CUDA_NO_ORDERED_F16_MATMUL` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the ordered F16 matmul CUDA F16 path. | [ds4_cuda.cu:20811](ds4_cuda.cu#L20811) |
+| `DS4_CUDA_NO_PARALLEL_ROUTER_SELECT` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the CUDA parallel router select optimization/path. | [ds4_cuda.cu:24491](ds4_cuda.cu#L24491) |
+| `DS4_CUDA_NO_Q4_DENSE_SCRATCH` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the Q4 dense scratch CUDA Q4 optimization. | [cuda/mmq/ds4_mmq.cu:3986](cuda/mmq/ds4_mmq.cu#L3986) |
+| `DS4_CUDA_NO_Q4_GB10_FAST` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the GB10-specific Q4 fast-path family. | [cuda/mmq/ds4_mmq.cu:3908](cuda/mmq/ds4_mmq.cu#L3908) |
+| `DS4_CUDA_NO_Q4_GROUPED_ATTN_A` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the Q4 grouped attn a CUDA Q4 optimization. | [cuda/mmq/ds4_mmq.cu:4295](cuda/mmq/ds4_mmq.cu#L4295) |
+| `DS4_CUDA_NO_Q4_GROUPED_ATTN_A_BATCH` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the Q4 grouped attn a batch CUDA Q4 optimization. | [cuda/mmq/ds4_mmq.cu:4305](cuda/mmq/ds4_mmq.cu#L4305) |
+| `DS4_CUDA_NO_Q4_GROUPED_ATTN_A_PREFILL` | presence kill switch for the default-on GB10 path; default unset; any defined value including empty or 0 disables and dominates ENABLE/REQUIRE | Restore the eight pack/MMQ/unpack Q4 attention-A prefill projections. | [ds4_cuda.cu:41930](ds4_cuda.cu#L41930) |
+| `DS4_CUDA_NO_Q4_GROUPED_ATTN_A_Q81` | presence rollback for the default-on fixed-shape quantizer; default unset; any defined value including empty or 0 disables; REQUIRE then fails closed | Restore the canonical strided Q8_1 producer while retaining grouped Q4 attention-A prefill and its eight MMQ grids. | [cuda/mmq/ds4_mmq.cu:1762](cuda/mmq/ds4_mmq.cu#L1762); [ds4_cuda.cu:44143](ds4_cuda.cu#L44143) |
+| `DS4_CUDA_NO_Q4_K1024_PERSISTENT` | presence kill switch, default off; any defined value including 0 disables | Disable the Q4 K1024 persistent CUDA Q4 optimization. | [cuda/mmq/ds4_mmq.cu:3907](cuda/mmq/ds4_mmq.cu#L3907) |
+| `DS4_CUDA_NO_Q4_MMQ_16WARP` | value-aware rollback, default off; unset/empty/exact 0 permits the experiment, every other nonempty value disables it and overrides REQUEST/REQUIRE | Disable the experimental Stream-K-compatible CUDA Q4_K m128n128 16-warp prefill kernel. | [cuda/mmq/ds4_mmq.cu:1133](cuda/mmq/ds4_mmq.cu#L1133) |
+| `DS4_CUDA_NO_Q8_ALIGNED_DENSE_SCRATCH` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the Q8 aligned dense scratch CUDA Q8 optimization. | [cuda/mmq/ds4_mmq.cu:5578](cuda/mmq/ds4_mmq.cu#L5578) |
+| `DS4_CUDA_NO_Q8_ALIGNED_PERSISTENT` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the Q8 aligned persistent CUDA Q8 optimization. | [cuda/mmq/ds4_mmq.cu:5410](cuda/mmq/ds4_mmq.cu#L5410) |
+| `DS4_CUDA_NO_Q8_BATCH_EXACT_TOK2` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the Q8 batch exact tok2 CUDA Q8 optimization. | [ds4_cuda.cu:19852](ds4_cuda.cu#L19852) |
+| `DS4_CUDA_NO_Q8_BATCH_TOK4` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the Q8 batch tok4 CUDA Q8 optimization. | [ds4_cuda.cu:19805](ds4_cuda.cu#L19805) |
+| `DS4_CUDA_NO_Q8_BATCH_TOK8` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the Q8 batch tok8 CUDA Q8 optimization. | [ds4_cuda.cu:19788](ds4_cuda.cu#L19788) |
+| `DS4_CUDA_NO_Q8_BATCH_WARP` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the Q8 batch warp CUDA Q8 optimization. | [ds4_cuda.cu:19787](ds4_cuda.cu#L19787) |
+| `DS4_CUDA_NO_Q8_DP4A` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the Q8 DP4A CUDA Q8 optimization. | [ds4_cuda.cu:2391](ds4_cuda.cu#L2391) |
+| `DS4_CUDA_NO_Q8_F16_CACHE` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the Q8 F16 cache CUDA Q8 optimization. | [ds4_cuda.cu:2356](ds4_cuda.cu#L2356) |
+| `DS4_CUDA_NO_Q8_F32_CACHE` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the Q8 F32 cache CUDA Q8 optimization. | [ds4_cuda.cu:2411](ds4_cuda.cu#L2411) |
+| `DS4_CUDA_NO_Q8_FOLD` | value-aware kill switch, default off; nonempty value other than exact 0 disables and wins over enable | Disable the Q8_1 producer-to-consumer fold. | [ds4_cuda.cu:786](ds4_cuda.cu#L786) |
+| `DS4_CUDA_NO_Q8_FUSED_ALIGNED` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the Q8 fused aligned CUDA Q8 optimization. | [ds4_cuda.cu:20141](ds4_cuda.cu#L20141) |
+| `DS4_CUDA_NO_Q8_MMA` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the Q8 MMA CUDA Q8 optimization. | [ds4_cuda.cu:10781](ds4_cuda.cu#L10781) |
+| `DS4_CUDA_NO_Q8_PAIR_BATCH_EXACT` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the Q8 pair batch exact CUDA Q8 optimization. | [ds4_cuda.cu:20302](ds4_cuda.cu#L20302) |
+| `DS4_CUDA_NO_Q8_PAIR_BATCH_EXACT_TOK2` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the Q8 pair batch exact tok2 CUDA Q8 optimization. | [ds4_cuda.cu:20305](ds4_cuda.cu#L20305) |
+| `DS4_CUDA_NO_QKV_KV_ROPE_FUSE` | value-aware kill switch; default off; nonempty value other than exact 0 disables | Disable the CUDA QKV KV rope fuse optimization/path. | [ds4.c:17426](ds4.c#L17426) |
+| `DS4_CUDA_NO_QKV_PAIR` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the CUDA QKV pair optimization/path. | [ds4.c:17562](ds4.c#L17562) |
+| `DS4_CUDA_NO_SCORE_TILE` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the CUDA score tile optimization/path. | [ds4_cuda.cu:13734](ds4_cuda.cu#L13734); [ds4.c:68122](ds4.c#L68122) |
+| `DS4_CUDA_NO_SETDEVICE_CACHE` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the cached current-tier shortcut and call cudaSetDevice for every tier selection. | [ds4_cuda.cu:377](ds4_cuda.cu#L377) |
+| `DS4_CUDA_NO_SPLITKV_DECODE` | value-aware kill switch, default off; exact 0/empty is off, other nonempty values disable | Disable splitkv decode in CUDA split-KV attention/speculation. | [ds4_cuda.cu:2211](ds4_cuda.cu#L2211) |
+| `DS4_CUDA_NO_SPLITKV_SPEC` | value-aware kill switch; default off; nonempty value other than exact 0 disables | Disable splitkv spec in CUDA split-KV attention/speculation. | [ds4.c:17253](ds4.c#L17253) |
+| `DS4_CUDA_NO_SPLITKV_SPEC_BATCH_VERIFY` | value-aware kill switch; default off; nonempty value other than exact 0 disables | Disable splitkv spec batch verify in CUDA split-KV attention/speculation. | [ds4.c:17273](ds4.c#L17273) |
+| `DS4_CUDA_NO_SPLITKV_SPEC_TOPONLY_ROW0` | value-aware kill switch; default off; nonempty value other than exact 0 disables | Disable splitkv spec toponly row0 in CUDA split-KV attention/speculation. | [ds4.c:17263](ds4.c#L17263) |
+| `DS4_CUDA_NO_STREAMING_EXPERT_PERSISTENT_CACHE` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, any other nonempty value is on; disable flags dominate | Disable streaming expert persistent cache in CUDA SSD streaming. | [ds4_cuda.cu:4115](ds4_cuda.cu#L4115) |
+| `DS4_CUDA_NO_STREAMING_SELECTED_BATCH_IO` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, any other nonempty value is on; disable flags dominate | Disable streaming selected batch I/O in CUDA SSD streaming. | [ds4_cuda.cu:4736](ds4_cuda.cu#L4736) |
+| `DS4_CUDA_NO_STREAMING_SELECTED_EVENT_PIPELINE` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, any other nonempty value is on; disable flags dominate | Disable streaming selected event pipeline in CUDA SSD streaming. | [ds4_cuda.cu:4868](ds4_cuda.cu#L4868) |
+| `DS4_CUDA_NO_TF32` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Use default cuBLAS math instead of TF32 tensor operations. | [ds4_cuda.cu:6657](ds4_cuda.cu#L6657) |
+| `DS4_CUDA_NO_TOP1` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the dedicated CUDA indexer top-1 kernel. | [ds4_cuda.cu:375](ds4_cuda.cu#L375) |
+| `DS4_CUDA_NO_TOPK1024` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the topk1024 CUDA indexer kernel/path. | [ds4_cuda.cu:19290](ds4_cuda.cu#L19290) |
+| `DS4_CUDA_NO_TOPK2048` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the topk2048 CUDA indexer kernel/path. | [ds4_cuda.cu:19297](ds4_cuda.cu#L19297) |
+| `DS4_CUDA_NO_TOPK2048_WIDE` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the topk2048 wide CUDA indexer kernel/path. | [ds4_cuda.cu:19212](ds4_cuda.cu#L19212) |
+| `DS4_CUDA_NO_TOPK8192` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the topk8192 CUDA indexer kernel/path. | [ds4_cuda.cu:19335](ds4_cuda.cu#L19335) |
+| `DS4_CUDA_NO_TOPK_CHUNKED` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the topk chunked CUDA indexer kernel/path. | [ds4_cuda.cu:19374](ds4_cuda.cu#L19374) |
+| `DS4_CUDA_NO_TOPK_STREAM` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the topk stream CUDA indexer kernel/path. | [ds4_cuda.cu:19366](ds4_cuda.cu#L19366) |
+| `DS4_CUDA_NO_TP_ATTN_OUT_HC_FUSE` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the CUDA TP attn out HC fuse optimization/path. | [ds4.c:17565](ds4.c#L17565) |
+| `DS4_CUDA_NO_VERIFY_DECODE2_SPLIT_TOP1` | value-aware kill switch; default off; nonempty value other than exact 0 disables | Disable the CUDA verify decode2 split top1 optimization/path. | [ds4.c:17223](ds4.c#L17223) |
+| `DS4_CUDA_NO_WARP_ROUTER_SELECT` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the CUDA warp router select optimization/path. | [ds4_cuda.cu:24490](ds4_cuda.cu#L24490) |
+| `DS4_CUDA_NO_WINDOW_ATTENTION` | presence kill switch; default unset (eligible path remains available); any defined value including 0 disables | Disable the CUDA window attention optimization/path. | [ds4_cuda.cu:23050](ds4_cuda.cu#L23050) |
+| `DS4_CUDA_NSYS_PREFILL_START_POS` | nonempty-string flag, default off; any nonempty value enables MMQ NVTX ranges (the value is not parsed as a position) | Enable MMQ NVTX annotations intended for Nsight Systems prefill capture. | [cuda/mmq/ds4_mmq.cu:49](cuda/mmq/ds4_mmq.cu#L49) |
+| `DS4_CUDA_NVTX` | strict flag, default off; only exact value 1 enables (a nonempty NSYS variable also enables ranges) | Enable NVTX ranges around MMQ work. | [cuda/mmq/ds4_mmq.cu:48](cuda/mmq/ds4_mmq.cu#L48) |
+| `DS4_CUDA_OUTPUT_FUSED_TOP1` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Fuse output projection with top-1 selection in greedy decode. | [ds4.c:17215](ds4.c#L17215) |
+| `DS4_CUDA_PREFILL_PIPELINE` | boolean, default follows CUDA TP decode; nonempty exact 0 disables, any other nonempty value enables | Control the CUDA multi-tier prefill pipeline. | [ds4.c:17454](ds4.c#L17454) |
+| `DS4_CUDA_PREFILL_PIPELINE_MB` | positive integer rows; default/invalid 512 | Set prefill-pipeline microbatch rows. | [ds4.c:17469](ds4.c#L17469) |
+| `DS4_CUDA_PREFILL_PIPELINE_Q8_CACHE` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Keep selective Q8 caches enabled while running the prefill pipeline. | [ds4.c:17464](ds4.c#L17464) |
+| `DS4_CUDA_PREFILL_PIPELINE_SEQUENTIAL` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Execute prefill pipeline stages sequentially for diagnosis. | [ds4.c:35525](ds4.c#L35525) |
+| `DS4_CUDA_PREFILL_PIPELINE_SYNC_BOUNDARY` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Synchronize CUDA at every prefill pipeline tier boundary. | [ds4.c:35572](ds4.c#L35572) |
+| `DS4_CUDA_Q4_ATTN_OUT_HC_ORACLE` | value-aware flag, default off; unset/empty/exact 0 is off, any other nonempty value is on | Compare fused Q4 attention-output/HC expansion with the canonical path and retain canonical output. | [ds4_cuda.cu:1475](ds4_cuda.cu#L1475) |
+| `DS4_CUDA_Q4_ATTN_OUT_HC_Q8K_EXPERIMENT` | value-aware flag, default off; unset/empty/exact 0 is off, any other nonempty value is on | Enable the experimental Q8_K-based Q4 attention-output/HC fusion. | [ds4_cuda.cu:37377](ds4_cuda.cu#L37377) |
+| `DS4_CUDA_Q4_GROUPED_ATTN_A_ORACLE` | value-aware flag, default off; unset/empty/exact 0 is off, any other nonempty value is on | Compare grouped attention-A against the canonical per-group result. | [ds4_cuda.cu:1477](ds4_cuda.cu#L1477) |
+| `DS4_CUDA_Q4_K1024_PERSISTENT_ORACLE` | value-aware flag, default off; nonempty value other than exact 0 enables and implies candidate admission | Bitwise-compare the exact-shape persistent Q4 K1024 kernel with canonical MMVQ and retain canonical output. | [cuda/mmq/ds4_mmq.cu:3738](cuda/mmq/ds4_mmq.cu#L3738) |
+| `DS4_CUDA_Q4_K1024_PERSISTENT_STATS` | value-aware flag, default off; nonempty value other than exact 0 enables | Print exact-shape persistent Q4 K1024 dispatch counters at exit. | [cuda/mmq/ds4_mmq.cu:3737](cuda/mmq/ds4_mmq.cu#L3737) |
+| `DS4_CUDA_Q4_MMQ_16WARP` | value-aware opt-in cached on the first Q4_K dense or dense-pair MMQ call; unset/empty/exact 0 is off, every other nonempty value requests the candidate; rollback wins; standalone dense requires M>=1024 and admits K<=8192 including attention output-B, while dense-pair admits legs down to M=512, remains bounded to K<=4096, and shares one Q8_1 activation; grids require at least 80% whole-tile SM-wave efficiency and use the canonical Stream-K partition/fixup below its 90% cutoff; ineligible optional shapes fall back | Enable the experimental exact-integer CUDA Q4_K m128n128 16-warp kernel for eligible dense and dense-pair prefills without changing the canonical FP32 reduction tree. | [cuda/mmq/ds4_mmq.cu:1126](cuda/mmq/ds4_mmq.cu#L1126) |
+| `DS4_CUDA_Q8_F16_ALL` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Control the Q8 F16 all CUDA quantized-matmul/cache optimization. | [ds4_cuda.cu:2358](ds4_cuda.cu#L2358) |
+| `DS4_CUDA_Q8_F16_CACHE_MB` | unsigned integer MiB, full-string parse; default unlimited; 0 disables this cache | Limit the selective Q8-to-F16 derived-weight cache. | [ds4_cuda.cu:2218](ds4_cuda.cu#L2218) |
+| `DS4_CUDA_Q8_F16_CACHE_RESERVE_MB` | unsigned integer MiB, full-string parse; default is VRAM-dependent (>=112 GiB: 512; >=40 GiB: max(768,1%); smaller: max(4096,5%)) | Reserve free VRAM when growing the selective Q8-to-F16 cache. | [ds4_cuda.cu:2224](ds4_cuda.cu#L2224) |
+| `DS4_CUDA_Q8_F32_ALL` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Control the Q8 F32 all CUDA quantized-matmul/cache optimization. | [ds4_cuda.cu:2412](ds4_cuda.cu#L2412) |
+| `DS4_CUDA_Q8_F32_LARGE` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Control the Q8 F32 large CUDA quantized-matmul/cache optimization. | [ds4_cuda.cu:2416](ds4_cuda.cu#L2416) |
+| `DS4_CUDA_Q8_F32_PRELOAD` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Control the Q8 F32 preload CUDA quantized-matmul/cache optimization. | [ds4_cuda.cu:8597](ds4_cuda.cu#L8597) |
+| `DS4_CUDA_Q8_FOLD_ORACLE` | strict flag, default off; only exact value 1 enables | Compare folded Q8_1 bytes and consumer outputs against canonical work while retaining canonical results. | [cuda/mmq/ds4_mmq.cu:381](cuda/mmq/ds4_mmq.cu#L381) |
+| `DS4_CUDA_Q8_HC_EXPAND_FUSED` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, other nonempty values force fused | Force the fused Q8 shared-down/HC expansion path. | [ds4_cuda.cu:2084](ds4_cuda.cu#L2084) |
+| `DS4_CUDA_Q8_HC_EXPAND_STATS` | false-like-aware flag, default off; 0/false/no/off is off, other nonempty values print report | Print Q8 shared-down/HC policy and dispatch counters at exit. | [ds4_cuda.cu:2090](ds4_cuda.cu#L2090) |
+| `DS4_CUDA_Q8_NO_ALIGNED` | value-aware kill switch, default off; nonempty value other than exact 0 disables aligned Q8 kernels | Disable aligned Q8 CUDA matmul kernels. | [ds4_cuda.cu:1021](ds4_cuda.cu#L1021) |
+| `DS4_CUDA_Q8_PAIR_BATCH` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Control the Q8 pair batch CUDA quantized-matmul/cache optimization. | [ds4_cuda.cu:20167](ds4_cuda.cu#L20167) |
+| `DS4_CUDA_QKV_KV_ROPE_FUSE` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control or tune the CUDA QKV KV rope fuse path. | [ds4.c:17429](ds4.c#L17429) |
+| `DS4_CUDA_Q_NORM_ROPE_FUSE` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control or tune the CUDA q norm rope fuse path. | [ds4.c:17418](ds4.c#L17418) |
+| `DS4_CUDA_REQUIRE_IQ2_XXS_SSD_PREFILL_MMQ` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, any other nonempty value is on; disable flags dominate | Require the CUDA IQ2 XXS SSD prefill MMQ path; fail closed when unavailable. | [ds4_cuda.cu:4631](ds4_cuda.cu#L4631) |
+| `DS4_CUDA_REQUIRE_Q4_GROUPED_ATTN_A_BATCH` | value-aware flag, default off; unset/empty/exact 0 is off, any other nonempty value is on | Fail if grouped batched attention-A cannot be used. | [ds4_cuda.cu:40198](ds4_cuda.cu#L40198) |
+| `DS4_CUDA_REQUIRE_Q4_GROUPED_ATTN_A_PREFILL` | value-aware fail-closed assertion, default off; unset/empty/exact 0 is off, any other nonempty value requests the candidate and rejects ineligibility before enqueue | Require the GB10 grouped Q4_K attention-A prefill path instead of silently using pack/MMQ/unpack. | [ds4_cuda.cu:41889](ds4_cuda.cu#L41889) |
+| `DS4_CUDA_REQUIRE_Q4_GROUPED_ATTN_A_Q81` | value-aware fail-closed assertion, default off; unset/empty/exact 0 is off, any other nonempty value requests grouped prefill and the fixed K=4096, groups=8, rank=1024 Q8_1 producer; NO wins | Require the eight-warp K4096/G8x2 Q8_1 producer instead of silently using the generic strided quantizer. | [cuda/mmq/ds4_mmq.cu:1767](cuda/mmq/ds4_mmq.cu#L1767); [ds4_cuda.cu:44089](ds4_cuda.cu#L44089) |
+| `DS4_CUDA_REQUIRE_Q4_K1024_PERSISTENT` | presence flag, default off; any defined value including 0 makes ineligible candidate fail closed | Fail when the exact Q4 K1024 persistent candidate is unavailable instead of using MMVQ. | [cuda/mmq/ds4_mmq.cu:3929](cuda/mmq/ds4_mmq.cu#L3929) |
+| `DS4_CUDA_REQUIRE_Q4_MMQ_16WARP` | value-aware fail-closed prefill opt-in cached on the first Q4_K dense or dense-pair MMQ call; unset/empty/exact 0 is off, every other nonempty value requests and requires the candidate for N>8; a dense-pair is rejected before allocation unless both legs are eligible; rollback, disabled MMQ, ineligibility, or preflight failure prevents fallback; decode/speculative N<=8 remains on MMVQ | Require the experimental CUDA Q4_K 16-warp prefill kernel so benchmark runs cannot silently measure another path. | [cuda/mmq/ds4_mmq.cu:1130](cuda/mmq/ds4_mmq.cu#L1130); [ds4_cuda.cu:38208](ds4_cuda.cu#L38208); [ds4_cuda.cu:38358](ds4_cuda.cu#L38358) |
+| `DS4_CUDA_REQUIRE_STREAMING_EXPERT_PERSISTENT_CACHE` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, any other nonempty value is on; disable flags dominate | Require streaming expert persistent cache in CUDA SSD streaming; fail closed when unavailable. | [ds4_cuda.cu:4117](ds4_cuda.cu#L4117) |
+| `DS4_CUDA_REQUIRE_STREAMING_SELECTED_BATCH_IO` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, any other nonempty value is on; disable flags dominate | Require streaming selected batch I/O in CUDA SSD streaming; fail closed when unavailable. | [ds4_cuda.cu:4738](ds4_cuda.cu#L4738) |
+| `DS4_CUDA_REQUIRE_STREAMING_SELECTED_EVENT_PIPELINE` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, any other nonempty value is on; disable flags dominate | Require streaming selected event pipeline in CUDA SSD streaming; fail closed when unavailable. | [ds4_cuda.cu:4870](ds4_cuda.cu#L4870) |
+| `DS4_CUDA_SERIAL_F16_MATMUL` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Control the serial F16 matmul CUDA F16 matmul path. | [ds4_cuda.cu:20801](ds4_cuda.cu#L20801) |
+| `DS4_CUDA_SERIAL_ROUTER` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Control or tune the CUDA serial router path. | [ds4_cuda.cu:20806](ds4_cuda.cu#L20806) |
+| `DS4_CUDA_SESSION_BATCH_ATTN_ALIAS` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control the grouped multi-session CUDA attn alias stage. | [ds4.c:69902](ds4.c#L69902) |
+| `DS4_CUDA_SESSION_BATCH_ATTN_CORE` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control the grouped multi-session CUDA attn core stage. | [ds4.c:69905](ds4.c#L69905) |
+| `DS4_CUDA_SESSION_BATCH_ATTN_POST` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control the grouped multi-session CUDA attn post stage. | [ds4.c:69917](ds4.c#L69917) |
+| `DS4_CUDA_SESSION_BATCH_ATTN_PRE` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control the grouped multi-session CUDA attn pre stage. | [ds4.c:69898](ds4.c#L69898) |
+| `DS4_CUDA_SESSION_BATCH_FFN_PRE` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control the grouped multi-session CUDA ffn pre stage. | [ds4.c:69894](ds4.c#L69894) |
+| `DS4_CUDA_SESSION_BATCH_INTERLEAVE` | boolean, default on; unset/empty/nonzero enables pipeline interleaving; exact 0 disables | Control the grouped multi-session CUDA interleave stage. | [ds4.c:70578](ds4.c#L70578) |
+| `DS4_CUDA_SESSION_BATCH_KV_STORE` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control the grouped multi-session CUDA KV store stage. | [ds4.c:69913](ds4.c#L69913) |
+| `DS4_CUDA_SESSION_BATCH_MOE` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control the grouped multi-session CUDA MoE stage. | [ds4.c:69649](ds4.c#L69649) |
+| `DS4_CUDA_SESSION_BATCH_MOE_COMBINE_ROWS` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control the grouped multi-session CUDA MoE combine rows stage. | [ds4.c:69431](ds4.c#L69431) |
+| `DS4_CUDA_SESSION_BATCH_QKV` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control the grouped multi-session CUDA QKV stage. | [ds4.c:69909](ds4.c#L69909) |
+| `DS4_CUDA_SESSION_BATCH_SHARED` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control the grouped multi-session CUDA shared stage. | [ds4.c:69890](ds4.c#L69890) |
+| `DS4_CUDA_SPLITKV_CHUNK` | integer scores/chunk; default 512; clamped 1..512 | Control splitkv chunk in CUDA split-KV attention/speculation. | [ds4_cuda.cu:22568](ds4_cuda.cu#L22568) |
+| `DS4_CUDA_SPLITKV_DECODE` | value-aware boolean, default off; exact 0/empty is off, other nonempty values enable; mere presence also excludes one session-batch path | Enable split-KV decode attention. | [ds4_cuda.cu:2213](ds4_cuda.cu#L2213); [ds4.c:68111](ds4.c#L68111) |
+| `DS4_CUDA_SPLITKV_GLOBAL_SOFTMAX` | value-aware opt-in, default off; exact 0/empty is off, other nonempty values enable | Use the global-softmax variant of split-KV attention. | [ds4_cuda.cu:22589](ds4_cuda.cu#L22589) |
+| `DS4_CUDA_SPLITKV_MIN_SCORE` | integer score count 0..UINT32_MAX; default 0 when explicitly enabled, otherwise 512; CUDA kernel clamps to 0..8192 | Set the minimum visible-score count for split-KV attention. | [ds4_cuda.cu:22557](ds4_cuda.cu#L22557); [ds4.c:17402](ds4.c#L17402) |
+| `DS4_CUDA_SPLITKV_S` | integer exact split count; unset/invalid = automatic; valid value clamped 1..16 | Control splitkv s in CUDA split-KV attention/speculation. | [ds4_cuda.cu:22578](ds4_cuda.cu#L22578) |
+| `DS4_CUDA_SPLITKV_SPEC` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Enable split-KV speculative decoding. | [ds4.c:17255](ds4.c#L17255) |
+| `DS4_CUDA_SPLITKV_SPEC_BATCH_VERIFY` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Use batched verification for split-KV speculation. | [ds4.c:17275](ds4.c#L17275) |
+| `DS4_CUDA_SPLITKV_SPEC_LOG` | presence diagnostic flag; default off; any defined value including 0 enables | Log split-KV speculative-decode admission and fallback decisions. | [ds4.c:55812](ds4.c#L55812) |
+| `DS4_CUDA_SPLITKV_SPEC_TIMING` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Print timing for split-KV speculative-decode stages. | [ds4.c:55851](ds4.c#L55851) |
+| `DS4_CUDA_SPLITKV_SPEC_TOPONLY_ROW0` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Compute only the top result for row zero in split-KV speculation. | [ds4.c:17265](ds4.c#L17265) |
+| `DS4_CUDA_SPLITKV_S_FLOOR` | integer split count; default 4; clamped 1..16 | Control splitkv s floor in CUDA split-KV attention/speculation. | [ds4_cuda.cu:22571](ds4_cuda.cu#L22571) |
+| `DS4_CUDA_SPLITKV_S_MAX` | integer split count; default 16; clamped 1..16 | Control splitkv s max in CUDA split-KV attention/speculation. | [ds4_cuda.cu:22574](ds4_cuda.cu#L22574) |
+| `DS4_CUDA_STREAMING_EXPERT_CACHE_PROFILE` | presence diagnostic flag; default off; any defined value including 0 enables | Profile CUDA SSD-streaming streaming expert cache. | [ds4.c:21849](ds4.c#L21849) |
+| `DS4_CUDA_STREAMING_EXPERT_PERSISTENT_CACHE_ORACLE` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, any other nonempty value is on; disable flags dominate | Run the diagnostic oracle for CUDA SSD-streaming streaming expert persistent cache. | [ds4_cuda.cu:4121](ds4_cuda.cu#L4121) |
+| `DS4_CUDA_STREAMING_EXPERT_PERSISTENT_CACHE_STATS` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, any other nonempty value is on; disable flags dominate | Print counters for CUDA SSD-streaming streaming expert persistent cache. | [ds4_cuda.cu:4119](ds4_cuda.cu#L4119) |
+| `DS4_CUDA_STREAMING_PREFILL_BATCH_SELECTED_PROFILE` | presence diagnostic flag; default off; any defined value including 0 enables | Profile CUDA SSD-streaming streaming prefill batch selected. | [ds4.c:21932](ds4.c#L21932) |
+| `DS4_CUDA_STREAMING_SELECTED_BATCH_IO_ORACLE` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, any other nonempty value is on; disable flags dominate | Run the diagnostic oracle for CUDA SSD-streaming streaming selected batch I/O. | [ds4_cuda.cu:4740](ds4_cuda.cu#L4740) |
+| `DS4_CUDA_STREAMING_SELECTED_BATCH_IO_PROFILE` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, any other nonempty value is on; disable flags dominate | Profile CUDA SSD-streaming streaming selected batch I/O. | [ds4_cuda.cu:5711](ds4_cuda.cu#L5711) |
+| `DS4_CUDA_STREAMING_SELECTED_EVENT_PIPELINE_ORACLE` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, any other nonempty value is on; disable flags dominate | Run the diagnostic oracle for CUDA SSD-streaming streaming selected event pipeline. | [ds4_cuda.cu:4872](ds4_cuda.cu#L4872) |
+| `DS4_CUDA_STREAMING_SELECTED_EVENT_PIPELINE_STATS` | false-like-aware flag, default off; 0/false/no/off (case-insensitive) is off, any other nonempty value is on; disable flags dominate | Print counters for CUDA SSD-streaming streaming selected event pipeline. | [ds4_cuda.cu:4874](ds4_cuda.cu#L4874) |
+| `DS4_CUDA_STRICT_WEIGHT_CACHE` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Fail a weight lookup when cache allocation fails instead of falling back to mapped model memory. | [ds4_cuda.cu:6388](ds4_cuda.cu#L6388) |
+| `DS4_CUDA_SYNC_XDEV` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Synchronize cross-device CUDA copies for debugging and error localization. | [ds4_cuda.cu:363](ds4_cuda.cu#L363) |
+| `DS4_CUDA_TP_ATTN` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control CUDA tensor/expert-parallel attn execution. | [ds4.c:17035](ds4.c#L17035) |
+| `DS4_CUDA_TP_ATTN_CACHE_DUP` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control CUDA tensor/expert-parallel attn cache dup execution. | [ds4.c:17059](ds4.c#L17059) |
+| `DS4_CUDA_TP_ATTN_HEADS` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control CUDA tensor/expert-parallel attn heads execution. | [ds4.c:17051](ds4.c#L17051) |
+| `DS4_CUDA_TP_ATTN_OUT_HC_FUSE` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Control CUDA tensor/expert-parallel attn out HC fuse execution. | [ds4.c:17564](ds4.c#L17564) |
+| `DS4_CUDA_TP_ATTN_PEER_READ` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control CUDA tensor/expert-parallel attn peer read execution. | [ds4.c:17043](ds4.c#L17043) |
+| `DS4_CUDA_TP_EP_BALANCED_SHARED_MID` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control CUDA tensor/expert-parallel EP balanced shared mid execution. | [ds4.c:17116](ds4.c#L17116) |
+| `DS4_CUDA_TP_EP_DELAY_REDUCE` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control CUDA tensor/expert-parallel EP delay reduce execution. | [ds4.c:17091](ds4.c#L17091) |
+| `DS4_CUDA_TP_EP_DIRECT_RETURN` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control CUDA tensor/expert-parallel EP direct return execution. | [ds4.c:17083](ds4.c#L17083) |
+| `DS4_CUDA_TP_EP_DUAL_PREQUANT` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control CUDA tensor/expert-parallel EP dual prequant execution. | [ds4.c:17125](ds4.c#L17125) |
+| `DS4_CUDA_TP_EP_FUSED_HC_REDUCE` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control CUDA tensor/expert-parallel EP fused HC reduce execution. | [ds4.c:17099](ds4.c#L17099) |
+| `DS4_CUDA_TP_EP_FUSED_SHARED_MID` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control CUDA tensor/expert-parallel EP fused shared mid execution. | [ds4.c:17107](ds4.c#L17107) |
+| `DS4_CUDA_TP_EP_PACK_EXACT` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control CUDA tensor/expert-parallel EP pack exact execution. | [ds4.c:17075](ds4.c#L17075) |
+| `DS4_CUDA_TP_MOE` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control CUDA tensor/expert-parallel MoE execution. | [ds4.c:17067](ds4.c#L17067) |
+| `DS4_CUDA_TP_MOE_COPY3` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control CUDA tensor/expert-parallel MoE copy3 execution. | [ds4.c:17149](ds4.c#L17149) |
+| `DS4_CUDA_TP_MOE_DELAY_REDUCE` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control CUDA tensor/expert-parallel MoE delay reduce execution. | [ds4.c:17133](ds4.c#L17133) |
+| `DS4_CUDA_TP_MOE_PACK` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control CUDA tensor/expert-parallel MoE pack execution. | [ds4.c:17141](ds4.c#L17141) |
+| `DS4_CUDA_TP_MOE_PEER_READ` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control CUDA tensor/expert-parallel MoE peer read execution. | [ds4.c:17157](ds4.c#L17157) |
+| `DS4_CUDA_TP_MOE_PEER_ROUTER` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control CUDA tensor/expert-parallel MoE peer router execution. | [ds4.c:17165](ds4.c#L17165) |
+| `DS4_CUDA_TP_OUTPUT` | boolean, default on; empty/unset/nonzero enables, exact 0 disables | Control CUDA tensor/expert-parallel output execution. | [ds4.c:51713](ds4.c#L51713) |
+| `DS4_CUDA_TP_OUTPUT_WAYS` | integer 2..DS4_MAX_GPUS (16); default 8; invalid value falls back to 2; capped by available GPUs | Set the number of GPU ways used to shard CUDA tensor-parallel output projection. | [ds4.c:58](ds4.c#L58); [ds4.c:51720](ds4.c#L51720) |
+| `DS4_CUDA_TP_PREFILL_ATTN_OUTPUT` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control CUDA tensor/expert-parallel prefill attn output execution. | [ds4.c:17445](ds4.c#L17445) |
+| `DS4_CUDA_TP_PREFILL_FFN` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control CUDA tensor/expert-parallel prefill ffn execution. | [ds4.c:17437](ds4.c#L17437) |
+| `DS4_CUDA_TP_Q` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control CUDA tensor/expert-parallel q execution. | [ds4.c:17189](ds4.c#L17189) |
+| `DS4_CUDA_TP_SHARED` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control CUDA tensor/expert-parallel shared execution. | [ds4.c:17173](ds4.c#L17173) |
+| `DS4_CUDA_TP_SHARED_FOLD` | value-aware boolean; default on; unset/empty uses default, exact 0 disables, any other nonempty value enables | Control CUDA tensor/expert-parallel shared fold execution. | [ds4.c:17181](ds4.c#L17181) |
+| `DS4_CUDA_VERIFY_DECODE2_SPLIT_TOP1` | value-aware boolean; default off; unset/empty uses default, exact 0 disables, any other nonempty value enables | Enable the split top-1 path for two-row verification decode. | [ds4.c:17225](ds4.c#L17225) |
+| `DS4_CUDA_WEIGHT_ARENA_CHUNK_MB` | positive integer MiB; default 1792; clamped 256..8192 and raised/aligned when one allocation needs more | Set the CUDA selective-weight arena allocation chunk. | [ds4_cuda.cu:6311](ds4_cuda.cu#L6311) |
+| `DS4_CUDA_WEIGHT_CACHE` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Force selective CUDA weight caching instead of direct mapped access. | [ds4_cuda.cu:1246](ds4_cuda.cu#L1246) |
+| `DS4_CUDA_WEIGHT_CACHE_LIMIT_GB` | unsigned integer GiB; default/0 = unlimited; parser accepts a numeric prefix even with trailing text | Limit total CUDA selective-weight cache allocation. | [ds4_cuda.cu:6299](ds4_cuda.cu#L6299) |
+| `DS4_CUDA_WEIGHT_CACHE_VERBOSE` | presence diagnostic flag; default off; any defined value including 0 enables | Print CUDA weight mapping, caching, and preload diagnostics. | [ds4_cuda.cu:1297](ds4_cuda.cu#L1297) |
+| `DS4_CUDA_WEIGHT_PRELOAD` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Request proactive CUDA weight caching/preloading. | [ds4_cuda.cu:1247](ds4_cuda.cu#L1247) |
+| `DS4_CUDA_WEIGHT_PRELOAD_SPAN_MB` | positive integer MiB; default 1024; clamped 64..4096 | Set the maximum span size used by CUDA weight preload. | [ds4.c:2880](ds4.c#L2880) |
+| `DS4_CUDA_WINDOW_ATTENTION` | presence flag; unset does not force the path; any defined value including 0 is true; eligibility/auto-policy still applies | Control or tune the CUDA window attention path. | [ds4_cuda.cu:23051](ds4_cuda.cu#L23051) |
+
+
+
+
+ROCm (147)
+
+| Variable | Accepted value and default | Effect | Source |
+| --- | --- | --- | --- |
+| `DS4_ROCM_DECODE_STAGE_PROFILE` | presence/nonempty diagnostic; unset=off (path-valued DUMP names are noted by purpose) | Collect timing/profile diagnostics for rocm decode stage profile. | [ds4.c:18244](ds4.c#L18244) |
+| `DS4_ROCM_DECODE_STAGE_PROFILE_LAYER` | layer filter subordinate to DS4_ROCM_DECODE_STAGE_PROFILE; unset or whitespace-only: all layers allowed by the parent flag; otherwise the whitespace-trimmed value must be a complete base-10 strtoul result <= UINT32_MAX equal to the current layer; invalid values match none | Restricts the ROCm decode stage profiler to one layer; it does not enable profiling by itself. | [ds4.c:29116](ds4.c#L29116) |
+| `DS4_ROCM_DISABLE_GLM_STREAMING_PREFILL_FULL_LAYER` | integer selector/tuning value; unset or invalid uses internal automatic/default value | Disable/roll back rocm disable glm streaming prefill full layer. | [ds4.c:42709](ds4.c#L42709) |
+| `DS4_ROCM_DISABLE_GLM_STREAMING_PREFILL_FULL_LAYER_PREPARE` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable glm streaming prefill full layer prepare. | [ds4.c:42727](ds4.c#L42727) |
+| `DS4_ROCM_DISABLE_GLM_STREAMING_PREFILL_SELECTED_ASYNC_LOAD` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable glm streaming prefill selected async load. | [ds4.c:46420](ds4.c#L46420) |
+| `DS4_ROCM_DISABLE_GLM_STREAMING_SELECTED_ASYNC_LOAD` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable glm streaming selected async load. | [ds4.c:44328](ds4.c#L44328) |
+| `DS4_ROCM_DISABLE_IQ2_SELECTED_EXPERT_VIEWS` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable iq2 selected expert views. | [ds4.c:21079](ds4.c#L21079) |
+| `DS4_ROCM_DISABLE_IQ2_STREAM_ADDR_TABLE` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable iq2 stream addr table. | [ds4.c:6548](ds4.c#L6548) |
+| `DS4_ROCM_DISABLE_Q4_DENSE_PAIR` | presence rollback; unset leaves opt-in policy unchanged | Disable/roll back rocm disable q4 dense pair. | [rocm/ds4_rocm_q4.cuh:435](rocm/ds4_rocm_q4.cuh#L435) |
+| `DS4_ROCM_DISABLE_Q4_GROUPED_ATTN_A` | presence rollback; unset permits the caller-marked resident decode production-shape default and explicit ENABLE/REQUIRE; any defined value including empty or 0 disables all grouped attention-A paths and wins over ENABLE/REQUIRE | Restore eight standalone Q4 attention-A projections instead of the two-dispatch grouped path. | [rocm/ds4_rocm_q4.cuh:868](rocm/ds4_rocm_q4.cuh#L868) |
+| `DS4_ROCM_DISABLE_Q4_PREFILL_TILE8` | presence rollback; TILE8 is default for 9..4096 tokens | Disable/roll back rocm disable q4 prefill tile8. | [rocm/ds4_rocm_q4.cuh:448](rocm/ds4_rocm_q4.cuh#L448) |
+| `DS4_ROCM_DISABLE_Q4_PREFILL_WMMA` | value-aware authoritative opt-out for the automatic resident path and explicit SSD/REQUIRE requests; unset/0/false/no/off leaves policy unchanged, while empty or any other value disables; REQUIRE then fails closed | Prevent the gfx1151 direct-Q4 WMMA prefill path from dispatching and retain the Q8_K-plus-TILE8/TILE4 path. | [rocm/ds4_rocm_q4.cuh:1626](rocm/ds4_rocm_q4.cuh#L1626) |
+| `DS4_ROCM_DISABLE_Q4_PREFILL_WMMA_K128` | value-aware rollback for the default K128/P144 stage; unset/0/false/no/off keeps K128 after the normal direct-Q4 WMMA gates, K64 control, 256-row geometry, and 16-byte activation alignment pass; empty or any other value restores K64; incompatible launches also retain K64 and K64=0 retains the K32 rollback | Roll aligned resident q_b-shaped 256-row direct-WMMA launches back from four-qgroup K128/P144 staging and float4 activation loads to K64/P80. | [rocm/ds4_rocm_q4.cuh:1874](rocm/ds4_rocm_q4.cuh#L1874) |
+| `DS4_ROCM_DISABLE_Q4_SELECTED_EXPERT_VIEWS` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable q4 selected expert views. | [ds4.c:21150](ds4.c#L21150) |
+| `DS4_ROCM_DISABLE_RESIDENT_IQ2_SORTED` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable resident iq2 sorted. | [rocm/ds4_rocm_moe_launch.cuh:751](rocm/ds4_rocm_moe_launch.cuh#L751) |
+| `DS4_ROCM_DISABLE_ROUTED_PAIR_SWIGLU_FUSION` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable routed pair swiglu fusion. | [ds4.c:18543](ds4.c#L18543) |
+| `DS4_ROCM_DISABLE_STREAMING_COLD_DECODE_PREFILL` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming cold decode prefill. | [ds4.c:32021](ds4.c#L32021) |
+| `DS4_ROCM_DISABLE_STREAMING_DECODE_PREFILL` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming decode prefill. | [ds4.c:31970](ds4.c#L31970) |
+| `DS4_ROCM_DISABLE_STREAMING_EXPERT_ADDR_TABLE` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming expert addr table. | [ds4.c:18539](ds4.c#L18539) |
+| `DS4_ROCM_DISABLE_STREAMING_EXPERT_HOTLIST` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming expert hotlist. | [ds4.c:21304](ds4.c#L21304) |
+| `DS4_ROCM_DISABLE_STREAMING_FULL_EXPERT_ADDR_TABLE` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming full expert addr table. | [ds4.c:18257](ds4.c#L18257) |
+| `DS4_ROCM_DISABLE_STREAMING_LAYER_BATCH` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming layer batch. | [ds4.c:18253](ds4.c#L18253) |
+| `DS4_ROCM_DISABLE_STREAMING_MADVISE_WILLNEED` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming madvise willneed. | [ds4.c:18226](ds4.c#L18226) |
+| `DS4_ROCM_DISABLE_STREAMING_PREFILL_BATCH_SELECTED_ADDR` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming prefill batch selected addr. | [ds4.c:18537](ds4.c#L18537) |
+| `DS4_ROCM_DISABLE_STREAMING_PREFILL_LAYER_MADVISE` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming prefill layer madvise. | [ds4.c:18480](ds4.c#L18480) |
+| `DS4_ROCM_DISABLE_STREAMING_PREFILL_LAYER_PAGEIN` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming prefill layer pagein. | [ds4.c:18448](ds4.c#L18448) |
+| `DS4_ROCM_DISABLE_STREAMING_PREFILL_LAYER_PAGEIN_OVERLAP` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming prefill layer pagein overlap. | [ds4.c:19335](ds4.c#L19335) |
+| `DS4_ROCM_DISABLE_STREAMING_PREFILL_LAYER_PREAD` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming prefill layer pread. | [ds4.c:18468](ds4.c#L18468) |
+| `DS4_ROCM_DISABLE_STREAMING_PREFILL_LAYER_PREPARE` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming prefill layer prepare. | [ds4.c:18460](ds4.c#L18460) |
+| `DS4_ROCM_DISABLE_STREAMING_PREFILL_LAYER_PREPARE_OVERLAP` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming prefill layer prepare overlap. | [ds4.c:19333](ds4.c#L19333) |
+| `DS4_ROCM_DISABLE_STREAMING_PREFILL_LAYER_READAHEAD` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming prefill layer readahead. | [ds4.c:18458](ds4.c#L18458) |
+| `DS4_ROCM_DISABLE_STREAMING_PREFILL_SELECTED_ASYNC_LOAD` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming prefill selected async load. | [ds4.c:46684](ds4.c#L46684) |
+| `DS4_ROCM_DISABLE_STREAMING_PREFILL_SELECTED_MADVISE` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming prefill selected madvise. | [ds4.c:18438](ds4.c#L18438) |
+| `DS4_ROCM_DISABLE_STREAMING_PREFILL_SELECTED_PAGEIN` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming prefill selected pagein. | [ds4.c:18428](ds4.c#L18428) |
+| `DS4_ROCM_DISABLE_STREAMING_PREFILL_SELECTED_PROFILE` | presence rollback flag; unset keeps automatic/default path | Collect timing/profile diagnostics for rocm disable streaming prefill selected profile. | [ds4.c:18922](ds4.c#L18922) |
+| `DS4_ROCM_DISABLE_STREAMING_PREFILL_SELECTED_READAHEAD` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming prefill selected readahead. | [ds4.c:19974](ds4.c#L19974) |
+| `DS4_ROCM_DISABLE_STREAMING_PREFILL_SELECTED_READAHEAD_SHARED` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming prefill selected readahead shared. | [ds4.c:19984](ds4.c#L19984) |
+| `DS4_ROCM_DISABLE_STREAMING_READAHEAD` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming readahead. | [ds4.c:18219](ds4.c#L18219) |
+| `DS4_ROCM_DISABLE_STREAMING_SELECTED_ASYNC_LOAD` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming selected async load. | [ds4.c:44587](ds4.c#L44587) |
+| `DS4_ROCM_DISABLE_STREAMING_SPLIT_SELECTED` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming split selected. | [rocm/ds4_rocm_moe_launch.cuh:665](rocm/ds4_rocm_moe_launch.cuh#L665) |
+| `DS4_ROCM_DISABLE_STREAMING_STATIC_DECODE_MAP` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming static decode map. | [ds4.c:18231](ds4.c#L18231) |
+| `DS4_ROCM_DISABLE_STREAMING_STATIC_MAP_STATE_CACHE` | presence rollback flag; unset keeps automatic/default path | Disable/roll back rocm disable streaming static map state cache. | [ds4.c:18244](ds4.c#L18244) |
+| `DS4_ROCM_DSV4_PREQUANT_DECODE` | sampled once; unset: enabled; present empty or exact 0: disabled; every other present value: enabled; quality mode and GLM models force it off regardless | ROCm DeepSeek-V4 decode: quantizes one-token F32 activations to Q8 once and selects the prequantized Q8_0/DP4A projection kernels instead of the full-F32 activation paths. | [rocm/ds4_rocm_runtime.cuh:4775](rocm/ds4_rocm_runtime.cuh#L4775) |
+| `DS4_ROCM_ENABLE_MXFP4_LDSB` | presence opt-in; unset=off; any defined value including empty or 0 enables the candidate when the MXFP4 path, sorted expert tiles, token count >= 128, LDS-size limit, and dimension-alignment gates all pass | Select the ROCm MXFP4 prefill gate/up kernel that stages eight gate and eight up weight rows in LDS and reuses them across expert tiles of up to 128 tokens. | [rocm/ds4_rocm_moe_launch.cuh:782](rocm/ds4_rocm_moe_launch.cuh#L782) |
+| `DS4_ROCM_ENABLE_MXFP4_ROW64` | presence opt-in; unset=off; any defined value including empty or 0 enables the candidate when the MXFP4 sorted-tile path has at least 8 tokens and the TILE32, LDSB, and TILE4 candidates are not selected | Select the ROCm MXFP4 gate/up tile8 occupancy variant with 64 row slots and 512 threads per block. | [rocm/ds4_rocm_moe_launch.cuh:798](rocm/ds4_rocm_moe_launch.cuh#L798) |
+| `DS4_ROCM_ENABLE_MXFP4_TILE32` | presence opt-in; unset=off; any defined value including empty or 0 enables the candidate when the MXFP4 sorted-tile path has at least 32 tokens and the expert intermediate dimension is divisible by 32 | Select the ROCm MXFP4 gate/up tile32 kernel, reusing each loaded expert-weight chunk across as many as 32 tokens. | [rocm/ds4_rocm_moe_launch.cuh:786](rocm/ds4_rocm_moe_launch.cuh#L786) |
+| `DS4_ROCM_ENABLE_MXFP4_TILE4` | presence opt-in; unset=off; any defined value including empty or 0 enables the candidate when the MXFP4 sorted-tile path has at least 5 tokens and neither TILE32 nor LDSB is selected | Select the ROCm MXFP4 gate/up tile4 occupancy variant, reducing staged-activation LDS per block. | [rocm/ds4_rocm_moe_launch.cuh:794](rocm/ds4_rocm_moe_launch.cuh#L794) |
+| `DS4_ROCM_ENABLE_Q4_DENSE_PAIR` | presence opt-in; unset=off; DISABLE takes precedence | Enable rocm enable q4 dense pair. | [rocm/ds4_rocm_q4.cuh:434](rocm/ds4_rocm_q4.cuh#L434) |
+| `DS4_ROCM_ENABLE_Q4_GROUPED_ATTN_A` | presence opt-in outside the default scope; the exact caller-marked resident decode shape groups=8, N=1, K=4096, M=1024 is automatic, while row-at-a-time batch fallbacks are not; DISABLE wins | Enable grouped Q4 attention-A for eligible slices, non-production shapes, or explicit experiments in addition to the resident decode default. | [rocm/ds4_rocm_q4.cuh:872](rocm/ds4_rocm_q4.cuh#L872) |
+| `DS4_ROCM_ENABLE_Q4_PREFILL_WMMA` | value-aware compatibility control; unset keeps automatic resident direct-Q4 WMMA for standalone dense and attention-output A while attention-output B remains on Q8_K+TILE8; empty or any value other than 0/false/no/off explicitly retains the same eligible A paths but no longer opts B into direct WMMA; explicit 0/false/no/off opts out unless REQUIRE is set, while DISABLE is the authoritative rollback; N=256..4096, K a positive multiple of 256, resident non-quality gfx1151 wave32 only; SSD has a separate gate | Use compressed Q4_K-to-F16 register dequantization plus shape-selected 64-token by 64/128/256-row WMMA tiles, K64/P80 staging on 64/128 rows, and default K128/P144 float4 staging on aligned 256 rows, without Q8_K activation scratch or an F16 weight sidecar. | [rocm/ds4_rocm_q4.cuh:1622](rocm/ds4_rocm_q4.cuh#L1622) |
+| `DS4_ROCM_ENABLE_Q4_PREFILL_WMMA_K64` | value-aware base staging control; unset, empty, or any value other than 0/false/no/off uses K64/P80 on 64/128-row or K128-incompatible launches and permits default K128/P144 on aligned 256-row launches; 0/false/no/off suppresses both wider stages and rolls back to K32; DS4_ROCM_DISABLE_Q4_PREFILL_WMMA wins | Stage two adjacent 32-value Q4_K groups and a 64-value activation slice in one padded P80 LDS tile as the narrower geometry and K128 fallback, halving K32 workgroup barriers while preserving its activation traffic and accumulation order. | [rocm/ds4_rocm_q4.cuh:1870](rocm/ds4_rocm_q4.cuh#L1870) |
+| `DS4_ROCM_ENABLE_Q4_PREFILL_WMMA_SSD` | value-aware SSD-only opt-in, default off; unset/0/false/no/off retains TILE8/TILE4, while empty or any other value requests direct-Q4 WMMA for eligible standalone projections and attention-output A but leaves attention-output B on Q8_K+TILE8; eligibility additionally requires each complete projection weight range in physical device storage rather than mapped/registered host memory; DISABLE wins | Allow the compressed direct-Q4 WMMA kernel to consume an already device-resident/cache-backed Q4_K projection during SSD streaming without changing model I/O. | [rocm/ds4_rocm_q4.cuh:1356](rocm/ds4_rocm_q4.cuh#L1356) |
+| `DS4_ROCM_ENABLE_STREAMING_FULL_EXPERT_ADDR_TABLE` | presence opt-in flag; unset=off unless paired policy is automatic | Enable rocm enable streaming full expert addr table. | [ds4.c:18255](ds4.c#L18255) |
+| `DS4_ROCM_ENABLE_STREAMING_MADVISE_WILLNEED` | presence opt-in flag; unset=off unless paired policy is automatic | Enable rocm enable streaming madvise willneed. | [ds4.c:18224](ds4.c#L18224) |
+| `DS4_ROCM_ENABLE_STREAMING_PREFILL_BATCH_SELECTED_ADDR` | presence opt-in flag; unset=off unless paired policy is automatic | Enable rocm enable streaming prefill batch selected addr. | [ds4.c:18584](ds4.c#L18584) |
+| `DS4_ROCM_ENABLE_STREAMING_PREFILL_CACHE_SEED` | presence opt-in flag; unset=off unless paired policy is automatic | Enable rocm enable streaming prefill cache seed. | [ds4.c:21273](ds4.c#L21273) |
+| `DS4_ROCM_ENABLE_STREAMING_PREFILL_LAYER_PAGEIN` | presence opt-in flag; unset=off unless paired policy is automatic | Enable rocm enable streaming prefill layer pagein. | [ds4.c:18446](ds4.c#L18446) |
+| `DS4_ROCM_ENABLE_STREAMING_PREFILL_LAYER_READAHEAD` | presence opt-in flag; unset=off unless paired policy is automatic | Enable rocm enable streaming prefill layer readahead. | [ds4.c:18456](ds4.c#L18456) |
+| `DS4_ROCM_ENABLE_STREAMING_PREFILL_SELECTED_MADVISE` | presence opt-in flag; unset=off unless paired policy is automatic | Enable rocm enable streaming prefill selected madvise. | [ds4.c:18436](ds4.c#L18436) |
+| `DS4_ROCM_ENABLE_STREAMING_PREFILL_SELECTED_PAGEIN` | presence opt-in flag; unset=off unless paired policy is automatic | Enable rocm enable streaming prefill selected pagein. | [ds4.c:18426](ds4.c#L18426) |
+| `DS4_ROCM_ENABLE_STREAMING_PREFILL_SELECTED_READAHEAD` | presence opt-in flag; unset=off unless paired policy is automatic | Enable rocm enable streaming prefill selected readahead. | [ds4.c:19970](ds4.c#L19970) |
+| `DS4_ROCM_ENABLE_STREAMING_PREFILL_SELECTED_READAHEAD_SHARED` | presence opt-in flag; unset=off unless paired policy is automatic | Enable rocm enable streaming prefill selected readahead shared. | [ds4.c:19972](ds4.c#L19972) |
+| `DS4_ROCM_ENABLE_STREAMING_READAHEAD` | presence opt-in flag; unset=off unless paired policy is automatic | Enable rocm enable streaming readahead. | [ds4.c:18217](ds4.c#L18217) |
+| `DS4_ROCM_ENABLE_STREAMING_STATIC_DECODE_MAP` | presence opt-in flag; unset=off unless paired policy is automatic | Enable rocm enable streaming static decode map. | [ds4.c:18236](ds4.c#L18236) |
+| `DS4_ROCM_GLM_CAUSAL_ATTN_GEMM` | Enabled by default when unset. Exact "0" or an empty value disables; every other nonempty value enables (including false/off/no), because cuda_env_present only tests nonempty and != "0". Eligibility still requires causal_range && !has_selected; a failed GEMM helper falls through to the scalar attention kernel. | Use FP16 BLAS GEMMs for dense causal GLM indexed prefill; =0 is the correctness/performance rollback to the scalar attention kernel. | [rocm/ds4_rocm_glm.cuh:3283](rocm/ds4_rocm_glm.cuh#L3283) |
+| `DS4_ROCM_GLM_DISABLE_STREAMING_EXPERT_CACHE` | Pure presence flag: any defined value, including empty or "0", disables. Unset leaves automatic GLM streaming expert-cache eligibility enabled for supported model/quant/quality/SSD configurations. On ROCm builds DS4_METAL_GLM_DISABLE_STREAMING_EXPERT_CACHE is an accepted fallback alias. | Disable selected/resident streamed-expert cache paths and force generic/full-layer expert handling for GLM SSD streaming. | [ds4.c:21197](ds4.c#L21197) |
+| `DS4_ROCM_GLM_DISABLE_STREAMING_SEED_BEFORE_PREFILL` | Pure presence flag: any defined value, including empty or "0", disables. Unset seeds before prefill whenever SSD streaming is active. On ROCm builds DS4_METAL_GLM_DISABLE_STREAMING_SEED_BEFORE_PREFILL is an accepted fallback alias. | Skip the pre-prefill hotlist seed of the streaming expert cache in both one-shot GLM generation and session setup. | [ds4.c:51073](ds4.c#L51073) |
+| `DS4_ROCM_GLM_DISABLE_STREAMING_TOKEN_PREFILL` | Pure presence flag: any defined value, including empty or "0", disables. Unset leaves the token-major path eligible only for SSD streaming, non-quality mode, a nonempty batch fitting full attention, and n_tokens <= the configured nonzero maximum. DS4_METAL_GLM_DISABLE_STREAMING_TOKEN_PREFILL and generic DS4_GLM_DISABLE_STREAMING_TOKEN_PREFILL are also accepted presence aliases. | Roll back GLM SSD-streaming token-major prefill to the normal prefill implementation. | [ds4.c:49703](ds4.c#L49703) |
+| `DS4_ROCM_GLM_GROUPED_QK_LOW` | sampled once; unset: enabled; present empty or exact 0: disabled; every other present value: enabled | Selects the grouped shared-input ROCm kernel for eligible multi-token GLM qk-lowrank projection; disabling uses the per-head/per-token projection kernel. | [rocm/ds4_rocm_runtime.cuh:4800](rocm/ds4_rocm_runtime.cuh#L4800) |
+| `DS4_ROCM_GLM_GROUPED_VALUE_PROJECT` | sampled once; unset: enabled; present empty or exact 0: disabled; every other present value: enabled | Selects the grouped shared-input ROCm kernel for eligible multi-token GLM value projection; disabling uses the non-grouped batch projection path. | [rocm/ds4_rocm_runtime.cuh:4791](rocm/ds4_rocm_runtime.cuh#L4791) |
+| `DS4_ROCM_GLM_LAYER_SLICE_TOKEN_DECODE` | Opt-in truthy parser; unset, empty, "0", false, off, or no (case-insensitive words) are false, every other nonempty value is true. Default off and compiled only for ROCm. | Allow a one-token, pos>0 GLM layer-slice with inter-node input/output hidden buffers to use the optimized resident token graph; without it only the no-hidden-buffer case takes that shortcut. | [ds4.c:43573](ds4.c#L43573) |
+| `DS4_ROCM_GLM_SELECTED_ATTN_GEMM` | Enabled by default when unset. Exact "0" or an empty value disables; every other nonempty value enables (including false/off/no). Eligibility still requires !causal_range && has_selected; failure/ineligibility falls through to the scalar attention kernel. | Gather per-token selected cache rows into FP16 matrices and use strided-batched BLAS GEMMs for GLM selected indexed prefill; =0 forces the scalar path. | [rocm/ds4_rocm_glm.cuh:3239](rocm/ds4_rocm_glm.cuh#L3239) |
+| `DS4_ROCM_GLM_SELECTED_ATTN_HEAD_TILE` | Unsigned integer read and cached once; valid values are exactly 1,2,4,8,16,32,64. Unset/empty defaults to 16. A nonnumeric, partially parsed, overflowed, or unsupported value prints a warning and uses 16; the effective tile is min(requested,n_head). | Set how many attention heads each selected-attention GEMM workspace tile processes. | [rocm/ds4_rocm_glm.cuh:2509](rocm/ds4_rocm_glm.cuh#L2509) |
+| `DS4_ROCM_GLM_SELECTED_ATTN_PROFILE` | presence/nonempty diagnostic; unset=off (path-valued DUMP names are noted by purpose) | Collect timing/profile diagnostics for rocm glm selected attn profile. | [rocm/ds4_rocm_glm.cuh:2534](rocm/ds4_rocm_glm.cuh#L2534) |
+| `DS4_ROCM_GLM_STREAMING_ASYNC_PROFILE` | presence/nonempty diagnostic; unset=off (path-valued DUMP names are noted by purpose) | Collect timing/profile diagnostics for rocm glm streaming async profile. | [ds4.c:44361](ds4.c#L44361) |
+| `DS4_ROCM_GLM_STREAMING_DECODE_FULL_LAYER_MAP` | Pure presence flag: any defined value, including empty or "0", forces full mapping. Unset uses automatic mapping: resident layers map fully, eligible expert-cache layers use decode-only/expert mapping, otherwise full mapping. DS4_METAL_GLM_STREAMING_DECODE_FULL_LAYER_MAP and generic DS4_GLM_STREAMING_DECODE_FULL_LAYER_MAP are also accepted presence aliases. | Force every GLM SSD-streaming decode layer through full-layer mapping, bypassing the selected-expert/decode mapping optimization. | [ds4.c:42615](ds4.c#L42615) |
+| `DS4_ROCM_GLM_STREAMING_DECODE_SYNC_EACH_LAYER` | ROCm-only primary value; nonempty takes priority over DS4_METAL_GLM_STREAMING_DECODE_SYNC_EACH_LAYER and the generic DS4_GLM_STREAMING_DECODE_SYNC_EACH_LAYER fallback; empty acts as unset; truthy unless exact 0 or case-insensitive false/off/no; with all aliases unset: false | For non-static GLM SSD decode on ROCm, opts into a full command/device synchronization after token mapping and every layer; default keeps ordered work queued across layer mappings, and static-map decode bypasses it. | [ds4.c:49779](ds4.c#L49779) |
+| `DS4_ROCM_GLM_STREAMING_GROW_CACHE_AFTER_PREFILL` | Enabled by default when absent. If defined, only a truthy nonempty value enables; empty, "0", false, off, or no disable. Growth also requires SSD streaming plus nonzero base cache and prefill-headroom budgets, and occurs only if the recomputed expert count exceeds the current count. | After successful ROCm GLM prefill, add the released prefill headroom to the dynamic streaming expert-cache byte budget. | [ds4.c:51111](ds4.c#L51111) |
+| `DS4_ROCM_GLM_STREAMING_PREFILL_FULL_LAYER` | presence force-on; any presence including empty or 0 enables; unset falls back to the Metal alias and then the automatic token threshold (1024 by default on ROCm); DS4_ROCM_DISABLE_GLM_STREAMING_PREFILL_FULL_LAYER dominates | Forces GLM SSD prefill into full-layer mapping/cache mode even below the automatic large-batch threshold. | [ds4.c:42692](ds4.c#L42692) |
+| `DS4_ROCM_GLM_STREAMING_PREFILL_FULL_LAYER_MIN_TOKENS` | Positive uint32 threshold parsed with strtoul; ROCm default is 1024. Missing/empty, no leading number, errno/overflow, zero, or >UINT32_MAX returns 1024. The parser does not require end-of-string, so trailing junk after a valid leading number is accepted. A nonempty ROCm value takes precedence; otherwise DS4_METAL_GLM_STREAMING_PREFILL_FULL_LAYER_MIN_TOKENS is a fallback alias. | Set the automatic token-count crossover for ROCm GLM SSD prefill to load/use full resident expert layers when the layer supports that mode. | [ds4.c:42692](ds4.c#L42692) |
+| `DS4_ROCM_GLM_STREAMING_PREFILL_SYNC_EACH_LAYER` | ROCm-only primary value; nonempty takes priority over DS4_METAL_GLM_STREAMING_PREFILL_SYNC_EACH_LAYER and the generic DS4_GLM_STREAMING_PREFILL_SYNC_EACH_LAYER fallback; empty acts as unset; truthy unless exact 0 or case-insensitive false/off/no; with all aliases unset: false for compact prefill; full-layer prefill always returns true | For compact GLM SSD prefill on ROCm, opts into a full command/device synchronization at every layer boundary; default preserves queued work across mappings, while full-layer cache mode always synchronizes. | [ds4.c:42395](ds4.c#L42395) |
+| `DS4_ROCM_GLM_STREAMING_TOKEN_PREFILL_MAX` | primary nonempty value, then the Metal alias, then generic DS4_GLM_STREAMING_TOKEN_PREFILL_MAX; parsed by strtoul without requiring full-string consumption; 0 is valid and disables; no digits, ERANGE, or > UINT32_MAX uses the ROCm default 0 | Sets the largest non-quality GLM SSD-prefill chunk eligible for token-major/decode-style execution; ROCm defaults to canonical indexed batch prefill (0 disables token-major mode). | [ds4.c:49682](ds4.c#L49682) |
+| `DS4_ROCM_GLM_VALUE_PROJECT_WAVE_DECODE` | Enabled by default when unset. Exact "0" or empty disables; every other nonempty value enables (including false/off/no). It applies only when n_tokens==1; =0 or multi-token input uses the generic per-head batch kernel. | Select the validated wave-per-output-row ROCm Q8 GLM value-projection kernel for one-token decode; =0 is the generic-kernel rollback. | [rocm/ds4_rocm_glm.cuh:2019](rocm/ds4_rocm_glm.cuh#L2019) |
+| `DS4_ROCM_GRAPH_DUMP_LAYER` | unsigned layer or all; unset=all layers | Filter ROCm graph dumps by layer. | [ds4.c:16862](ds4.c#L16862) |
+| `DS4_ROCM_GRAPH_DUMP_NAME` | nonempty substring filter; unset=all tensor names | Filter ROCm graph dumps by tensor/stage name. | [ds4.c:16858](ds4.c#L16858) |
+| `DS4_ROCM_GRAPH_DUMP_NONINVASIVE` | truthy value under the shared parser; unset lets dumping select conservative kernels | Keep production ROCm kernel selection while graph dumping. | [rocm/ds4_rocm_runtime.cuh:4822](rocm/ds4_rocm_runtime.cuh#L4822) |
+| `DS4_ROCM_GRAPH_DUMP_POS` | unsigned token position; unset=all positions | Filter ROCm graph dumps by position. | [ds4.c:16869](ds4.c#L16869) |
+| `DS4_ROCM_GRAPH_DUMP_PREFIX` | nonempty output path prefix; unset=off | Enable ROCm intermediate graph/tensor dumps. | [ds4_cuda.cu:397](ds4_cuda.cu#L397) |
+| `DS4_ROCM_GRAPH_DUMP_TRACE` | presence/nonempty diagnostic; unset=off (path-valued DUMP names are noted by purpose) | Emit trace diagnostics for rocm graph dump trace. | [ds4.c:16899](ds4.c#L16899) |
+| `DS4_ROCM_GRAPH_OUTPUT_ROW` | Nonempty string with a leading strtoul-parsable unsigned value < n_tokens selects that zero-based row. Default, empty, unparsable, or out-of-range selects n_tokens-1. Trailing characters are accepted because full consumption/errno are not checked. A nonempty ROCm value takes precedence; otherwise DS4_METAL_GRAPH_OUTPUT_ROW is a fallback alias. | Choose which prefill hidden-state row is sent through the output head to produce logits, primarily for graph/correctness diagnostics. | [ds4.c:35845](ds4.c#L35845) |
+| `DS4_ROCM_GRAPH_PREFILL_PROFILE` | presence/nonempty diagnostic; unset=off (path-valued DUMP names are noted by purpose) | Collect timing/profile diagnostics for rocm graph prefill profile. | [ds4.c:32038](ds4.c#L32038) |
+| `DS4_ROCM_GRAPH_PREFILL_SPLIT_PROFILE` | presence/nonempty diagnostic; unset=off (path-valued DUMP names are noted by purpose) | Collect timing/profile diagnostics for rocm graph prefill split profile. | [ds4.c:35768](ds4.c#L35768) |
+| `DS4_ROCM_GRAPH_TOKEN_PROFILE` | presence/nonempty diagnostic; unset=off (path-valued DUMP names are noted by purpose) | Collect timing/profile diagnostics for rocm graph token profile. | [ds4.c:31722](ds4.c#L31722) |
+| `DS4_ROCM_INDEXER_STAGE_PROFILE` | presence/nonempty diagnostic; unset=off (path-valued DUMP names are noted by purpose) | Collect timing/profile diagnostics for rocm indexer stage profile. | [ds4.c:29265](ds4.c#L29265) |
+| `DS4_ROCM_LAYER_STAGE_PROFILE` | presence/nonempty diagnostic; unset=off (path-valued DUMP names are noted by purpose) | Collect timing/profile diagnostics for rocm layer stage profile. | [ds4.c:29104](ds4.c#L29104) |
+| `DS4_ROCM_LAYER_STAGE_PROFILE_LAYER` | layer filter subordinate to DS4_ROCM_LAYER_STAGE_PROFILE; unset or whitespace-only: all layers allowed by the parent flag; otherwise the whitespace-trimmed value must be a complete base-10 strtoul result <= UINT32_MAX equal to the current layer; invalid values match none | Restricts the ROCm layer/prefill stage profiler to one layer; it does not enable profiling by itself. | [ds4.c:29105](ds4.c#L29105) |
+| `DS4_ROCM_MOE_DECODE_DOWN_RPB` | sampled once; nonempty value is parsed by strtoul (a numeric prefix is sufficient), cast to uint32_t, and accepted only if 1/2/4/8/16/32; unset/empty/invalid inherits DS4_ROCM_MOE_DECODE_RPB, with defaults quality=8, non-quality SSD=2, resident=1 | Sets output rows (warps) per block for ROCm Q2_K routed-MoE decode down-projection kernels; threads per block are value * 32. | [rocm/ds4_rocm_runtime.cuh:4842](rocm/ds4_rocm_runtime.cuh#L4842) |
+| `DS4_ROCM_MOE_DECODE_GATE_RPB` | sampled once; nonempty value is parsed by strtoul (a numeric prefix is sufficient), cast to uint32_t, and accepted only if 1/2/4/8/16/32; unset/empty/invalid defaults to 1 in non-quality SSD mode when DS4_ROCM_MOE_DECODE_RPB is unset/empty, otherwise inherits the resolved base RPB | Sets output rows (warps) per block for ROCm Q2_K routed-MoE decode gate/up kernels; threads per block are value * 32. | [rocm/ds4_rocm_runtime.cuh:4836](rocm/ds4_rocm_runtime.cuh#L4836) |
+| `DS4_ROCM_MOE_DECODE_PROFILE` | presence/nonempty diagnostic; unset=off (path-valued DUMP names are noted by purpose) | Collect timing/profile diagnostics for rocm moe decode profile. | [rocm/ds4_rocm_moe_launch.cuh:82](rocm/ds4_rocm_moe_launch.cuh#L82) |
+| `DS4_ROCM_MOE_DECODE_RPB` | sampled once; nonempty value is parsed by strtoul (a numeric prefix is sufficient), cast to uint32_t, and accepted only if 1/2/4/8/16/32; unset/empty/invalid default: quality=8, non-quality SSD=2, resident=1 | Sets the base ROCm Q2_K decode-MoE rows-per-block value inherited by gate/up and down controls, except the automatic SSD gate specialization defaults to 1 when this variable is unset/empty. | [rocm/ds4_rocm_runtime.cuh:4832](rocm/ds4_rocm_runtime.cuh#L4832) |
+| `DS4_ROCM_MOE_PATH_DEBUG` | presence diagnostic; unset=off; any defined value including empty or 0 enables it | Print ROCm routed-MoE path selection, sorted-tile scratch state, and MXFP4 gate/up launch diagnostics to stderr. | [rocm/ds4_rocm_moe_launch.cuh:831](rocm/ds4_rocm_moe_launch.cuh#L831) |
+| `DS4_ROCM_MOE_WRITE_CLAMPED_ACT` | Pure presence sentinel: any defined value, including empty or "0", is active; DS4_METAL_MOE_WRITE_CLAMPED_ACT is an accepted fallback alias. On ROCm the variable is only consumed as a path-admission veto: it disables selected-expert cache/address-table, selected-slot and CPU-router/fused optimized paths. No ROCm call site parses a clamp amount or directly enables a write-clamped kernel. | Force shared graph selection away from optimizations incompatible with the clamped-intermediate MoE diagnostic; on ROCm this is a compatibility/rollback gate, not itself a clamped-write implementation. | [ds4.c:18526](ds4.c#L18526) |
+| `DS4_ROCM_MXFP4_DOWN_RGROUP` | nonempty value is parsed by strtol and a numeric prefix is sufficient; integers 1..8 are accepted; unset, empty, invalid, or out-of-range values use 1 | Set how many 32-row output blocks each ROCm MXFP4 tiled down-projection block computes, reducing the first launch-grid dimension as the value increases. | [rocm/ds4_rocm_moe_launch.cuh:801](rocm/ds4_rocm_moe_launch.cuh#L801) |
+| `DS4_ROCM_Q4_GROUPED_ATTN_A_STATS` | presence/nonempty diagnostic; unset=off (path-valued DUMP names are noted by purpose) | Print counters for rocm q4 grouped attn a stats. | [rocm/ds4_rocm_q4.cuh:614](rocm/ds4_rocm_q4.cuh#L614) |
+| `DS4_ROCM_Q4_PREFILL_TILE8_STATS` | presence diagnostic; unset=off; any defined value including empty or 0 prints at exit | Print tiled-prefill dense/pair/attention counters, total and SSD-specific K=1024 TILE4 dispatches, and direct-WMMA total/K32/K64/K128 launch counts. | [rocm/ds4_rocm_q4.cuh:1454](rocm/ds4_rocm_q4.cuh#L1454) |
+| `DS4_ROCM_Q4_PREFILL_WMMA_ROW_TILE` | unsigned integer; unset, empty, malformed, negative, or values other than 64/128/256 use shape selection (64 rows when M<1024, 128 when M<8192, otherwise 256); 64 retains the previous geometry | Override the number of output rows sharing each direct-Q4 64x32 activation tile for controlled 64/128/256-row ROCm WMMA A/B measurements. | [rocm/ds4_rocm_q4.cuh:1517](rocm/ds4_rocm_q4.cuh#L1517) |
+| `DS4_ROCM_Q8_DECODE_SHAREDX_64K` | sampled once; unset: enabled; present empty or exact 0: disabled; every other present value: enabled; effective only for one-token non-prequant Q8_0 matmul with 8192 < in_dim <= 16384 | Allows the ROCm shared-input Q8 decode kernel to use up to 64 KiB dynamic LDS for wide inputs; an unsupported/failed LDS launch automatically falls back to the regular kernel. | [rocm/ds4_rocm_runtime.cuh:4805](rocm/ds4_rocm_runtime.cuh#L4805) |
+| `DS4_ROCM_Q_STAGE_PROFILE` | presence/nonempty diagnostic; unset=off (path-valued DUMP names are noted by purpose) | Collect timing/profile diagnostics for rocm q stage profile. | [ds4.c:29284](ds4.c#L29284) |
+| `DS4_ROCM_REQUIRE_Q4_GROUPED_ATTN_A` | presence fail-closed assertion; also requests the candidate outside the caller-marked resident decode default; DISABLE remains authoritative and causes failure | Require grouped Q4 attention-A and fail instead of silently falling back. | [rocm/ds4_rocm_q4.cuh:870](rocm/ds4_rocm_q4.cuh#L870) |
+| `DS4_ROCM_REQUIRE_Q4_PREFILL_TILE8` | presence fail-closed assertion for eligible TILE8 calls | Require rocm require q4 prefill tile8 and fail instead of silently falling back. | [rocm/ds4_rocm_q4.cuh:452](rocm/ds4_rocm_q4.cuh#L452) |
+| `DS4_ROCM_REQUIRE_Q4_PREFILL_WMMA` | value-aware strict diagnostic assertion, not required for the automatic standalone/attention-output-A resident default; unset/0/false/no/off is off; empty or any other value requires every selected Q4 dense or attention-output projection to use direct-Q4 WMMA and is the only control that selects the numerically compounded attention-output B stage; unsupported shape/device, quality mode, DISABLE, or an SSD weight range without physical device residency fails before dispatch | Prevent a strict ROCm Q4 prefill WMMA kernel oracle from silently timing TILE8/TILE4; normal runtime controls keep attention-output B on Q8_K+TILE8. | [rocm/ds4_rocm_q4.cuh:1360](rocm/ds4_rocm_q4.cuh#L1360) |
+| `DS4_ROCM_STREAMING_DECODE_PREFILL_MAX` | primary nonempty value over the Metal alias; parsed by strtol when it has a numeric prefix (trailing text is accepted); <= 0 disables, values > UINT32_MAX clamp, no numeric prefix uses automatic default: 64 for Flash with uniform Q4_K/MXFP4 experts, 18 for other Pro/Flash, otherwise 0; the disable flag dominates | Sets the largest short, non-quality SSD-streaming prefill batch routed through the decode-style path instead of canonical layer-major prefill. | [ds4.c:31976](ds4.c#L31976) |
+| `DS4_ROCM_STREAMING_EXPERT_AUTO_PRELOAD_CAP` | primary nonempty value over the Metal alias; strict full-string strtoul; valid values > UINT32_MAX clamp, invalid uses 4096, and 0 means no cap (not disabled); when CLI preload is auto/0, unset defaults to cap 4096 except ROCm GLM52, where absent/empty disables automatic preload entirely | Caps the number of hot experts synchronously seeded into the SSD-streaming expert cache in automatic preload mode; an explicit CLI preload count bypasses this cap, and setting this variable opts ROCm GLM52 back into auto preload. | [ds4.c:21469](ds4.c#L21469) |
+| `DS4_ROCM_STREAMING_EXPERT_CACHE_VERBOSE` | presence flag; unset=off | Print verbose ROCm streaming expert-cache seed/load diagnostics. | [rocm/ds4_rocm_runtime.cuh:2904](rocm/ds4_rocm_runtime.cuh#L2904) |
+| `DS4_ROCM_STREAMING_EXPERT_HOTLIST` | Nonempty filesystem path; a nonempty ROCm value takes precedence, otherwise DS4_METAL_STREAMING_EXPERT_HOTLIST is a fallback. The file contains whitespace-separated layer expert hits rows; blank/comment lines are ignored, zero-hit rows skipped, malformed/open/read errors fail seeding. Unset/empty uses the built-in Pro/Flash/GLM52 hotlist. Effective only when non-cold SSD hotlist seeding is enabled and cache/preload budget is nonzero. | Select a custom ranked expert hotlist used to preseed the streaming resident expert cache before decode. | [ds4.c:21494](ds4.c#L21494) |
+| `DS4_ROCM_STREAMING_EXPERT_HOTLIST_PROFILE` | presence/nonempty diagnostic; unset=off (path-valued DUMP names are noted by purpose) | Collect timing/profile diagnostics for rocm streaming expert hotlist profile. | [ds4.c:32244](ds4.c#L32244) |
+| `DS4_ROCM_STREAMING_MAP_TRACE` | presence/nonempty diagnostic; unset=off (path-valued DUMP names are noted by purpose) | Emit trace diagnostics for rocm streaming map trace. | [ds4.c:42643](ds4.c#L42643) |
+| `DS4_ROCM_STREAMING_PREFILL_BATCH_SELECTED_ADDR_MAX` | primary nonempty value over the Metal alias; strtol accepts a numeric prefix; <= 0 returns 0, > UINT32_MAX clamps, invalid uses ROCm default UINT32_MAX for Pro/Flash/GLM52 and 0 otherwise | Sets the inclusive upper token-count bound for automatically using selected-expert address-table kernels during eligible non-quality SSD batch prefill; 0 disables automatic selection. | [ds4.c:18471](ds4.c#L18471) |
+| `DS4_ROCM_STREAMING_PREFILL_BATCH_SELECTED_ADDR_MIN` | primary nonempty value over the Metal alias; strtol accepts a numeric prefix; <= 0 returns 0, > UINT32_MAX clamps, invalid uses ROCm default 2 for Pro/Flash/GLM52 and 0 otherwise | Sets the inclusive lower token-count bound for automatically using selected-expert address-table kernels during eligible non-quality SSD batch prefill (the path independently requires more than one token). | [ds4.c:18494](ds4.c#L18494) |
+| `DS4_ROCM_STREAMING_PREFILL_CACHE_SEED_K` | primary nonempty value over the Metal alias; strict full-string strtoul; unset/empty/invalid: 1; 0 disables; positive values clamp to 64; ignored unless SSD streaming and DS4_ROCM_ENABLE_STREAMING_PREFILL_CACHE_SEED (or Metal alias) is present | Chooses how many trailing token router selections per layer are captured from prefill and used to seed the streaming expert cache afterward. | [ds4.c:21267](ds4.c#L21267) |
+| `DS4_ROCM_STREAMING_PREFILL_CACHE_SEED_PROFILE` | presence/nonempty diagnostic; unset=off (path-valued DUMP names are noted by purpose) | Collect timing/profile diagnostics for rocm streaming prefill cache seed profile. | [ds4.c:32153](ds4.c#L32153) |
+| `DS4_ROCM_STREAMING_PREFILL_LAYER_MADVISE_PROFILE` | presence/nonempty diagnostic; unset=off (path-valued DUMP names are noted by purpose) | Collect timing/profile diagnostics for rocm streaming prefill layer madvise profile. | [ds4.c:19609](ds4.c#L19609) |
+| `DS4_ROCM_STREAMING_PREFILL_LAYER_PAGEIN_NO_OVERLAP` | Pure presence flag: any defined value, including empty or "0", disables overlap. Default overlap is enabled only if this, PREPARE_NO_OVERLAP, DISABLE_*_PREPARE_OVERLAP, and DISABLE_*_PAGEIN_OVERLAP are all absent. The corresponding DS4_METAL name is an accepted fallback alias. In current code PAGEIN_NO_OVERLAP and PREPARE_NO_OVERLAP are exact synonyms. | Serialize SSD-streaming prefill layer page-in/preparation instead of overlapping preparation of upcoming layers. | [ds4.c:19316](ds4.c#L19316) |
+| `DS4_ROCM_STREAMING_PREFILL_LAYER_PAGEIN_PROFILE` | presence/nonempty diagnostic; unset=off (path-valued DUMP names are noted by purpose) | Collect timing/profile diagnostics for rocm streaming prefill layer pagein profile. | [ds4.c:19605](ds4.c#L19605) |
+| `DS4_ROCM_STREAMING_PREFILL_LAYER_PAGEIN_THREADS` | legacy fallback read only when DS4_ROCM_STREAMING_PREFILL_LAYER_PREPARE_THREADS and its Metal alias are absent/empty; strict full-string strtoul; unset/empty across both names: 8; invalid or 0: 1; values > 16 clamp to 16 | Sets worker count for full-layer SSD-prefill preparation (page touch, pread, readahead, or madvise) when the canonical PREPARE_THREADS control is not set. | [ds4.c:19274](ds4.c#L19274) |
+| `DS4_ROCM_STREAMING_PREFILL_LAYER_PREAD_PROFILE` | presence/nonempty diagnostic; unset=off (path-valued DUMP names are noted by purpose) | Collect timing/profile diagnostics for rocm streaming prefill layer pread profile. | [ds4.c:19607](ds4.c#L19607) |
+| `DS4_ROCM_STREAMING_PREFILL_LAYER_PREPARE_AHEAD` | primary nonempty value over the Metal alias; strict full-string strtoul; unset/empty: 1; invalid or 0: 1; values > 4 clamp to 4 | Sets how many future layer-preparation jobs may be queued concurrently while SSD-prefill preparation overlap is enabled. | [ds4.c:19328](ds4.c#L19328) |
+| `DS4_ROCM_STREAMING_PREFILL_LAYER_PREPARE_NO_OVERLAP` | Pure presence flag: any defined value, including empty or "0", disables overlap. Default overlap is enabled only if this, PAGEIN_NO_OVERLAP, DISABLE_*_PREPARE_OVERLAP, and DISABLE_*_PAGEIN_OVERLAP are all absent. The corresponding DS4_METAL name is an accepted fallback alias. In current code PREPARE_NO_OVERLAP and PAGEIN_NO_OVERLAP are exact synonyms. | Serialize SSD-streaming prefill layer preparation/page-in instead of overlapping preparation of upcoming layers. | [ds4.c:19314](ds4.c#L19314) |
+| `DS4_ROCM_STREAMING_PREFILL_LAYER_PREPARE_THREADS` | primary nonempty value over the Metal alias; strict full-string strtoul; unset/empty falls back to LAYER_PAGEIN_THREADS, then default 8; invalid or 0: 1; values > 16 clamp to 16 | Sets worker count used to split full-layer SSD-prefill page-touch, pread, readahead, or madvise preparation ranges. | [ds4.c:19270](ds4.c#L19270) |
+| `DS4_ROCM_STREAMING_PREFILL_LAYER_READAHEAD_PROFILE` | presence/nonempty diagnostic; unset=off (path-valued DUMP names are noted by purpose) | Collect timing/profile diagnostics for rocm streaming prefill layer readahead profile. | [ds4.c:19611](ds4.c#L19611) |
+| `DS4_ROCM_STREAMING_PREFILL_SELECTED_MADVISE_PROFILE` | presence/nonempty diagnostic; unset=off (path-valued DUMP names are noted by purpose) | Collect timing/profile diagnostics for rocm streaming prefill selected madvise profile. | [ds4.c:19355](ds4.c#L19355) |
+| `DS4_ROCM_STREAMING_PREFILL_SELECTED_MADVISE_THREADS` | legacy fallback read only for selected-expert madvise preparation when DS4_ROCM_STREAMING_PREFILL_SELECTED_PREPARE_THREADS and its Metal alias are absent/empty; strict full-string strtoul; if all selected controls are unset it inherits layer preparation threads (default 8); invalid or 0: 1; values > 16 clamp to 16 | Sets worker count for selected-expert madvise preparation under its legacy name; non-madvise selected page-in always uses one worker. | [ds4.c:19292](ds4.c#L19292) |
+| `DS4_ROCM_STREAMING_PREFILL_SELECTED_PAGEIN_PROFILE` | presence/nonempty diagnostic; unset=off (path-valued DUMP names are noted by purpose) | Collect timing/profile diagnostics for rocm streaming prefill selected pagein profile. | [ds4.c:19353](ds4.c#L19353) |
+| `DS4_ROCM_STREAMING_PREFILL_SELECTED_PREPARE_GAP` | primary nonempty value over the Metal alias; strict full-string strtoul; unset/empty/invalid: 0; values > 8 clamp to 8 | For selected-expert madvise preparation, merges selected expert runs separated by at most this many unselected expert IDs, trading broader hints for fewer ranges. | [ds4.c:19304](ds4.c#L19304) |
+| `DS4_ROCM_STREAMING_PREFILL_SELECTED_PREPARE_THREADS` | primary nonempty value over the Metal alias; strict full-string strtoul; for selected-expert madvise, unset/empty falls back to SELECTED_MADVISE_THREADS then layer preparation threads (default 8); invalid or 0: 1; values > 16 clamp to 16; non-madvise selected page-in ignores it and uses 1 | Sets worker count for selected-expert madvise preparation using the canonical control name. | [ds4.c:19288](ds4.c#L19288) |
+| `DS4_ROCM_STREAMING_PREFILL_SELECTED_PROFILE` | presence/nonempty diagnostic; unset=off (path-valued DUMP names are noted by purpose) | Collect timing/profile diagnostics for rocm streaming prefill selected profile. | [ds4.c:18905](ds4.c#L18905) |
+| `DS4_ROCM_STREAMING_PREFILL_SELECTED_READAHEAD_GAP` | primary nonempty value over the Metal alias; strict full-string strtoul; unset/empty/invalid: 0; values > 8 clamp to 8 | For selected-expert file readahead, merges selected expert runs separated by at most this many unselected expert IDs, reducing readahead calls at the cost of hinting extra weights. | [ds4.c:19977](ds4.c#L19977) |
+| `DS4_ROCM_STREAMING_PREFILL_SELECTED_READAHEAD_PROFILE` | presence/nonempty diagnostic; unset=off (path-valued DUMP names are noted by purpose) | Collect timing/profile diagnostics for rocm streaming prefill selected readahead profile. | [ds4.c:20062](ds4.c#L20062) |
+| `DS4_ROCM_STREAM_CACHE_LAYER_STATS` | presence flag; unset=off | Collect per-layer ROCm streaming cache statistics; also enables aggregate stats. | [rocm/ds4_rocm_runtime.cuh:390](rocm/ds4_rocm_runtime.cuh#L390) |
+| `DS4_ROCM_STREAM_CACHE_STATS` | presence flag; unset=off unless layer stats are enabled | Collect aggregate ROCm streaming cache statistics. | [rocm/ds4_rocm_runtime.cuh:398](rocm/ds4_rocm_runtime.cuh#L398) |
+| `DS4_ROCM_STREAM_EVICT_PAST_LAYERS_FIRST` | nonempty and not 0 enables; unset/empty/0=off | Prefer evicting cached experts from already-processed layers. | [rocm/ds4_rocm_runtime.cuh:406](rocm/ds4_rocm_runtime.cuh#L406) |
+| `DS4_ROCM_STREAM_FREE_RESERVE_GB` | integer 2..64 GiB; default 16 | Reserve unified-memory headroom while growing the ROCm expert cache. | [rocm/ds4_rocm_runtime.cuh:1526](rocm/ds4_rocm_runtime.cuh#L1526) |
+| `DS4_ROCM_STREAM_MODEL_CACHE_GB` | positive GiB integer; unset/invalid uses automatic streaming model cache limit | Cap cached streaming model spans. | [rocm/ds4_rocm_runtime.cuh:5464](rocm/ds4_rocm_runtime.cuh#L5464) |
+| `DS4_ROCM_STREAM_NO_DIRECT` | nonempty and not 0 disables direct reads; unset/empty/0 keeps direct I/O eligible | Force the buffered ROCm SSD-streaming read path. | [rocm/ds4_rocm_runtime.cuh:1932](rocm/ds4_rocm_runtime.cuh#L1932) |
+| `DS4_ROCM_STREAM_Q8_F16_CACHE_GB` | non-negative GiB integer; unset/invalid uses automatic Q8-F16 cache limit | Cap converted Q8-to-F16 weights in SSD mode. | [rocm/ds4_rocm_runtime.cuh:4859](rocm/ds4_rocm_runtime.cuh#L4859) |
+| `DS4_ROCM_STREAM_READ_PROFILE` | nonempty and not 0 enables; unset/empty/0=off | Print ROCm SSD-streaming read/locality statistics at exit. | [rocm/ds4_rocm_runtime.cuh:1918](rocm/ds4_rocm_runtime.cuh#L1918) |
+| `DS4_ROCM_STREAM_READ_WORKERS` | integer; default DS4_ROCM_STREAM_READ_DEFAULT_WORKERS; 0 coerces to 1; capped at compile-time max | Set parallel ROCm SSD read/upload workers. | [rocm/ds4_rocm_runtime.cuh:2077](rocm/ds4_rocm_runtime.cuh#L2077) |
+
+
+
+
+GLM shared (41)
+
+| Variable | Accepted value and default | Effect | Source |
+| --- | --- | --- | --- |
+| `DS4_GLM_ABLATE_COMBINE` | presence ablation; unset: exchange the local TP partial with the peer and add both halves; any presence including empty or 0 skips the exchange | Metal two-rank TP timing probe: doubles the local routed-MoE or split-attention partial instead of combining with the peer, deliberately producing invalid output; both ranks must set it or their exchange gates desynchronize. | [ds4.c:44181](ds4.c#L44181) |
+| `DS4_GLM_ATTN_NO_LORA_VEC2` | presence kill switch; unset leaves the eligible path available; any defined value, including empty or 0, disables it | Disable vectorized two-row LoRA accumulation in CUDA GLM indexed attention. | [ds4_cuda.cu:34176](ds4_cuda.cu#L34176) |
+| `DS4_GLM_ATTN_NO_SCORE_VEC2` | presence kill switch; unset leaves the eligible path available; any defined value, including empty or 0, disables it | Disable vectorized two-row score computation in CUDA GLM indexed attention. | [ds4_cuda.cu:34165](ds4_cuda.cu#L34165) |
+| `DS4_GLM_ATTN_NO_STAGED_DECODE` | presence kill switch; unset leaves the eligible path available; any defined value, including empty or 0, disables it | Disable staged CUDA GLM indexed-decode attention for large selected sets. | [ds4_cuda.cu:34214](ds4_cuda.cu#L34214) |
+| `DS4_GLM_DECODE_ABLATE` | cached substring list; default empty mask; recognized tokens are attn_out, attn_core, qpath, indexer, routed, shared, qklow; unknown text has no effect; matching stages are skipped and output is invalid | Skip selected GLM decode stages for timing attribution; generated output is invalid. | [ds4.c:44411](ds4.c#L44411) |
+| `DS4_GLM_DECODE_FLUSH_INTERVAL` | integer layers via atoi; default 4 for indexed decode and 32 otherwise; <=0/nonnumeric disables periodic flush; capped to layer count and forced to 0 for deferred completion | Set how often non-streaming GLM decode command work is flushed between layers. | [ds4.c:49818](ds4.c#L49818) |
+| `DS4_GLM_DISABLE_FLASH_PREFILL` | presence kill switch; unset leaves the eligible path available; any defined value, including empty or 0, disables it | Disable GLM Flash Attention prefill. | [ds4.c:45087](ds4.c#L45087) |
+| `DS4_GLM_DISABLE_STREAMING_TOKEN_PREFILL` | presence kill switch; unset leaves the eligible path available; any defined value, including empty or 0, disables it; either backend-specific ROCm/Metal alias also disables | Disable token-major GLM SSD-streaming prefill. | [ds4.c:49702](ds4.c#L49702) |
+| `DS4_GLM_FENCE_TRACE` | presence flag; unset is off; any defined value, including empty or 0, is on; normal eligibility still applies | Log fenced CUDA tier switches used by GLM multi-GPU execution. | [ds4_cuda.cu:7984](ds4_cuda.cu#L7984) |
+| `DS4_GLM_GEMM_TRACE` | presence flag; unset is off; any defined value, including empty or 0, is on; normal eligibility still applies | Measure and print CUDA GLM dequantization and cuBLAS GEMM timings. | [ds4_cuda.cu:19706](ds4_cuda.cu#L19706) |
+| `DS4_GLM_HIDDEN_DUMP` | nonempty filesystem path/prefix; unset/empty disables; writes final hidden row or per-layer files selected by DS4_GLM_HIDDEN_DUMP_LAYER | Dump GLM hidden-state rows for correctness isolation. | [ds4.c:38523](ds4.c#L38523) |
+| `DS4_GLM_HIDDEN_DUMP_LAYER` | selector; unset/empty = -1 (no per-layer dump, final hidden still dumped when path set); all = every layer; otherwise atoi result selects a layer, so invalid text selects layer 0 | Choose which GLM layer hidden states are dumped. | [ds4.c:38543](ds4.c#L38543) |
+| `DS4_GLM_KV_DUMP` | nonempty filesystem prefix; unset/empty disables; writes layer-0 lora and rope compact-cache files after sync | Dump layer-0 compact GLM KV cache data after prompt synchronization. | [ds4.c:63131](ds4.c#L63131) |
+| `DS4_GLM_LOGIT_DUMP` | nonempty filesystem path; unset/empty disables; dumps the first post-prefill logits vector once per process | Dump the first post-prefill GLM logits vector. | [ds4.c:38601](ds4.c#L38601) |
+| `DS4_GLM_MEMORY_GUARD` | guard is on by default; exact 0 or case-insensitive false/off/no disables it; any other value and unset keep it enabled | Control the pre-allocation GLM host/GPU memory safety guard. | [ds4.c:41989](ds4.c#L41989) |
+| `DS4_GLM_MEMORY_GUARD_FRACTION` | floating-point fraction; default 0.99; parsed numeric prefix is accepted, invalid/nonfinite falls back, values clamp to 0.50..1.00 | Set the fraction of detected memory usable by the GLM memory guard. | [ds4.c:42028](ds4.c#L42028) |
+| `DS4_GLM_MEMORY_GUARD_REPORT` | nonempty diagnostic flag; unset/empty is off; any nonempty value including 0 prints successful-admission accounting (refusals always report) | Print successful GLM memory-guard budget accounting. | [ds4.c:42068](ds4.c#L42068) |
+| `DS4_GLM_MEMORY_GUARD_RESERVE_GB` | floating-point GiB; dynamic default (normally 32, 24 on near-full 480..640 GiB hosts, possibly lower for resident ROCm slices); numeric prefixes accepted; invalid falls back; clamp 0..1024 | Set fixed headroom subtracted by the GLM memory guard. | [ds4.c:42046](ds4.c#L42046) |
+| `DS4_GLM_MOE_EXPERT_MAJOR` | presence selector; unset: off; any presence including empty or 0 requests the path only for n_tokens >= 16; the automatic tile-8 path takes precedence when enabled (normally n_tokens >= 128) | CUDA only: groups selected token/expert pairs by expert and uses expert-major Q2_K routed-MoE gate/up/down kernels to reuse expert weights; otherwise the normal token-major path is used. | [ds4_cuda.cu:35973](ds4_cuda.cu#L35973) |
+| `DS4_GLM_MOE_NO_DOWN_TILE8_EXACT` | presence kill switch; unset leaves the eligible path available; any defined value, including empty or 0, disables it | Disable the exact tile-8 CUDA GLM routed-MoE down projection. | [ds4_cuda.cu:36028](ds4_cuda.cu#L36028) |
+| `DS4_GLM_MOE_NO_EXPERT_TILE8` | presence kill switch; unset leaves the eligible path available; any defined value, including empty or 0, disables it | Disable automatic expert tile-8 CUDA GLM routed-MoE batching. | [ds4_cuda.cu:35971](ds4_cuda.cu#L35971) |
+| `DS4_GLM_MOE_NO_LOCAL_BATCH_IO` | presence kill switch; unset leaves the eligible path available; any defined value, including empty or 0, disables it | Disable device-local batch scratch I/O for large CUDA GLM MoE batches. | [ds4_cuda.cu:35942](ds4_cuda.cu#L35942) |
+| `DS4_GLM_MOE_SCALAR` | presence rollback; unset: use optimized warp kernels; any presence including empty or 0 selects scalar baseline kernels where an earlier expert-tile/expert-major path does not return; the special two-token MTP gate/up kernel still takes precedence | CUDA only: forces the baseline scalar Q2_K routed-MoE gate/up and down implementations for A/B or correctness testing (for two-token MTP, only the down half is forced). | [ds4_cuda.cu:36154](ds4_cuda.cu#L36154) |
+| `DS4_GLM_MOE_SCRATCH_TIER0` | presence placement override; unset: allocate xq/midq quantization scratch on the current logical tier; any presence including empty or 0 allocates it on logical tier 0 | CUDA only: pins the routed-MoE xq_scratch and midq_scratch allocations to GPU tier 0 for multi-tier placement experiments; other MoE scratch remains on the current tier. | [ds4_cuda.cu:35918](ds4_cuda.cu#L35918) |
+| `DS4_GLM_MTP_NO_ATTN_TOK2` | presence kill switch; unset leaves the eligible path available; any defined value, including empty or 0, disables it | Disable the exact two-token CUDA GLM MTP attention kernel. | [ds4_cuda.cu:34168](ds4_cuda.cu#L34168) |
+| `DS4_GLM_MTP_NO_MOE_TOK2` | presence kill switch; unset leaves the eligible path available; any defined value, including empty or 0, disables it | Disable the exact two-token CUDA GLM MTP routed-MoE kernel. | [ds4_cuda.cu:36140](ds4_cuda.cu#L36140) |
+| `DS4_GLM_MTP_NO_SHARED_TOK2` | presence kill switch; unset leaves the eligible path available; any defined value, including empty or 0, disables it | Disable the exact two-token CUDA GLM MTP shared-FFN kernel. | [ds4_cuda.cu:37940](ds4_cuda.cu#L37940) |
+| `DS4_GLM_MTP_PROBE` | presence flag; unset is off; any defined value, including empty or 0, is on; its second call site also rejects the normal batching path | Run the GLM next-N/MTP acceptance quality-and-timing probe without changing output and force probe-compatible scheduling. | [ds4.c:64959](ds4.c#L64959) |
+| `DS4_GLM_PREFILL_TRUNC` | nonempty value parsed by atoi (leading whitespace/sign accepted and trailing junk ignored); effective only when the resulting int is > 0 and < the current prompt length; unset/empty or a result <= 0 or >= prompt length leaves the prompt unchanged | GPU GLM debug hook: truncates the prompt before prefill/checkpoint handling so dumped prefill logits can be aligned with a CPU first-token reference. | [ds4.c:63270](ds4.c#L63270) |
+| `DS4_GLM_RESUME_PREFILL_MIN` | integer suffix tokens, non-ROCm builds only; default 4; parsed numeric prefixes accepted; <=0 maps to UINT32_MAX and effectively disables batched resume; ROCm build ignores it and stays at 4 | Set the suffix-length crossover from token decode to batched resumed prefill. | [ds4.c:38434](ds4.c#L38434) |
+| `DS4_GLM_ROUTER_SCALAR` | presence rollback; unset: use the 256-thread parallel router when n_expert <= 256 (the scalar path is already automatic above 256); any presence including empty or 0 forces the scalar path | CUDA only: selects the one-active-thread-per-token sigmoid/top-k router kernel instead of the parallel shared-memory reduction, for A/B or correctness testing. | [ds4_cuda.cu:36390](ds4_cuda.cu#L36390) |
+| `DS4_GLM_SHARED_SPLIT` | presence rollback; unset: use the fused one-token shared-expert Q8_0 gate+up+SwiGLU kernel when its shape/buffers are eligible; any presence including empty or 0 skips that fused one-token path; the earlier two-token MTP-specialized path is unaffected | CUDA only: forces shared-expert gate and up through two separate Q8_0 matmuls followed by a separate SwiGLU operation for one-token decode. | [ds4_cuda.cu:37966](ds4_cuda.cu#L37966) |
+| `DS4_GLM_STREAMING_DECODE_FULL_LAYER_MAP` | presence compatibility alias; unset: automatic mapping; any presence including empty or 0 independently forces full-layer mapping, equivalent to the backend-specific DS4_ROCM_GLM_STREAMING_DECODE_FULL_LAYER_MAP or DS4_METAL_GLM_STREAMING_DECODE_FULL_LAYER_MAP control | Backend-neutral alias for supported GLM SSD streaming (Metal/ROCm): maps every tensor in each decode layer instead of using the decode-only map that can omit routed experts served by the expert cache; layers that already require a full map are unchanged. | [ds4.c:42617](ds4.c#L42617) |
+| `DS4_GLM_STREAMING_DECODE_SYNC_EACH_LAYER` | ROCm-only third-priority legacy value: a nonempty DS4_ROCM_GLM_STREAMING_DECODE_SYNC_EACH_LAYER wins, otherwise a nonempty DS4_METAL_GLM_STREAMING_DECODE_SYNC_EACH_LAYER wins, otherwise this name is read; nonempty values are true except exact 0 or case-insensitive false/off/no; unset/empty: false; non-ROCm builds always return true and ignore this name | On ROCm non-static GLM SSD decode, opts into ending/synchronizing commands after token mapping and after every layer; the default keeps ordered work alive across layer mappings. Static-map decode bypasses this control. | [ds4.c:49781](ds4.c#L49781) |
+| `DS4_GLM_STREAMING_PREFILL_SYNC_EACH_LAYER` | ROCm-only third-priority legacy value: a nonempty DS4_ROCM_GLM_STREAMING_PREFILL_SYNC_EACH_LAYER wins, otherwise a nonempty DS4_METAL_GLM_STREAMING_PREFILL_SYNC_EACH_LAYER wins, otherwise this name is read; nonempty values are true except exact 0 or case-insensitive false/off/no; unset/empty: false for compact prefill; full-layer prefill and non-ROCm builds always synchronize and ignore this name | On ROCm compact GLM SSD prefill, opts into ending/synchronizing commands at every layer boundary; the default carries ordered work across mappings, while full-layer expert-cache prefill always retains the boundary. | [ds4.c:42397](ds4.c#L42397) |
+| `DS4_GLM_STREAMING_TOKEN_PREFILL_MAX` | unsigned token limit; backend-specific ROCm/Metal variable takes precedence, generic is fallback; default 0 on ROCm and 64 otherwise; invalid/overflow falls back, numeric prefixes accepted; 0 disables token-major streaming prefill | Set the largest SSD-streaming prefill handled by the token-major decode-like path. | [ds4.c:49684](ds4.c#L49684) |
+| `DS4_GLM_SYNC_TRACE` | presence flag; unset is off; any defined value, including empty or 0, is on; normal eligibility still applies | Log GLM checkpoint/resume and dense-versus-indexed prefill decisions. | [ds4.c:63368](ds4.c#L63368) |
+| `DS4_GLM_TP_DEBUG` | presence flag; unset is off; any defined value, including empty or 0, is on; normal eligibility still applies | Print CUDA/GLM tensor-parallel dispatch, gate, selected-ID, and failure diagnostics. | [ds4.c:44083](ds4.c#L44083) |
+| `DS4_GLM_TP_EXACT_PREFILL_MAX` | integer suffix limit via atoi cast to uint32; default 64; nonnumeric becomes 0; negative values wrap to a very large unsigned limit | Set the maximum two-way TP suffix that uses exact token-by-token prefill. | [ds4.c:63310](ds4.c#L63310) |
+| `DS4_GLM_TP_HEAD_SPLIT_MIN` | cached integer token threshold via atoi; default 64; negative values clamp to 0, nonnumeric becomes 0; 0 admits all otherwise-eligible batches | Set the minimum batch size for GLM tensor-parallel output-head splitting. | [ds4.c:38513](ds4.c#L38513) |
+| `DS4_GLM_VALUE_NO_TILE16` | presence kill switch; unset leaves the eligible path available; any defined value, including empty or 0, disables it | Disable the CUDA GLM 16-token tiled value-projection kernel. | [ds4_cuda.cu:36806](ds4_cuda.cu#L36806) |
+
+
+
+
+Distributed (15)
+
+| Variable | Accepted value and default | Effect | Source |
+| --- | --- | --- | --- |
+| `DS4_DIST_CONNECT_BIND_HOST` | non-empty string; unset/empty means no local bind constraint | Bind outgoing distributed connections to a local host/address. | [ds4_distributed.c:1332](ds4_distributed.c#L1332) |
+| `DS4_DIST_CONNECT_BIND_IF` | non-empty string; unset/empty means no local bind constraint | Bind outgoing distributed connections to a network interface. | [ds4_distributed.c:1334](ds4_distributed.c#L1334) |
+| `DS4_DIST_CONNECT_TRACE` | presence flag; unset=off, any set value=on | Emit trace diagnostics for dist connect trace. | [ds4_distributed.c:1112](ds4_distributed.c#L1112) |
+| `DS4_DIST_DECODE_PROFILE` | presence flag; unset=off, any set value=on | Collect timing/profile diagnostics for dist decode profile. | [ds4_distributed.c:753](ds4_distributed.c#L753) |
+| `DS4_DIST_DISABLE_PREFILL_ACK_ONLY` | presence flag; unset keeps optimized/default behavior, any set value disables it | Disable/roll back dist disable prefill ack only. | [ds4_distributed.c:3692](ds4_distributed.c#L3692) |
+| `DS4_DIST_DISABLE_PREFILL_PIPELINE` | presence flag; unset keeps optimized/default behavior, any set value disables it | Disable/roll back dist disable prefill pipeline. | [ds4_distributed.c:3427](ds4_distributed.c#L3427) |
+| `DS4_DIST_DISABLE_WORKER_PREFETCH` | presence flag; unset keeps optimized/default behavior, any set value disables it | Disable/roll back dist disable worker prefetch. | [ds4_distributed.c:7878](ds4_distributed.c#L7878) |
+| `DS4_DIST_PREFILL_CHUNK` | positive integer; unset/0 uses session prefill capacity; explicit value may not exceed capacity | Set distributed prefill chunk size. | [ds4_distributed.c:3455](ds4_distributed.c#L3455) |
+| `DS4_DIST_PREFILL_SEND_DEPTH` | integer 1..8; default 2; capped to chunk count | Set coordinator prefill sender queue depth. | [ds4_distributed.c:470](ds4_distributed.c#L470) |
+| `DS4_DIST_PREFILL_WINDOW` | positive integer <=64; auto default remote stages+2 clamped 2..8 and chunk count | Set maximum distributed prefill chunks in flight. | [ds4_distributed.c:3485](ds4_distributed.c#L3485) |
+| `DS4_DIST_SOCKET_BUFFER_MB` | integer 0..512 MiB; default 128; 0 disables socket buffer override | Set TCP send/receive buffer sizes. | [ds4_distributed.c:712](ds4_distributed.c#L712) |
+| `DS4_DIST_SOCKET_RECV_TIMEOUT_SEC` | Nonempty base-10 integer parsed completely; valid range 1..3600 seconds. Unset, empty, partially parsed, or out-of-range values install no SO_RCVTIMEO at all. | Optionally bound blocking receives on distributed TCP sockets; the default deliberately permits indefinitely idle control connections during separate KV transfers. | [ds4_distributed.c:1049](ds4_distributed.c#L1049) |
+| `DS4_DIST_SOCKET_TIMEOUT_SEC` | Nonempty base-10 integer parsed completely; valid range 1..3600 seconds. Default 60 seconds for unset, empty, partially parsed, or out-of-range values. | Set SO_SNDTIMEO on distributed TCP sockets so blocked coordinator/worker sends eventually fail. | [ds4_distributed.c:1032](ds4_distributed.c#L1032) |
+| `DS4_DIST_WORKER_FORWARD_WINDOW` | integer 1..64; default 4 | Set worker forward-results window. | [ds4_distributed.c:740](ds4_distributed.c#L740) |
+| `DS4_DIST_WORKER_PREFETCH_DEPTH` | integer 1..8; default 2 | Set worker input-prefetch queue depth. | [ds4_distributed.c:726](ds4_distributed.c#L726) |
+
+
+
+
+DSpark shared (24)
+
+| Variable | Accepted value and default | Effect | Source |
+| --- | --- | --- | --- |
+| `DS4_DSPARK_CACHE_RESERVE_GB` | integer GiB via atoi; default 4.5 GiB; values 1..32 replace it, all other values fall back; decimal/trailing text is truncated/accepted by atoi | Reserve VRAM on DSpark support-cache tiers before packing support-model tensors. | [ds4.c:59770](ds4.c#L59770) |
+| `DS4_DSPARK_DISABLE_FINAL_OUTPUT_ALIAS` | presence kill switch; unset leaves the eligible path available; any defined value, including empty or 0, disables it | Disable aliasing the final DSpark stage output to the next-stage buffer and use an explicit copy. | [ds4.c:33784](ds4.c#L33784) |
+| `DS4_DSPARK_DISABLE_FUSED_CPU_MARKOV_ARGMAX` | cached value-aware kill switch; default off; nonempty value other than exact 0 disables; false/off also disable because only 0 is recognized as false | Disable the fused CPU Markov-bias plus argmax implementation. | [ds4.c:34487](ds4.c#L34487) |
+| `DS4_DSPARK_DISABLE_REUSE_CONFIDENCE0_MARKOV` | cached value-aware kill switch; default off; nonempty value other than exact 0 disables; false/off also disable because only 0 is recognized as false | Disable reuse of the first confidence score during Markov proposal. | [ds4.c:34496](ds4.c#L34496) |
+| `DS4_DSPARK_DISABLE_VERIFY_SELECTED_PROFILE` | presence kill switch; unset leaves the eligible path available; any defined value, including empty or 0, disables it | Override and disable the selected-expert verifier profiler. | [ds4.c:36660](ds4.c#L36660) |
+| `DS4_DSPARK_EXEC_TIER` | integer tier via atoi; default is placement/TP free-VRAM heuristic; valid 0..n_gpus-1 overrides; invalid numeric range falls back, but nonnumeric text becomes tier 0 | Choose the GPU tier that executes and primarily caches the DSpark support model. | [ds4.c:59743](ds4.c#L59743) |
+| `DS4_DSPARK_FAKE_ARGMAX_PROPOSAL` | nonempty boolean; unset/empty or exact 0: off; every other nonempty value enables, but only while DSpark itself is enabled | If the real DSpark proposer produced no draft, installs a one-token fallback proposal equal to the argmax of the current target logits; debug/test mode also selects the non-fused stage-0 setup path. | [ds4.c:64278](ds4.c#L64278) |
+| `DS4_DSPARK_LOW_MEMORY_PREFILL_CHUNK` | unsigned integer rows; default 128; 0 disables the low-memory policy; invalid/overflow falls back, numeric prefixes are accepted; only consulted for Metal SSD+DSpark on <=24 GiB hosts without an explicit chunk | Set the automatic low-memory Metal prefill chunk for SSD-streamed DSpark. | [ds4.c:60714](ds4.c#L60714) |
+| `DS4_DSPARK_NO_GPU_MARKOV` | presence kill switch; unset leaves the eligible path available; any defined value, including empty or 0, disables it | Disable GPU Markov bias/argmax and the fully device-resident proposal path. | [ds4.c:34711](ds4.c#L34711) |
+| `DS4_DSPARK_NO_MARKOV` | cached value-aware kill switch; default off; nonempty value other than exact 0 disables Markov bias; false/off also disable | Disable Markov bias in DSpark proposal generation. | [ds4.c:34478](ds4.c#L34478) |
+| `DS4_DSPARK_PROBE` | nonempty-string diagnostic; unset/empty is off, any nonempty value including 0 is on | Log DSpark proposal/probe diagnostics. | [ds4.c:64275](ds4.c#L64275) |
+| `DS4_DSPARK_PROP_PROFILE` | presence flag; unset is off; any defined value, including empty or 0, is on; normal eligibility still applies | Print fine-grained timings for DSpark proposal setup. | [ds4.c:32959](ds4.c#L32959) |
+| `DS4_DSPARK_SPEC_LOG` | presence flag; unset is off; any defined value, including empty or 0, is on; normal eligibility still applies | Log speculative proposal, verification, acceptance, and fallback decisions. | [ds4.c:66596](ds4.c#L66596) |
+| `DS4_DSPARK_SSD_VERIFY_BLOCK_MAX` | unsigned integer rows; default/fallback 0 means automatic policy; numeric prefixes accepted; used both as verifier cap and as an exact-2 proposer-policy discriminator | Cap speculative rows verified from SSD and influence exact-2 proposal sizing. | [ds4.c:52380](ds4.c#L52380) |
+| `DS4_DSPARK_STAGE_PROFILE` | presence flag; unset is off; any defined value, including empty or 0, is on; DS4_DSPARK_STAGE_PROFILE_STAGE must also match | Profile DSpark support stages with command-boundary timings. | [ds4.c:33416](ds4.c#L33416) |
+| `DS4_DSPARK_STAGE_PROFILE_STAGE` | selector subordinate to DS4_DSPARK_STAGE_PROFILE; unset/empty: match every stage; otherwise strtoul base 10 must consume the whole value, fit uint32_t, and equal the current stage; invalid/out-of-range values match no stage | Restricts DSpark stage-boundary timing output to one stage; it does not enable profiling by itself. | [ds4.c:33417](ds4.c#L33417) |
+| `DS4_DSPARK_STATS` | value-aware flag; default off; nonempty value other than exact 0 enables; false/off are treated as enabled | Collect and print aggregate DSpark runtime statistics. | [ds4.c:61607](ds4.c#L61607) |
+| `DS4_DSPARK_VERIFY_CACHE` | presence diagnostic; unset: off; any presence including empty or 0 enables on each support-cache installation | CUDA only: copies every installed nonempty DSpark/support-cache range back to the host, byte-compares it with its source, and logs each mismatch plus a bad-count summary without changing the install result. | [ds4_cuda.cu:8257](ds4_cuda.cu#L8257) |
+| `DS4_DSPARK_VERIFY_HEAD_NO_TP` | presence rollback; unset: allow eligible CUDA output tensor parallelism; any presence including empty or 0 removes the TP path from eligibility | CUDA only: forces the DSpark speculative batched vocabulary head away from output-TP for correctness isolation; under CUDA TP+EP the attempt fails instead of using unavailable full output weights. | [ds4.c:26641](ds4.c#L26641) |
+| `DS4_DSPARK_VERIFY_NONCAUSAL` | presence diagnostic sampled once after the first successfully submitted CUDA noncausal-attention kernel; unset: verify 0 calls; any presence including empty or 0: verify that call and the next 2 | CUDA only: synchronizes and reads back Q/KV/output, computes the DSpark noncausal attention CPU reference, and logs max absolute/relative error; it reports only and does not fail the operation. | [ds4_cuda.cu:21736](ds4_cuda.cu#L21736) |
+| `DS4_DSPARK_VERIFY_PROFILE` | cached presence diagnostic; unset is off; any defined value including empty/0 profiles only the first eligible verifier invocation | Profile one full DSpark target-verifier invocation layer by layer. | [ds4.c:36757](ds4.c#L36757) |
+| `DS4_DSPARK_VERIFY_SELECTED_PROFILE` | presence flag; unset is off; any defined value, including empty or 0, enables unless DS4_DSPARK_DISABLE_VERIFY_SELECTED_PROFILE is also present (disable wins) | Profile selected-expert streaming inside the DSpark verifier. | [ds4.c:36659](ds4.c#L36659) |
+| `DS4_DSPARK_VERIFY_SPLIT_HEAD` | nonempty boolean with inverted default; unset/empty or exact 0: fused head; every other nonempty value: split head | Runs the DSpark suffix verifier output head and top-1 reduction in a separate GPU command section after the layer loop, for timing/correctness isolation; default keeps them fused into the layer command section. | [ds4.c:36725](ds4.c#L36725) |
+| `DS4_DSPARK_VERIFY_TOPS_CHECK` | presence flag; unset is off; any defined value, including empty or 0, is on; normal eligibility still applies | Read back verifier logits and compare GPU top IDs with CPU argmax. | [ds4.c:36873](ds4.c#L36873) |
+
+
+
+
+General and shared (77)
+
+| Variable | Accepted value and default | Effect | Source |
+| --- | --- | --- | --- |
+| `DS4_BATCHED_FFN` | Pure presence flag: any defined value, including empty or "0", enables. Unset leaves the default shared-expert-batched FFN path (or its configured fallback). It is read only by CPU layer-major prefill and takes precedence over shared-batch and token-parallel FFN choices. | Run the complete CPU prefill FFN in chunks through layer_ffn_batch instead of the default shared-expert-only batched path. | [ds4.c:14411](ds4.c#L14411) |
+| `DS4_BATCHED_ROPE_MAX` | Nonempty value parsed by strtol without full-string validation; integers 0..65536 are accepted, otherwise default 4096. Zero disables batched RoPE for every nonempty prompt. Effective only when prefix batch attention is selected and DS4_NO_BATCHED_ROPE is absent. | Set the largest CPU prefix-prefill token batch that applies RoPE and inverse RoPE with the batched kernels. | [ds4.c:13911](ds4.c#L13911) |
+| `DS4_BENCH_DISABLE_SNAPSHOT` | presence flag; unset allows snapshots for eligible frontiers | Disable benchmark state snapshots. | [ds4_bench.c:709](ds4_bench.c#L709) |
+| `DS4_BENCH_FORCE_SNAPSHOT` | presence flag; unset obeys the normal size/eligibility checks | Force benchmark state snapshots despite the normal limit. | [ds4_bench.c:712](ds4_bench.c#L712) |
+| `DS4_BENCH_SNAPSHOT_MAX_BYTES` | unsigned bytes or unlimited/inf; default DS4_BENCH_DEFAULT_SNAPSHOT_MAX_BYTES | Limit session snapshot size during benchmark sweeps. | [ds4_bench.c:70](ds4_bench.c#L70) |
+| `DS4_CHROME` | executable path; unset auto-detects Chrome/Chromium via standard paths and PATH | Select the browser executable used by web tooling. | [ds4_web.c:1014](ds4_web.c#L1014) |
+| `DS4_CLI_FORCE_SESSION` | Pure presence flag: any defined value, including empty or "0", forces the session path. Unset uses the session path only for distributed coordinators, TP leaders, temperature>0, or MTP depth>1; otherwise the CLI calls direct argmax generation. | Force ordinary CLI generation through run_sampled_generation/session APIs so single-node validation follows the same stateful path as TP/distributed runs. | [ds4_cli.c:1226](ds4_cli.c#L1226) |
+| `DS4_CPU_DISABLE_UNROLLED_ARGMAX` | presence rollback flag; unset keeps optimized/default path | Disable/roll back cpu disable unrolled argmax. | [ds4.c:41075](ds4.c#L41075) |
+| `DS4_CPU_DUMP_LOGITS` | filesystem path; unset disables read/write | Dump or select diagnostic data for cpu dump logits. | [ds4.c:39086](ds4.c#L39086) |
+| `DS4_CPU_DUMP_PREFILL_LOGITS` | filesystem path; unset disables read/write | Dump or select diagnostic data for cpu dump prefill logits. | [ds4.c:41606](ds4.c#L41606) |
+| `DS4_DECODE_PROFILE_DETAIL` | presence flag; unset=off | Print per-stage timing for the single-token CPU FFN path. | [ds4.c:12209](ds4.c#L12209) |
+| `DS4_DISABLE_GREEDY_TOP1_READBACK` | presence rollback; unset uses device top-1 plus a 4-byte readback for eligible single-tier greedy generation, including SSD streaming; any defined value including empty or 0 restores full-logits readback and CPU argmax | Restore the legacy per-token full-logits host readback for greedy generation A/B and emergency rollback. | [ds4.c:51964](ds4.c#L51964) |
+| `DS4_EXPERT_HOTLIST` | nonempty filesystem path; unset=off; currently Metal-only | Load an expert hotlist for Metal expert profiling/streaming. | [ds4.c:60637](ds4.c#L60637) |
+| `DS4_EXPERT_PROFILE` | presence diagnostic flag; unset=off | Collect timing/profile diagnostics for expert profile. | [ds4.c:60635](ds4.c#L60635) |
+| `DS4_FORCE_CUDA_PEER` | presence flag read once at CUDA init; unset uses automatic transfer selection; any defined value including 0 enables | Force cross-device transfers through cudaMemcpyPeerAsync for diagnostics. | [ds4_cuda.cu:364](ds4_cuda.cu#L364) |
+| `DS4_FORCE_HOST_BOUNCE` | presence flag read once at CUDA init; unset uses automatic transfer selection; any defined value including 0 enables | Force cross-device transfers through pinned host bounce buffers for diagnostics. | [ds4_cuda.cu:365](ds4_cuda.cu#L365) |
+| `DS4_LOCK_FILE` | path string; default /tmp/ds4.lock | Override the single-instance lock file. | [ds4.c:51999](ds4.c#L51999) |
+| `DS4_MMID_CASE1` | boolean-ish cached flag; default on; a value starting with 0 disables | Disable the single-expert MM-IDs specialized fast path for comparison. | [cuda/mmq/mmid.cu:290](cuda/mmq/mmid.cu#L290) |
+| `DS4_MMID_LARGE` | boolean-ish cached flag; default on; a value starting with 0 disables | Control the large-N global-memory MM-IDs path used beyond shared-memory capacity. | [cuda/mmq/mmid.cu:245](cuda/mmq/mmid.cu#L245) |
+| `DS4_MMQ_D2R` | boolean-ish cached flag; default on; a value starting with 0 disables | Control the direct-to-register Q2_K MoE down path. | [cuda/mmq/ds4_mmq.cu:525](cuda/mmq/ds4_mmq.cu#L525) |
+| `DS4_MMQ_D2R_IQ2` | boolean-ish cached flag; default on; a value starting with 0 disables | Control the direct-to-register IQ2 MoE gate/up path. | [cuda/mmq/ds4_mmq.cu:534](cuda/mmq/ds4_mmq.cu#L534) |
+| `DS4_MMQ_D2R_MIN_COLS` | positive integer; default 1024; invalid or nonpositive input restores the default | Set the minimum output-column count for the MMQ direct-to-register path. | [cuda/mmq/ds4_mmq.cu:629](cuda/mmq/ds4_mmq.cu#L629) |
+| `DS4_MMQ_D2R_STATS` | exact 1 enables; unset or every other value disables; cached and synchronizes the stream | Print partial-tile fill telemetry for the direct-to-register MMQ kernels. | [cuda/mmq/ds4_mmq_d2r.cu:33](cuda/mmq/ds4_mmq_d2r.cu#L33) |
+| `DS4_MMQ_DENSE_D2R` | boolean-ish flag; default on; exact 0 disables | Control the eligible aligned-Q8 dense prefill direct-to-register path. | [ds4_cuda.cu:19567](ds4_cuda.cu#L19567) |
+| `DS4_MMQ_NO_YIND` | presence rollback; unset keeps Y-indirect staging; any defined value including 0 disables it | Restore slot-gathered MoE gate/up activation quantization. | [cuda/mmq/ds4_mmq.cu:609](cuda/mmq/ds4_mmq.cu#L609) |
+| `DS4_MMQ_OUT_MEMSET` | exact 1 enables; unset or every other value disables; cached | Restore blanket MMQ output-buffer zeroing for diagnostics. | [cuda/mmq/ds4_mmq.cu:552](cuda/mmq/ds4_mmq.cu#L552) |
+| `DS4_MMQ_YBUF_MEMSET` | unset or 0 disables; 1 zero-fills; a value starting with p or P poison-fills with 0xFF | Control MMQ Q8_1 activation-staging initialization and its poison oracle. | [cuda/mmq/ds4_mmq.cu:578](cuda/mmq/ds4_mmq.cu#L578) |
+| `DS4_MMQ_YIND_VERIFY` | presence diagnostic; unset is off; any defined value including 0 enables | Byte-compare Y-indirect and slot-gathered MoE activation buffers. | [cuda/mmq/ds4_mmq.cu:620](cuda/mmq/ds4_mmq.cu#L620) |
+| `DS4_MOE_RECORD_SELECTED_HOTLIST` | nonempty output path; unset=off | Record per-layer selected-expert hit counts to a Metal hotlist file. | [ds4_metal.m:1741](ds4_metal.m#L1741) |
+| `DS4_MOE_RECORD_SELECTED_HOTLIST_FRESH` | presence flag; only relevant with HOTLIST; overrides MERGE | Start the selected-expert hotlist from empty state. | [ds4_metal.m:1642](ds4_metal.m#L1642) |
+| `DS4_MOE_RECORD_SELECTED_HOTLIST_MERGE` | presence flag; active only when FRESH is absent | Merge an existing selected-expert hotlist before recording. | [ds4_metal.m:1641](ds4_metal.m#L1641) |
+| `DS4_MOE_RECORD_SELECTED_IDS` | nonempty output path; unset=off | Record routed-MoE six-expert selections; also disables incompatible optimized paths. | [ds4.c:65290](ds4.c#L65290) |
+| `DS4_MOE_REPLAY_SELECTED_IDS` | nonempty input path; unset=off | Replay routed-MoE six-expert selections; also disables incompatible optimized paths. | [ds4.c:25308](ds4.c#L25308) |
+| `DS4_MTP_BATCH_VERIFY` | Pure presence flag: any defined value, including empty or "0", suppresses the exact two-row decode verifier. Unset selects exact decode-2 when draft_n==2 and either strict mode is active or the build is ROCm; other cases already use the generic verifier. | Diagnostic rollback from the exact Q8/one-token-equivalent MTP decode-2 verifier to the generic microbatch verifier. | [ds4.c:71021](ds4.c#L71021) |
+| `DS4_MTP_CAPTURE_PREFIX1` | Pure presence flag. In the generic verifier with exactly two drafts it enables prefix-1 state capture under strict mode; non-strict mode already captures prefix-1 without the variable. Unset under strict mode instead snapshots and replays a partial acceptance. | Let a one-of-two MTP partial acceptance commit the verifier's captured prefix directly, avoiding an exact one-token replay. | [ds4.c:71134](ds4.c#L71134) |
+| `DS4_MTP_CONF_LOG` | Pure presence flag; default off. It forces materialization of full draft logits, computes the top-2 margin, and after a successful generic microbatch verification prints drafted/committed counts, top candidates, margin, target-next and draft-next. Exact decode-2 success does not emit that generic log line. | Inspect MTP draft confidence and compare the recursive draft token with the target verifier result. | [ds4.c:70900](ds4.c#L70900) |
+| `DS4_MTP_EXACT_REPLAY` | Pure presence flag; default off. In the generic microbatch verifier it forces a pre-verifier frontier snapshot; after verification the snapshot is restored and every accepted draft is decoded sequentially to rebuild exact final state/logits. | Validate MTP acceptance while committing through the normal one-token decode path rather than retaining batched-verifier state. | [ds4.c:71139](ds4.c#L71139) |
+| `DS4_MTP_FORCE_SNAPSHOT` | Pure presence flag; default off. It forces a speculative-frontier snapshot before the generic verifier regardless of draft count or prefix-capture mode; it does not by itself force restoration or replay after a successful full acceptance. | Measure/debug snapshot behavior and guarantee a restorable pre-verifier frontier for generic MTP verification. | [ds4.c:71143](ds4.c#L71143) |
+| `DS4_MTP_FULL_LOGITS` | Pure presence flag; default off. When set, legacy and recursive MTP draft calls write the full vocabulary logits to s->mtp_logits; unset permits the faster top-token-only output unless confidence/margin logic independently needs logits. | Force full MTP draft-logit materialization for correctness comparison, inspection, or downstream confidence calculations. | [ds4.c:64260](ds4.c#L64260) |
+| `DS4_MTP_MIN_MARGIN` | non-negative float; default engine --mtp-margin value | Set confidence margin threshold for speculative MTP verification. | [ds4.c:70893](ds4.c#L70893) |
+| `DS4_MTP_PROBE` | Pure presence flag; default off. For legacy MTP it prepares drafts even when configured depth<=1, compares the previous draft with the next committed token, and prints cumulative hit counts/failures; generated output is unchanged. | Measure legacy MTP next-token draft accuracy without enabling speculative acceptance. | [ds4.c:64990](ds4.c#L64990) |
+| `DS4_MTP_SPEC_DISABLE` | Pure presence flag: any defined value, including empty or "0", disables MTP speculative argmax in CLI/chat/server loops. Unset permits it for greedy temperature<=0 generation with draft depth>1; unrelated split-KV speculation can still be independently requested. | Fall back from MTP multi-token speculative evaluation to normal one-token session evaluation. | [ds4_cli.c:580](ds4_cli.c#L580) |
+| `DS4_MTP_SPEC_LOG` | Pure presence flag; default off. It only emits diagnostics for first-draft misses, exact/generic verifier failures and sequential fallback misses/acceptance outcomes; it does not select a verifier. | Trace why MTP drafts were accepted, partially accepted, rejected, or sent to sequential fallback. | [ds4.c:70916](ds4.c#L70916) |
+| `DS4_MTP_STRICT` | Pure presence flag; engine quality mode also enables strictness automatically. Strict mode skips the non-strict low-margin shortcut, selects exact decode-2 for two drafts unless DS4_MTP_BATCH_VERIFY is set, and disables default prefix-1 capture unless explicitly restored. | Force the exact/quality-oriented MTP verification policy on otherwise non-quality runs. | [ds4.c:70891](ds4.c#L70891) |
+| `DS4_MTP_TIMING` | Pure presence flag; default off. When set, timestamps and prints draft, snapshot, verifier, prefix/replay and total durations for the path taken; algorithm selection is otherwise unchanged. | Profile end-to-end MTP speculative decoding and separate draft, verification and state-commit costs. | [ds4.c:70899](ds4.c#L70899) |
+| `DS4_NO_BATCHED_ATTN` | presence rollback flag; unset keeps default/optimized path | Disable/roll back no batched attn. | [ds4.c:14410](ds4.c#L14410) |
+| `DS4_NO_BATCHED_ROPE` | presence rollback flag; unset keeps default/optimized path | Disable/roll back no batched rope. | [ds4.c:13918](ds4.c#L13918) |
+| `DS4_NO_PARALLEL_ATTN_ROWS` | presence rollback flag; unset keeps default/optimized path | Disable/roll back no parallel attn rows. | [ds4.c:13904](ds4.c#L13904) |
+| `DS4_NO_ROUTED_TOKEN_PARALLEL` | presence rollback flag; unset keeps default/optimized path | Disable/roll back no routed token parallel. | [ds4.c:12588](ds4.c#L12588) |
+| `DS4_NO_SHARED_BATCH_FFN` | presence rollback flag; unset keeps default/optimized path | Disable/roll back no shared batch ffn. | [ds4.c:14413](ds4.c#L14413) |
+| `DS4_ORACLE_LOGITS` | filesystem path; unset disables read/write | Load reference logits for graph correctness comparison. | [ds4.c:39056](ds4.c#L39056) |
+| `DS4_PARALLEL_ATTN_ROWS` | Pure presence opt-in; any defined value enables the preference, but DS4_NO_PARALLEL_ATTN_ROWS overrides it. The path is eligible only for prefix prefill with cache n_raw==0 and pos0==0; unset uses per-token attention rows. | Batch/parallelize CPU prefix attention-row evaluation after cache/index preparation. | [ds4.c:13901](ds4.c#L13901) |
+| `DS4_PARALLEL_FFN` | Pure presence opt-in. It is effective only in CPU prefill when batched attention is enabled, DS4_BATCHED_FFN is absent, and the default shared-batch path has been disabled with DS4_NO_SHARED_BATCH_FFN; otherwise higher-priority paths win. | Run independent prompt-token FFNs through layer_ffn_tokens_parallel as the fallback after disabling shared batching. | [ds4.c:14412](ds4.c#L14412) |
+| `DS4_PREFILL_BATCH` | Nonempty value parsed by strtol without full-string validation; accepted range 1..4095, default 128 for unset/invalid/out-of-range values. It is used only when DS4_BATCHED_FFN selects full batched CPU FFN. | Set the token chunk size for layer_ffn_batch during CPU layer-major prefill. | [ds4.c:14414](ds4.c#L14414) |
+| `DS4_PREFILL_PROFILE_DETAIL` | presence flag; unset=off | Print detailed per-stage CPU prefill timing. | [ds4.c:12555](ds4.c#L12555) |
+| `DS4_PREFILL_PROFILE_TOKEN` | presence flag; effective within detailed prefill profiling | Print token-loop substage timings during CPU prefill. | [ds4.c:14130](ds4.c#L14130) |
+| `DS4_Q8_FOLD_SELFTEST` | positive call budget; unset/empty disables; a nonempty value parsing to 1 or less selects 512 calls | Byte-check folded Q8_1 activations against a fresh quantization; synchronizes eager streams. | [cuda/mmq/ds4_mmq.cu:5953](cuda/mmq/ds4_mmq.cu#L5953) |
+| `DS4_ROUTED_TOKEN_PARALLEL` | Pure presence flag that forces token-parallel routed MoE, even if DS4_NO_ROUTED_TOKEN_PARALLEL is also set. When unset, token parallelism is automatic for n_tok>=64 unless the NO flag is present; smaller batches use per-token routed MoE. | Choose token-parallel CPU routed-expert evaluation inside the default shared-batch FFN prefill path. | [ds4.c:12587](ds4.c#L12587) |
+| `DS4_SERVER_BATCH_LOG` | Pure presence flag read once when the decode worker starts; default off. Any defined value, including empty or "0", logs one record per coalesced decode batch with count, elapsed milliseconds and ok/error status. | Observe server-side decode coalescing size, latency and result without changing batching behavior. | [ds4_server.c:11090](ds4_server.c#L11090) |
+| `DS4_SERVER_DECODE_COALESCE_US` | integer 0..100000 microseconds; default 2000; 0 disables wait | Control server micro-batch coalescing delay. | [ds4_server.c:11069](ds4_server.c#L11069) |
+| `DS4_SSD_AUTO_CACHE_PCT` | integer 50..95; default 80 | Choose the RAM percentage used by automatic SSD expert-cache planning. | [ds4_ssd.c:81](ds4_ssd.c#L81) |
+| `DS4_TEST_METAL_EXACTN_ORACLE` | presence flag compiled only with DS4_TEST_HOOKS; unset is off; any defined value enables | Force allocation of the Metal exact-N verifier/oracle workspace in test builds. | [ds4.c:61991](ds4.c#L61991) |
+| `DS4_THREADS` | positive integer; default min(online CPUs,12), capped by DS4_MAX_THREADS; CLI thread request overrides env | Set CPU worker-pool size. | [ds4.c:1874](ds4.c#L1874) |
+| `DS4_TOKEN_TIMING` | Pure presence flag; default off. Any defined value times and prints each CPU token decode evaluation; sampling, emission and callbacks are outside the measured interval. | Report per-token CPU model-evaluation latency during direct argmax generation. | [ds4.c:41619](ds4.c#L41619) |
+| `DS4_TP_ABLATE` | comma/list string matched for hcpre,router,kv,compidx; unset=no ablation; must match on both ranks | Skip named TP encode chains for timing; output is semantically wrong. | [ds4.c:22520](ds4.c#L22520) |
+| `DS4_TP_EVENT_GATES` | presence flag; unset uses lower-latency slab flag gates when available | Fall back to Metal shared-event arrival gates. | [ds4_metal.m:10768](ds4_metal.m#L10768) |
+| `DS4_TP_GATE_PROFILE` | presence diagnostic flag; unset=off | Collect timing/profile diagnostics for tp gate profile. | [ds4_metal.m:10662](ds4_metal.m#L10662) |
+| `DS4_TP_GATE_TRACE` | presence diagnostic flag; unset=off | Emit trace diagnostics for tp gate trace. | [ds4_tp.c:911](ds4_tp.c#L911) |
+| `DS4_TP_KEEPALIVE_ITERS` | atoi unsigned iteration count; default 1200000 | Tune work per Metal TP keep-alive dispatch. | [ds4_metal.m:10626](ds4_metal.m#L10626) |
+| `DS4_TP_KEEPALIVE_TGS` | integer 1..2048; invalid/out of range uses 1 | Tune threadgroups per Metal TP keep-alive dispatch. | [ds4_metal.m:10612](ds4_metal.m#L10612) |
+| `DS4_TP_NO_KEEPALIVE` | presence flag; unset starts Metal TP keep-alive | Disable the Metal TP GPU keep-alive worker. | [ds4_metal.m:10798](ds4_metal.m#L10798) |
+| `DS4_TP_PREFILL_SPLIT_MIN` | atoi token threshold; default 32; values below 2 clamp to 2 | Set when TP prefill row-splits the replicated shared expert. | [ds4.c:29192](ds4.c#L29192) |
+| `DS4_TP_SUBGATE_PIPELINE` | nonempty integer; nonzero enables; default off; must match on both ranks | Enable TP prefill sub-chunk gate pipelining. | [ds4.c:29206](ds4.c#L29206) |
+| `DS4_TP_TIMEOUT_SEC` | atoi seconds stored unsigned; default DS4_TP_DEFAULT_TIMEOUT_SEC | Override TP control/data socket operation timeout. | [ds4_tp.c:1329](ds4_tp.c#L1329) |
+| `DS4_TRACE_TOP` | presence flag; unset=off | Print top-logit/token trace data during CPU generation. | [ds4.c:41588](ds4.c#L41588) |
+| `DS4_WS_REPACK_HASH` | exact 1 enables; unset or every other value disables unless overridden by CLI; cached | Print a per-artifact FNV-1a hash for workspace repack identity checks. | [cuda/mmq/ds4_repack.cu:530](cuda/mmq/ds4_repack.cu#L530) |
+| `DS4_WS_REPACK_THREADS` | positive integer; default min(6, hardware threads), capped at 16 and the job count | Set the CPU worker count for CUDA workspace artifact repacking. | [cuda/mmq/ds4_repack.cu:539](cuda/mmq/ds4_repack.cu#L539) |
+
+
+
+### External runtime environment
+
+These names are not owned by the `DS4_*` namespace but are read directly by
+the binaries or vendored runtime code.
+
+| Variable | Accepted value and default | Effect | Source |
+| --- | --- | --- | --- |
+| `GGML_CUDA_DISABLE_GRAPHS` | Pure presence flag cached on first is_enabled() call; any defined value, including empty or "0", disables. Unset permits CUDA graphs unless the GPU architecture independently disables them; relevant only when compiled with USE_CUDA_GRAPH. | Disable vendored GGML CUDA graph capture/replay and execute through the ordinary CUDA path. | [cuda/mmq/common.cuh:1208](cuda/mmq/common.cuh#L1208) |
+| `HOME` | Filesystem directory string. In ds4-agent, unset or empty falls back to "." for the default cache and history roots; the web helper applies the same fallback for its browser profile. A nonempty value roots .ds4/kvcache, .ds4_agent_history and .ds4/browser. | Choose the user's persistent ds4-agent cache, line-history and Chrome-profile base directory. | [ds4_agent.c:4023](ds4_agent.c#L4023) |
+| `LINENOISE_ASSUME_TTY` | Pure presence test flag: any defined value, including empty or "0", treats non-TTY input as interactive while skipping real termios raw-mode setup/restoration. Unset follows isatty and uses plain blocking line input for pipes. | Exercise the live linenoise/agent editor, prompt and status layout in automated pipe-based tests without a real terminal. | [linenoise.c:593](linenoise.c#L593) |
+| `LINENOISE_COLS` | If defined, its value is returned directly through atoi with no validation: empty/nonnumeric becomes 0 and signed values are accepted. If unset, linenoise uses TIOCGWINSZ, then a cursor-position query, then fallback width 80. | Force a deterministic terminal column count for linenoise wrapping/layout tests. | [linenoise.c:684](linenoise.c#L684) |
+| `PATH` | Colon-separated executable search directories consulted only after DS4_CHROME, macOS app paths and fixed Chrome/Chromium paths fail. The first executable google-chrome, google-chrome-stable, chromium or chromium-browser wins; unset/empty/no match falls back to the literal command google-chrome, which execlp may search again. | Locate a Chrome/Chromium executable for the ds4 web/CDP tool. | [ds4_web.c:992](ds4_web.c#L992) |
+| `TERM` | Case-insensitive terminal name. Values dumb, cons25, or emacs select linenoise's simple prompt plus blocking line reader; unset, empty, or any other value selects the normal interactive editor when stdin is a TTY. | Avoid ANSI/raw interactive editing on terminal types known not to support the required escape sequences. | [linenoise.c:559](linenoise.c#L559) |
+
+## Test and fixture environment inputs
+
+These entries are consumed by repository test binaries or fixture scripts. Some
+production runtime controls are repeated here because a maintained fixture exposes
+them as part of its own test contract.
+
+### Test binaries and cleanup hooks
+
+| Variable | Accepted value and default | Effect | Source |
+| --- | --- | --- | --- |
+| `DS4_CUDA_TOPK_REGRESSION_SEC` | positive floating-point seconds; default 2.0; invalid or nonpositive input restores the default | Set the CUDA large-top-k elapsed-time regression limit. | [tests/cuda_long_context_smoke.c:72](tests/cuda_long_context_smoke.c#L72) |
+| `DS4_METAL_MOE_TILE_MAX` | cleanup-only historical spelling; no production consumer exists, so setting it has no runtime effect | Clears a legacy Metal MoE tile override while preparing the test environment. | [tests/ds4_test.c:7516](tests/ds4_test.c#L7516) |
+| `DS4_ROCM_ENABLE_Q4_PREFILL_TILE8` | cleanup-only legacy spelling; no runtime or test reader; setting it has no effect | Remove a stale opt-in name while preparing ROCm Q4 test cases; TILE8 is automatic. | [tests/test_rocm_q4_dense_pair.cpp:58](tests/test_rocm_q4_dense_pair.cpp#L58) |
+| `DS4_TEST_ALLOW_FALLBACK` | presence flag; unset: native mixed path required; any defined value including empty or 0 permits exactly the serialized-fallback counter outcome | Lets the CUDA mixed prefill/decode oracle accept serialized fallback while retaining bit-exact logit comparisons. | [tests/test_cuda_mixed_batch.c:204](tests/test_cuda_mixed_batch.c#L204) |
+| `DS4_TEST_BACKEND` | exact cpu selects CPU; every other value, including unset/empty, selects Metal on Apple and CUDA elsewhere | Chooses the backend used by model-backed tests in tests/ds4_test.c. | [tests/ds4_test.c:91](tests/ds4_test.c#L91) |
+| `DS4_TEST_BATCH_ONLY` | presence flag; unset: run batched and isolated-control phases; any defined value including empty or 0 stops after the batched archive/hash phase | Runs only the CUDA session-batch phase and skips replay against isolated control sessions. | [tests/test_cuda_session_batch.c:288](tests/test_cuda_session_batch.c#L288) |
+| `DS4_TEST_CONTEXT` | CUDA session/mixed fixtures default to 1024 and require 1024..65536; mixed-batch uses strict full decimal parsing, while session-batch uses atoi and therefore accepts numeric prefixes | Sets the context and placement hint for the CUDA session-batch and mixed prefill/decode oracles. | [tests/test_cuda_session_batch.c:125](tests/test_cuda_session_batch.c#L125) |
+| `DS4_TEST_DSPARK` | nonempty DSpark support-GGUF path; unset/empty skips the DSpark verify-depth test | Loads the DSpark support model for teacher-forced verification of committed speculative tokens. | [tests/ds4_test.c:8563](tests/ds4_test.c#L8563) |
+| `DS4_TEST_GPU_DEVICES` | GPU device-list string parsed with the normal auto-VRAM parser; unset/empty defaults to 0,2,4,6,1,3,5,7; parse failure is fatal | Selects and orders the CUDA TP/EP devices used by the mixed prefill/decode oracle. | [tests/test_cuda_mixed_batch.c:122](tests/test_cuda_mixed_batch.c#L122) |
+| `DS4_TEST_LOCAL_GOLDEN_FILE` | nonempty readable fixture path; unset/empty defaults to tests/test-vectors/flash-0731/local-golden.vec | Selects the local-golden vector file used for model-logit regression checks. | [tests/ds4_test.c:7501](tests/ds4_test.c#L7501) |
+| `DS4_TEST_LOGPROB_AUTO_METAL` | presence flag; unset forces DS4_METAL_DISABLE_METAL4=1; any presence including empty or 0 removes that rollback and permits automatic Metal selection | Runs official log-probability vectors with automatic Metal-path selection instead of the fixed pre-Metal4 baseline. | [tests/ds4_test.c:7235](tests/ds4_test.c#L7235) |
+| `DS4_TEST_LONG_PROMPT` | nonempty readable prompt-file path; unset/empty defaults to tests/long_context_story_prompt.txt | Selects the rendered story prompt for the long-context fact-recall test. | [tests/ds4_test.c:6970](tests/ds4_test.c#L6970) |
+| `DS4_TEST_LONG_WORDS` | atoi integer; unset/empty/nonnumeric defaults to 0; valid range is 0..DS4_TEST_CONTEXT-128 and numeric prefixes are accepted | Adds repeated words to alternating CUDA session-batch prompts to exercise long-prefill rows. | [tests/test_cuda_session_batch.c:135](tests/test_cuda_session_batch.c#L135) |
+| `DS4_TEST_METAL_ARGMAX_TOP1_TIMING` | presence flag; unset runs correctness only; any defined value including empty or 0 also runs the GGUF-free resident production-shape A/B | Measures generic argsort versus dedicated Metal top-1 and full-readback versus 4-byte greedy selection using resident synthetic logits, excluding model and SSD I/O. | [tests/test_metal_argmax_top1.c:545](tests/test_metal_argmax_top1.c#L545) |
+| `DS4_TEST_METAL_EXACTN_BATCH_HEAD` | nonempty value other than exact 0 enables; unset/empty/0 disables; false/off also enable | Enables the Metal exact-N batch-head path and requires its attempt/use counters for every eligible oracle case. | [tests/test_metal_exactn_oracle.c:401](tests/test_metal_exactn_oracle.c#L401) |
+| `DS4_TEST_METAL_EXACTN_ORACLE` | presence flag compiled only with DS4_TEST_HOOKS; absent from normal production builds | Force allocation of the exact-N Metal verifier/oracle workspace in tests. | [ds4.c:61991](ds4.c#L61991) |
+| `DS4_TEST_MIXED_INITIAL` | integer 128..context-1; default 128 | Set the initial prefill length for the CUDA mixed-batch oracle. | [tests/test_cuda_mixed_batch.c:111](tests/test_cuda_mixed_batch.c#L111) |
+| `DS4_TEST_MIXED_QUANTUM` | integer 1..context-1; default 128 | Set the number of prompt tokens added per CUDA mixed-batch round. | [tests/test_cuda_mixed_batch.c:113](tests/test_cuda_mixed_batch.c#L113) |
+| `DS4_TEST_MIXED_ROUNDS` | integer 1..64; default 3 | Set the number of CUDA mixed-batch oracle rounds. | [tests/test_cuda_mixed_batch.c:115](tests/test_cuda_mixed_batch.c#L115) |
+| `DS4_TEST_MODEL` | nonempty GGUF path; tests/ds4_test.c defaults to ds4flash.gguf, while standalone model-backed CUDA/Metal fixtures generally require a supplied path and fail or skip when absent | Selects the target model shared by model-backed test binaries. | [tests/ds4_test.c:14](tests/ds4_test.c#L14) |
+| `DS4_TEST_MPP_EQ_CASE` | comma-separated substring filter; unset/empty runs all cases; tokens are whitespace-trimmed and the filter is truncated to 255 bytes | Restricts Metal tensor-equivalence vectors to IDs containing at least one requested substring. | [tests/ds4_test.c:7805](tests/ds4_test.c#L7805) |
+| `DS4_TEST_MTP` | nonempty MTP support-GGUF path; unset/empty loads no MTP head; only the fast test engine uses it, with draft depth 4 | Enables the legacy MTP verify-depth regression; the test self-skips without this model. | [tests/ds4_test.c:104](tests/ds4_test.c#L104) |
+| `DS4_TEST_Q4_STREAM_ITERS` | integer 1..10000; default 2 | Set measured iterations for the Metal Q4 stream oracle. | [tests/test_metal_q4_streams.c:734](tests/test_metal_q4_streams.c#L734) |
+| `DS4_TEST_Q4_STREAM_SOAK` | integer 1..100000; default 8 | Set bounded overlap-soak iterations for the Metal Q4 stream oracle. | [tests/test_metal_q4_streams.c:736](tests/test_metal_q4_streams.c#L736) |
+| `DS4_TEST_Q4_STREAM_TIMING` | presence flag; unset: correctness/leak checks only; any defined value including empty or 0 also runs timing pairs | Adds FIFO-versus-overlap and native-versus-overlap timing measurements to the Metal Q4 stream oracle. | [tests/test_metal_q4_streams.c:737](tests/test_metal_q4_streams.c#L737) |
+| `DS4_TEST_Q4_STREAM_TIMING_BLOCKS` | integer 5..MAX_TIMING_BLOCKS; default 5 | Set the timing block count for the Metal Q4 stream oracle. | [tests/test_metal_q4_streams.c:739](tests/test_metal_q4_streams.c#L739) |
+| `DS4_TEST_Q4_STREAM_TIMING_ITERS` | integer 1..10000; default 20 | Set timing iterations for the Metal Q4 stream oracle. | [tests/test_metal_q4_streams.c:741](tests/test_metal_q4_streams.c#L741) |
+| `DS4_TEST_Q4_STREAM_WARMUP` | integer 1..64; default 1 | Set warmup iterations for the Metal Q4 stream oracle. | [tests/test_metal_q4_streams.c:732](tests/test_metal_q4_streams.c#L732) |
+| `DS4_TEST_REQUIRE_MODEL` | nonempty value other than exact 0 requires a readable model; unset/empty/0 permits a skip; false/off count as required | Turns a missing Metal exact-N oracle model from a developer skip into a release-gate failure. | [tests/test_metal_exactn_oracle.c:390](tests/test_metal_exactn_oracle.c#L390) |
+| `DS4_TEST_REQUIRE_ROCM_DEVICE` | nonempty value other than exact 0 requires a visible ROCm device; unset/empty/0 returns the fixture skip code; false/off count as required | Turns absence of a ROCm device from a skip into failure for the ROCm Q4 oracle. | [tests/test_rocm_q4_dense_pair.cpp:1569](tests/test_rocm_q4_dense_pair.cpp#L1569) |
+| `DS4_TEST_SERVER_PREFILL` | presence flag; unset: normal prefill; any defined value including empty or 0 installs a no-op display-progress callback | Exercises the progress-split prefill path used by ds4-server in CUDA session-batch and control sessions. | [tests/test_cuda_session_batch.c:110](tests/test_cuda_session_batch.c#L110) |
+| `DS4_TEST_SESSION_BATCH_ARM` | arbitrary nonempty label; unset/empty defaults to unspecified; it is logged only and does not alter execution | Labels the Metal session-batch experiment arm in setup diagnostics. | [tests/test_metal_session_batch.c:153](tests/test_metal_session_batch.c#L153) |
+| `DS4_TEST_SESSION_BATCH_TIMING` | nonempty boolean; unset/empty/exact 0 disables; every other value enables | Print timing data from the Metal session-batch oracle. | [tests/test_metal_session_batch.c:150](tests/test_metal_session_batch.c#L150) |
+| `DS4_TEST_SESSION_COUNT` | fixture-specific integer: CUDA session-batch defaults 8 and accepts atoi 2..16; CUDA mixed-batch defaults 8 with strict 3..16; Metal session-batch defaults 2 with strict 2..16 | Sets the number of simultaneous sessions exercised by the model-backed batch oracles. | [tests/test_cuda_session_batch.c:113](tests/test_cuda_session_batch.c#L113) |
+| `DS4_TEST_SSD_CACHE_EXPERTS` | strict unsigned integer 30..UINT32_MAX; unset/empty defaults to 30; read only when Metal session-batch SSD streaming is enabled | Sizes the Metal session-batch routed-expert cache used to exercise SSD union policies for N=2..5. | [tests/test_metal_session_batch.c:88](tests/test_metal_session_batch.c#L88) |
+| `DS4_TEST_SSD_STREAMING` | nonempty value other than exact 0 enables; unset/empty/0 disables; false/off also enable | Runs model-backed test engines through SSD streaming; the Metal session-batch fixture also uses cold mode and shared prefill workspace. | [tests/ds4_test.c:109](tests/ds4_test.c#L109) |
+| `DS4_TEST_SSD_STREAMING_CACHE_EXPERTS` | strtoul decimal prefix; unset/empty/nonnumeric becomes 0, values above UINT32_MAX (including a parsed negative) saturate, and trailing text is accepted | Sets the routed-expert cache count on SSD-streaming engines created by tests/ds4_test.c. | [tests/ds4_test.c:112](tests/ds4_test.c#L112) |
+| `DS4_TEST_SSD_STREAMING_CACHE_GB` | strtoull decimal GiB prefix; unset/empty/nonnumeric/zero becomes 0, byte overflow (including a parsed negative) saturates to UINT64_MAX, and trailing text is accepted | Sets the routed-expert cache byte budget on SSD-streaming engines created by tests/ds4_test.c. | [tests/ds4_test.c:114](tests/ds4_test.c#L114) |
+| `DS4_TEST_SSD_STREAMING_COLD` | nonempty boolean; unset/empty/exact 0 disables; every other value enables | Run test engines in cold SSD-streaming mode and skip hot-expert preload. | [tests/ds4_test.c:110](tests/ds4_test.c#L110) |
+| `DS4_TEST_SSD_STREAMING_PRELOAD_EXPERTS` | unsigned integer; default 0; numeric prefixes are accepted and overflow clamps to UINT32_MAX | Set the number of SSD-streaming experts preloaded by test engines. | [tests/ds4_test.c:116](tests/ds4_test.c#L116) |
+| `DS4_TEST_SSD_UNION_POLICY_SWITCH` | nonempty boolean; unset/empty/exact 0 disables; every other value enables | Exercise an SSD session-union policy transition in the Metal session-batch oracle. | [tests/test_metal_session_batch.c:152](tests/test_metal_session_batch.c#L152) |
+| `DS4_TEST_TP_DISCONNECT` | presence flag effective only in leader mode; unset: normal test; any defined value including empty or 0 enters the disconnect oracle | Waits for the TP worker to disconnect, then requires the next batch to fail and every session checkpoint to be invalidated. | [tests/test_metal_session_batch.c:268](tests/test_metal_session_batch.c#L268) |
+| `DS4_TEST_TP_LEADER_HOST` | nonempty host string required in worker mode; no default; ignored outside worker mode | Sets the TP leader address contacted by the Metal session-batch worker. | [tests/test_metal_session_batch.c:212](tests/test_metal_session_batch.c#L212) |
+| `DS4_TEST_TP_LISTEN_HOST` | nonempty host string; unset/empty defaults to 0.0.0.0; used only in leader mode | Sets the TP listen address for the Metal session-batch leader. | [tests/test_metal_session_batch.c:204](tests/test_metal_session_batch.c#L204) |
+| `DS4_TEST_TP_MODE` | unset/empty: no TP; exact leader or worker selects that role; every other nonempty value fails; incompatible with SSD-streaming mode | Selects standalone, TP-leader, or TP-worker execution for the Metal session-batch oracle. | [tests/test_metal_session_batch.c:168](tests/test_metal_session_batch.c#L168) |
+| `DS4_TEST_TP_PORT` | strict full decimal integer 1..65535; unset/empty defaults to 19452 | Sets the listen/connect port shared by Metal session-batch TP leader and worker. | [tests/test_metal_session_batch.c:63](tests/test_metal_session_batch.c#L63) |
+| `DS4_TEST_TP_TRANSPORT` | unset/empty/auto selects automatic transport; exact tcp or rdma selects that transport; other values fail | Chooses the TP transport for Metal session-batch leader/worker tests. | [tests/test_metal_session_batch.c:52](tests/test_metal_session_batch.c#L52) |
+| `DS4_TEST_VECTOR_FILE` | nonempty readable vector path; unset/empty defaults to tests/test-vectors/flash-0731/official.vec | Selects the official fixture used by log-probability and Metal tensor-equivalence tests. | [tests/ds4_test.c:7222](tests/ds4_test.c#L7222) |
+| `PROTO_Q8_DEBUG` | presence diagnostic; unset: summary only; any defined value including empty or 0 prints detailed error structure after a Q8 parity failure | Dumps bad-element tile and row/column histograms for the CUDA Q8 prototype when parity fails. | [cuda/mmq/test/proto_gemm_dense_q8_d2r.cu:647](cuda/mmq/test/proto_gemm_dense_q8_d2r.cu#L647) |
+
+### Test fixture scripts
+
+| Variable | Accepted value and default | Effect | Source |
+| --- | --- | --- | --- |
+| `DEEPSEEK_API_KEY` | secret string; required | Authenticate official test-vector fetch. | [tests/test-vectors/fetch_official_vectors.py:236](tests/test-vectors/fetch_official_vectors.py#L236) |
+| `DS4_BIN` | executable path; unset/empty defaults to ./ds4; the Q4 matrix requires it executable, the DSpark fixture skips if missing, and the GLM smoke lets command failure fail the test | Selects the ds4 binary launched by model-backed shell test fixtures. | [tests/cuda_q4_gb10_fast_matrix.sh:47](tests/cuda_q4_gb10_fast_matrix.sh#L47) |
+| `DS4_CUDA_DISABLE_DSPARK_EXACTN` | arbitrary inherited runtime value; the fixture neither parses nor changes it; unset/empty is printed as unset in metadata, and the environment is passed unchanged to ds4 | Records and passes through the CUDA exact-N rollback used by the acceptance run. | [tests/dspark_acceptance_fixture.sh:253](tests/dspark_acceptance_fixture.sh#L253) |
+| `DS4_CUDA_DISABLE_DSPARK_EXACTN_BATCH_HEAD` | arbitrary inherited runtime value; the fixture neither parses nor changes it; unset/empty is printed as unset in metadata, and the environment is passed unchanged to ds4 | Records and passes through the CUDA exact-N batch-head rollback. | [tests/dspark_acceptance_fixture.sh:255](tests/dspark_acceptance_fixture.sh#L255) |
+| `DS4_CUDA_DISABLE_DSPARK_EXACTN_GRAPHS` | arbitrary inherited runtime value; the fixture neither parses nor changes it; unset/empty is printed as unset in metadata, and the environment is passed unchanged to ds4 | Records and passes through the CUDA exact-N graph rollback. | [tests/dspark_acceptance_fixture.sh:257](tests/dspark_acceptance_fixture.sh#L257) |
+| `DS4_CUDA_DISABLE_DSPARK_NONCAUSAL_ONLINE` | arbitrary inherited runtime value; the fixture neither parses nor changes it; unset/empty is printed as unset in metadata, and the environment is passed unchanged to ds4 | Records and passes through the CUDA noncausal-online-attention rollback. | [tests/dspark_acceptance_fixture.sh:266](tests/dspark_acceptance_fixture.sh#L266) |
+| `DS4_CUDA_DSPARK_DEVICE_PROPOSER` | arbitrary inherited runtime value; the fixture neither parses nor changes it; unset/empty is printed as unset in metadata, and the environment is passed unchanged to ds4 | Records and passes through the CUDA device-proposer opt-in. | [tests/dspark_acceptance_fixture.sh:258](tests/dspark_acceptance_fixture.sh#L258) |
+| `DS4_CUDA_DSPARK_EXACT2` | arbitrary inherited runtime value; the fixture neither parses nor changes it; unset/empty is printed as unset in metadata, and the environment is passed unchanged to ds4 | Records and passes through the CUDA exact-2 verifier override. | [tests/dspark_acceptance_fixture.sh:250](tests/dspark_acceptance_fixture.sh#L250) |
+| `DS4_CUDA_DSPARK_EXACTN` | arbitrary inherited runtime value; the fixture neither parses nor changes it; unset/empty is printed as unset in metadata, and the environment is passed unchanged to ds4 | Records and passes through the CUDA exact-N verifier opt-in. | [tests/dspark_acceptance_fixture.sh:252](tests/dspark_acceptance_fixture.sh#L252) |
+| `DS4_CUDA_DSPARK_EXACTN_BATCH_HEAD` | arbitrary inherited runtime value; the fixture neither parses nor changes it; unset/empty is printed as unset in metadata, and the environment is passed unchanged to ds4 | Records and passes through the CUDA exact-N batch-head opt-in. | [tests/dspark_acceptance_fixture.sh:254](tests/dspark_acceptance_fixture.sh#L254) |
+| `DS4_CUDA_DSPARK_EXACTN_GRAPHS` | arbitrary inherited runtime value; the fixture neither parses nor changes it; unset/empty is printed as unset in metadata, and the environment is passed unchanged to ds4 | Records and passes through the CUDA exact-N graph opt-in. | [tests/dspark_acceptance_fixture.sh:256](tests/dspark_acceptance_fixture.sh#L256) |
+| `DS4_CUDA_DSPARK_NO_DEVICE_PROPOSER` | arbitrary inherited runtime value; the fixture neither parses nor changes it; unset/empty is printed as unset in metadata, and the environment is passed unchanged to ds4 | Records and passes through the CUDA device-proposer rollback. | [tests/dspark_acceptance_fixture.sh:259](tests/dspark_acceptance_fixture.sh#L259) |
+| `DS4_CUDA_DSPARK_PROPOSER_BLOCK_MAX` | arbitrary inherited runtime value; the fixture neither parses nor changes it; unset/empty is printed as unset in metadata, and the environment is passed unchanged to ds4 | Records and passes through the CUDA proposer block-size cap. | [tests/dspark_acceptance_fixture.sh:269](tests/dspark_acceptance_fixture.sh#L269) |
+| `DS4_CUDA_ENABLE_DSPARK_NONCAUSAL_ONLINE` | arbitrary inherited runtime value; the fixture neither parses nor changes it; unset/empty is printed as unset in metadata, and the environment is passed unchanged to ds4 | Records and passes through the CUDA noncausal-online-attention opt-in. | [tests/dspark_acceptance_fixture.sh:265](tests/dspark_acceptance_fixture.sh#L265) |
+| `DS4_CUDA_Q4_MATRIX_CTX` | nonempty decimal digits other than exact 0; unset/empty defaults to 4096; no upper bound; leading-zero zero strings such as 00 pass the script's guard | Sets --ctx for every Q4 GB10 smoke and score_official matrix arm. | [tests/cuda_q4_gb10_fast_matrix.sh:49](tests/cuda_q4_gb10_fast_matrix.sh#L49) |
+| `DS4_CUDA_Q4_MATRIX_DECODE_GRAPHS` | exact default, 0, or 1; unset/empty defaults to default; other values fail | Leaves decode graphs automatic, forces them off, or forces them on with capture logging for every matrix arm. | [tests/cuda_q4_gb10_fast_matrix.sh:56](tests/cuda_q4_gb10_fast_matrix.sh#L56) |
+| `DS4_CUDA_Q4_MATRIX_PROMPT` | prompt string; unset/empty defaults to Write a complete Python quicksort function with comments. | Sets the deterministic smoke prompt whose log-probability output is compared across Q4 fast-path arms. | [tests/cuda_q4_gb10_fast_matrix.sh:52](tests/cuda_q4_gb10_fast_matrix.sh#L52) |
+| `DS4_CUDA_Q4_MATRIX_SCORER` | executable path; unset/empty defaults to gguf-tools/quality-testing/score_official; a missing/nonexecutable path fails | Selects the scorer used to produce quality TSVs for each non-oracle Q4 matrix arm. | [tests/cuda_q4_gb10_fast_matrix.sh:48](tests/cuda_q4_gb10_fast_matrix.sh#L48) |
+| `DS4_CUDA_Q4_MATRIX_SKIP_PARITY` | exact 0 or 1; unset/empty defaults to 0; other values fail | When 1, skips the synthetic MMQ parity prerequisite and marks the resulting QA run incomplete. | [tests/cuda_q4_gb10_fast_matrix.sh:57](tests/cuda_q4_gb10_fast_matrix.sh#L57) |
+| `DS4_CUDA_Q4_MATRIX_SSD_CACHE` | unset/empty by default; required and passed verbatim as --ssd-streaming-cache-experts when streaming=1; must remain empty when streaming=0; no further validation | Sets the SSD expert cache as a count or NGB value for every streamed matrix arm. | [tests/cuda_q4_gb10_fast_matrix.sh:54](tests/cuda_q4_gb10_fast_matrix.sh#L54) |
+| `DS4_CUDA_Q4_MATRIX_SSD_PRELOAD` | unset/empty omits preload; a nonempty value is passed verbatim as --ssd-streaming-preload-experts and is allowed only when streaming=1 | Sets optional expert preload for streamed Q4 smoke and scoring arms. | [tests/cuda_q4_gb10_fast_matrix.sh:55](tests/cuda_q4_gb10_fast_matrix.sh#L55) |
+| `DS4_CUDA_Q4_MATRIX_SSD_STREAMING` | exact 0 or 1; unset/empty defaults to 0; other values fail | Runs all Q4 matrix arms resident or with SSD streaming and enforces matching cache/preload arguments. | [tests/cuda_q4_gb10_fast_matrix.sh:53](tests/cuda_q4_gb10_fast_matrix.sh#L53) |
+| `DS4_CUDA_Q4_MATRIX_TOKENS` | nonempty decimal digits other than exact 0; unset/empty defaults to 32; no upper bound; leading-zero zero strings such as 00 pass the script's guard | Sets the continuation length for each Q4 GB10 smoke arm. | [tests/cuda_q4_gb10_fast_matrix.sh:50](tests/cuda_q4_gb10_fast_matrix.sh#L50) |
+| `DS4_CUDA_Q4_MATRIX_TOP_K` | nonempty decimal digits other than exact 0 and numerically <=128; unset/empty defaults to 128; leading-zero zero strings such as 00 pass the guard | Sets --logprobs-top-k for the byte-comparable Q4 GB10 smoke dumps. | [tests/cuda_q4_gb10_fast_matrix.sh:51](tests/cuda_q4_gb10_fast_matrix.sh#L51) |
+| `DS4_DSPARK_FIXTURE_BACKEND` | unset/empty defaults to auto; exact auto, metal, cuda, or rocm accepted; every other value fails | Chooses the explicit backend flag for baseline and DSpark acceptance runs; auto passes none. | [tests/dspark_acceptance_fixture.sh:14](tests/dspark_acceptance_fixture.sh#L14) |
+| `DS4_DSPARK_FIXTURE_CONFIDENCE` | unset/empty omits the option and uses the runtime default; otherwise passed verbatim to --dspark-confidence without fixture-side validation | Overrides the DSpark confidence threshold for acceptance runs and records it in metadata. | [tests/dspark_acceptance_fixture.sh:13](tests/dspark_acceptance_fixture.sh#L13) |
+| `DS4_DSPARK_FIXTURE_C_ADD_MIN_ACCEPTED` | decimal digits including 0; unset/empty defaults to 8; non-digits fail | Sets the minimum accepted-draft count for the c_add case when the proposal-quality guard is active. | [tests/dspark_acceptance_fixture.sh:12](tests/dspark_acceptance_fixture.sh#L12) |
+| `DS4_DSPARK_FIXTURE_REQUIRE_ACTIVE` | exact 0 or 1; unset/empty defaults to 1; other values fail | When 1, requires aggregate proposed and accepted-draft counts to both be nonzero. | [tests/dspark_acceptance_fixture.sh:17](tests/dspark_acceptance_fixture.sh#L17) |
+| `DS4_DSPARK_FIXTURE_REQUIRE_CUDA_DEVICE_PROPOSER` | exact 0 or 1; unset/empty defaults to 0; other values fail; 1 also forces byte-identical output checking | Requires CUDA device-proposer attempts to equal uses, with nonzero use and zero fallback or policy mismatch. | [tests/dspark_acceptance_fixture.sh:22](tests/dspark_acceptance_fixture.sh#L22) |
+| `DS4_DSPARK_FIXTURE_REQUIRE_CUDA_EXACTN` | exact 0 or 1; unset/empty defaults to 0; other values fail; 1 also forces byte-identical output checking | Requires at least one CUDA exact-N attempt and zero exact-N error fallbacks. | [tests/dspark_acceptance_fixture.sh:19](tests/dspark_acceptance_fixture.sh#L19) |
+| `DS4_DSPARK_FIXTURE_REQUIRE_CUDA_EXACTN_BATCH_HEAD` | exact 0 or 1; unset/empty defaults to 0; other values fail; 1 implies REQUIRE_CUDA_EXACTN and identical output | Requires nonzero CUDA exact-N batch-head attempts/uses and zero batch-head fallbacks. | [tests/dspark_acceptance_fixture.sh:20](tests/dspark_acceptance_fixture.sh#L20) |
+| `DS4_DSPARK_FIXTURE_REQUIRE_CUDA_EXACTN_GRAPHS` | exact 0 or 1; unset/empty defaults to 0; other values fail; 1 implies REQUIRE_CUDA_EXACTN and identical output | Requires CUDA exact-N graph attempts, uses, captures, and replays, with zero no-slot or graph failures. | [tests/dspark_acceptance_fixture.sh:21](tests/dspark_acceptance_fixture.sh#L21) |
+| `DS4_DSPARK_FIXTURE_REQUIRE_DIRECT_COMMIT` | exact 0 or 1; unset/empty defaults to 0; other values fail | Requires at least one direct verifier-state commit; with REQUIRE_PARTIAL it also requires a direct partial commit. | [tests/dspark_acceptance_fixture.sh:9](tests/dspark_acceptance_fixture.sh#L9) |
+| `DS4_DSPARK_FIXTURE_REQUIRE_EXACT2` | exact 0 or 1; unset/empty defaults to 0; other values fail; 1 also forces byte-identical output checking | Requires at least one exact-2 attempt and zero exact-2 fallbacks. | [tests/dspark_acceptance_fixture.sh:18](tests/dspark_acceptance_fixture.sh#L18) |
+| `DS4_DSPARK_FIXTURE_REQUIRE_IDENTICAL` | exact 0 or 1; unset/empty defaults to 0; other values fail; several path-specific requirements force it to 1 | When 1, fails any byte difference between baseline and DSpark stdout; otherwise mismatches are reported but allowed. | [tests/dspark_acceptance_fixture.sh:10](tests/dspark_acceptance_fixture.sh#L10) |
+| `DS4_DSPARK_FIXTURE_REQUIRE_METAL_DEVICE_PROPOSER` | exact 0 or 1; unset/empty defaults to 0; other values fail; 1 also forces byte-identical output checking | Requires Metal device-proposer attempts to equal uses, with nonzero use and zero fallback or policy mismatch. | [tests/dspark_acceptance_fixture.sh:25](tests/dspark_acceptance_fixture.sh#L25) |
+| `DS4_DSPARK_FIXTURE_REQUIRE_METAL_EXACTN_BATCH_HEAD` | exact 0 or 1; unset/empty defaults to 0; other values fail; 1 also forces byte-identical output checking | Requires nonzero Metal exact-N batch-head attempts/uses and zero batch-head fallbacks. | [tests/dspark_acceptance_fixture.sh:23](tests/dspark_acceptance_fixture.sh#L23) |
+| `DS4_DSPARK_FIXTURE_REQUIRE_METAL_EXACTN_PARTIAL` | exact 0 or 1; unset/empty defaults to 0; other values fail; 1 also forces byte-identical output checking | Requires a Metal exact-N partial replay, matching verify-skip count, and zero union error fallbacks. | [tests/dspark_acceptance_fixture.sh:24](tests/dspark_acceptance_fixture.sh#L24) |
+| `DS4_DSPARK_FIXTURE_REQUIRE_PARTIAL` | unset/empty defaults to 0; exact 0 disables; any other value enables, with no 0/1 validation | Requires at least one partial-accept case and, together with REQUIRE_DIRECT_COMMIT, one direct partial commit. | [tests/dspark_acceptance_fixture.sh:8](tests/dspark_acceptance_fixture.sh#L8) |
+| `DS4_DSPARK_FIXTURE_REQUIRE_PROPOSAL_QUALITY` | unset/empty/auto selects auto; 0/false/no/off disables; 1/true/yes/on enables; values are lowercase and other strings fail; auto enables only without partial mode/confidence override and with tokens >=32 | Controls the c_add minimum-accepted-drafts quality guard. | [tests/dspark_acceptance_fixture.sh:11](tests/dspark_acceptance_fixture.sh#L11) |
+| `DS4_DSPARK_FIXTURE_SSD_STREAMING` | exact 0 or 1; unset/empty defaults to 0; other values fail | Adds --ssd-streaming to both baseline and DSpark runs when enabled. | [tests/dspark_acceptance_fixture.sh:15](tests/dspark_acceptance_fixture.sh#L15) |
+| `DS4_DSPARK_FIXTURE_SSD_STREAMING_CACHE_EXPERTS` | unset/empty omits the cache option; otherwise decimal digits including 0 are required, and a value is legal only with SSD streaming enabled | Passes an explicit --ssd-streaming-cache-experts value to both acceptance-run variants. | [tests/dspark_acceptance_fixture.sh:16](tests/dspark_acceptance_fixture.sh#L16) |
+| `DS4_DSPARK_FIXTURE_TOKENS` | token-count argument; unset/empty defaults to 32; the fixture does not validate it before passing --tokens, and auto quality treats nonnumeric or <32 as ineligible | Sets generated-token count for each baseline and DSpark acceptance case. | [tests/dspark_acceptance_fixture.sh:7](tests/dspark_acceptance_fixture.sh#L7) |
+| `DS4_DSPARK_MODEL` | target-model path; unset/empty falls back to DS4_TEST_MODEL, then ./ds4flash.gguf; a missing file causes a successful skip | Selects the target GGUF compared in baseline and DSpark acceptance runs. | [tests/dspark_acceptance_fixture.sh:5](tests/dspark_acceptance_fixture.sh#L5) |
+| `DS4_DSPARK_SSD_VERIFY_BLOCK_MAX` | unsigned integer rows; default/fallback 0 means automatic policy; numeric prefixes accepted; used both as verifier cap and as an exact-2 proposer-policy discriminator | Cap speculative rows verified from SSD and influence exact-2 proposal sizing. | [tests/dspark_acceptance_fixture.sh:271](tests/dspark_acceptance_fixture.sh#L271) |
+| `DS4_DSPARK_SUPPORT` | support-model path; unset/empty defaults to gguf/DeepSeek-V4-Flash-DSpark-support-0731.gguf; a missing file causes a successful skip | Selects the DSpark support GGUF passed through --mtp. | [tests/dspark_acceptance_fixture.sh:6](tests/dspark_acceptance_fixture.sh#L6) |
+| `DS4_DSPARK_VERIFY_NONCAUSAL` | presence diagnostic sampled once after the first successfully submitted CUDA noncausal-attention kernel; unset: verify 0 calls; any presence including empty or 0: verify that call and the next 2 | CUDA only: synchronizes and reads back Q/KV/output, computes the DSpark noncausal attention CPU reference, and logs max absolute/relative error; it reports only and does not fail the operation. | [tests/dspark_acceptance_fixture.sh:267](tests/dspark_acceptance_fixture.sh#L267) |
+| `DS4_GLM_BACKEND` | exact metal, cuda, or cpu; unset/empty defaults to metal; other values fail | Selects the backend flag used by the GLM long-context continuation smoke test. | [tests/glm_long_context_smoke.sh:29](tests/glm_long_context_smoke.sh#L29) |
+| `DS4_GLM_EXTRA_ARGS` | unset/empty adds no arguments; otherwise intentionally unquoted and therefore shell field-split and pathname-expanded | Adds backend/device options to the ds4 invocation used for every GLM long-context case. | [tests/glm_long_context_smoke.sh:91](tests/glm_long_context_smoke.sh#L91) |
+| `DS4_GLM_LONG_CONTEXT_CTX` | context argument; unset/empty defaults to 100000; forwarded to --ctx without script-side validation | Sets the context size for GLM long-context smoke invocations. | [tests/glm_long_context_smoke.sh:26](tests/glm_long_context_smoke.sh#L26) |
+| `DS4_GLM_LONG_CONTEXT_GEN` | generation-count argument; unset/empty defaults to 32; forwarded to -n without script-side validation | Sets the number of continuation tokens checked by each GLM long-context case. | [tests/glm_long_context_smoke.sh:28](tests/glm_long_context_smoke.sh#L28) |
+| `DS4_GLM_LONG_CONTEXT_REPEATS` | whitespace-separated list of prompt-padding counts; unset/empty defaults to the single count 130; each item must work as a shell integer | Chooses one or more audit-block counts used to construct long GLM prompts. | [tests/glm_long_context_smoke.sh:27](tests/glm_long_context_smoke.sh#L27) |
+| `DS4_GLM_MODEL` | model path used only when no nonempty positional MODEL is supplied; unset/empty defaults to models/GLM-5.2-UD-Q4_K_XL.gguf | Selects the GLM-5.2 GGUF used by the long-context continuation smoke test. | [tests/glm_long_context_smoke.sh:25](tests/glm_long_context_smoke.sh#L25) |
+| `DS4_METAL_DISABLE_DSPARK_EXACTN_BATCH_HEAD` | arbitrary inherited runtime value; the fixture neither parses nor changes it; unset/empty is printed as unset in metadata, and the environment is passed unchanged to ds4 | Records and passes through the Metal exact-N batch-head rollback. | [tests/dspark_acceptance_fixture.sh:262](tests/dspark_acceptance_fixture.sh#L262) |
+| `DS4_METAL_DSPARK_DEVICE_PROPOSER` | arbitrary inherited runtime value; the fixture neither parses nor changes it; unset/empty is printed as unset in metadata, and the environment is passed unchanged to ds4 | Records and passes through the Metal device-proposer opt-in. | [tests/dspark_acceptance_fixture.sh:263](tests/dspark_acceptance_fixture.sh#L263) |
+| `DS4_METAL_DSPARK_EXACT2` | arbitrary inherited runtime value; the fixture neither parses nor changes it; unset/empty is printed as unset in metadata, and the environment is passed unchanged to ds4 | Records and passes through the Metal exact-2 verifier override. | [tests/dspark_acceptance_fixture.sh:251](tests/dspark_acceptance_fixture.sh#L251) |
+| `DS4_METAL_DSPARK_EXACTN_BATCH_HEAD` | arbitrary inherited runtime value; the fixture neither parses nor changes it; unset/empty is printed as unset in metadata, and the environment is passed unchanged to ds4 | Records and passes through the Metal exact-N batch-head opt-in. | [tests/dspark_acceptance_fixture.sh:261](tests/dspark_acceptance_fixture.sh#L261) |
+| `DS4_METAL_DSPARK_EXACTN_UNION` | arbitrary inherited runtime value; the fixture neither parses nor changes it; unset/empty is printed as unset in metadata, and the environment is passed unchanged to ds4 | Records and passes through the Metal exact-N union-verifier opt-in. | [tests/dspark_acceptance_fixture.sh:260](tests/dspark_acceptance_fixture.sh#L260) |
+| `DS4_METAL_DSPARK_EXACT_ROWS_ASYNC_TAILS` | arbitrary inherited runtime value; the fixture neither parses nor changes it; unset/empty is printed as unset in metadata, and the environment is passed unchanged to ds4 | Records and passes through the Metal exact-row asynchronous-tail override. | [tests/dspark_acceptance_fixture.sh:268](tests/dspark_acceptance_fixture.sh#L268) |
+| `DS4_METAL_DSPARK_NO_DEVICE_PROPOSER` | arbitrary inherited runtime value; the fixture neither parses nor changes it; unset/empty is printed as unset in metadata, and the environment is passed unchanged to ds4 | Records and passes through the Metal device-proposer rollback. | [tests/dspark_acceptance_fixture.sh:264](tests/dspark_acceptance_fixture.sh#L264) |
+| `DS4_METAL_DSPARK_PROPOSER_BLOCK_MAX` | arbitrary inherited runtime value; the fixture neither parses nor changes it; unset/empty is printed as unset in metadata, and the environment is passed unchanged to ds4 | Records and passes through the Metal proposer block-size cap. | [tests/dspark_acceptance_fixture.sh:270](tests/dspark_acceptance_fixture.sh#L270) |
+| `DS4_TEST_MODEL` | fallback target-model path used only when DS4_DSPARK_MODEL is unset/empty; unset/empty then defaults to ./ds4flash.gguf | Provides the shared test-model fallback for the DSpark acceptance fixture. | [tests/dspark_acceptance_fixture.sh:5](tests/dspark_acceptance_fixture.sh#L5) |
+| `OPENROUTER_API_KEY` | secret string; required | Authenticate OpenRouter GLM test-vector fetch. | [tests/test-vectors/fetch_openrouter_glm_vectors.py:355](tests/test-vectors/fetch_openrouter_glm_vectors.py#L355) |
+| `TMPDIR` | temporary-directory base path; unset/empty defaults to /tmp | Chooses the parent directory for auto-created Q4 matrix, DSpark fixture, and GLM smoke work directories. | [tests/cuda_q4_gb10_fast_matrix.sh:108](tests/cuda_q4_gb10_fast_matrix.sh#L108) |
+
+## Tool and wrapper environment inputs
+
+These variables configure maintained download, service-wrapper, and offline tooling.
+A tool that accepts a variable name dynamically (for example `--api-key-env`) may read
+the caller-selected name in addition to the literal defaults listed here.
+
+| Variable | Accepted value and default | Effect | Source |
+| --- | --- | --- | --- |
+| `` | dynamic environment-variable name; no fixed identifier; overrides endpoint-derived key name | Allow a caller-selected credential environment variable. | [gguf-tools/quality-testing/collect_official.py:243](gguf-tools/quality-testing/collect_official.py#L243) |
+| `DEEPSEEK_API_KEY` | secret string; default credential for non-OpenRouter endpoint; required unless --api-key-env selects another name | Authenticate official DeepSeek continuation collection. | [gguf-tools/quality-testing/collect_official.py:242](gguf-tools/quality-testing/collect_official.py#L242) |
+| `DS4_BATCHED_SESSIONS` | unset/empty defaults to 16; otherwise passed verbatim to --batched-session; the wrapper does not validate it | Sets the maximum batched-session count for the managed CUDA tensor-parallel server. | [run-nvidia-tp-server.sh:14](run-nvidia-tp-server.sh#L14) |
+| `DS4_CTX` | unset/empty defaults to 100000; otherwise passed verbatim to --ctx; the wrapper does not validate it | Sets the managed server context size. | [run-nvidia-tp-server.sh:9](run-nvidia-tp-server.sh#L9) |
+| `DS4_GGUF_DIR` | path; default repository gguf/ directory | Choose the model download directory. | [download_model.sh:23](download_model.sh#L23) |
+| `DS4_KV_DIR` | directory path; unset/empty defaults to /data/ds4-kv | Sets --kv-disk-dir for the managed server disk-backed KV cache. | [run-nvidia-tp-server.sh:12](run-nvidia-tp-server.sh#L12) |
+| `DS4_KV_SPACE_MB` | unset/empty defaults to 8192; otherwise passed verbatim to --kv-disk-space-mb; the wrapper does not validate it | Sets the managed server disk-KV capacity in MiB. | [run-nvidia-tp-server.sh:13](run-nvidia-tp-server.sh#L13) |
+| `DS4_LOCK_FILE` | lock-file path; unset/empty defaults to /tmp/ds4.lock | Selects the PID/instance lock inspected by start, stop, restart, and status; an explicit environment value is inherited by ds4-server. | [run-nvidia-tp-server.sh:15](run-nvidia-tp-server.sh#L15) |
+| `DS4_MODEL` | model path; unset/empty defaults to /home/antirez/models/deepseek-v4-gguf/DeepSeek-V4-Flash-MXFP4Experts-F16HC-F16Compressor-F16Indexer-Q8Attn-Q8Shared-Q8Out-chat-v2-mxfp4-0731.gguf; unreadable paths fail | Sets the target GGUF passed to the managed CUDA tensor-parallel server. | [run-nvidia-tp-server.sh:8](run-nvidia-tp-server.sh#L8) |
+| `DS4_SERVER_HOST` | host string; unset/empty defaults to 0.0.0.0 | Sets the HTTP listen address passed to the managed server. | [run-nvidia-tp-server.sh:10](run-nvidia-tp-server.sh#L10) |
+| `DS4_SERVER_LOG` | log-file path; unset/empty defaults to /tmp/ds4-server.log | Receives detached-server stdout/stderr and supplies the readiness probe and failure tail. | [run-nvidia-tp-server.sh:16](run-nvidia-tp-server.sh#L16) |
+| `DS4_SERVER_PORT` | unset/empty defaults to 8000; otherwise passed verbatim to --port; the wrapper does not validate it | Sets the HTTP listen port passed to the managed server. | [run-nvidia-tp-server.sh:11](run-nvidia-tp-server.sh#L11) |
+| `DS4_START_TIMEOUT` | positive decimal integer with no leading zero; unset/empty defaults to 180; invalid values fail when starting | Sets how many seconds detached startup waits for the lock owner and listening log marker. | [run-nvidia-tp-server.sh:17](run-nvidia-tp-server.sh#L17) |
+| `DS4_STOP_TIMEOUT` | positive decimal integer with no leading zero; unset/empty defaults to 120; invalid values fail when stopping | Sets how many seconds graceful stop waits after SIGTERM before failing. | [run-nvidia-tp-server.sh:18](run-nvidia-tp-server.sh#L18) |
+| `FLATTEN_DOWNLOADS` | exact integer 1 enables; unset or 0 preserves normal shard paths | Move downloaded Hugging Face files from nested cache paths into the requested output directory. | [download_model.sh:244](download_model.sh#L244) |
+| `FORCE_HF_DOWNLOAD` | exact integer 1 enables; unset or 0 uses the available downloader automatically | Force download_model.sh to use hf download instead of curl when available. | [download_model.sh:216](download_model.sh#L216) |
+| `HF_TOKEN` | secret string; unset tries cached Hugging Face token or unauthenticated download | Authenticate Hugging Face downloads. | [download_model.sh:28](download_model.sh#L28) |
+| `HOME` | Filesystem directory string. In ds4-agent, unset or empty falls back to "." for the default cache and history roots; the web helper applies the same fallback for its browser profile. A nonempty value roots .ds4/kvcache, .ds4_agent_history and .ds4/browser. | Choose the user's persistent ds4-agent cache, line-history and Chrome-profile base directory. | [ds4_agent.c:4023](ds4_agent.c#L4023) |
+| `OPENROUTER_API_KEY` | secret string; default credential when endpoint contains openrouter.ai; required unless --api-key-env selects another name | Authenticate OpenRouter continuation collection. | [gguf-tools/quality-testing/collect_official.py:242](gguf-tools/quality-testing/collect_official.py#L242) |
+
+
diff --git a/Makefile b/Makefile
index c58acb939b..784e10f22c 100644
--- a/Makefile
+++ b/Makefile
@@ -1,5 +1,6 @@
CC ?= cc
UNAME_S := $(shell uname -s)
+.DEFAULT_GOAL := all
ifeq ($(UNAME_S),Darwin)
NATIVE_CPU_FLAG ?= -mcpu=native
@@ -50,7 +51,7 @@ endif
NVCCFLAGS ?= -O3 -g -lineinfo --use_fast_math $(NVCC_ARCH_FLAGS) -Xcompiler $(NATIVE_CPU_FLAG) -Xcompiler -pthread
# Vendored llama.cpp mmq prefill tier (cuda/mmq/, see cuda/mmq/VENDOR.md).
MMQ_INCLUDES := -Icuda/mmq
-MMQ_OBJS := cuda/mmq/ds4_ggml_stubs.o cuda/mmq/ds4_mmq.o cuda/mmq/ds4_mmq_d2r.o cuda/mmq/quantize.o cuda/mmq/mmid.o cuda/mmq/mmvq.o cuda/mmq/ds4_repack.o
+MMQ_OBJS := cuda/mmq/ds4_ggml_stubs.o cuda/mmq/ds4_mmq.o cuda/mmq/ds4_mmq_d2r.o cuda/mmq/ds4_mmq_q4_16warp.o cuda/mmq/quantize.o cuda/mmq/mmid.o cuda/mmq/mmvq.o cuda/mmq/ds4_repack.o
CORE_OBJS = ds4.o ds4_image.o ds4_distributed.o ds4_tp.o ds4_ssd.o ds4_cuda.o ds4_layer_pack.o $(MMQ_OBJS)
CPU_CORE_OBJS = ds4_cpu.o ds4_image.o ds4_distributed.o ds4_tp.o ds4_ssd.o ds4_layer_pack.o
CUDA_LDLIBS ?= -lm -Xcompiler -pthread -L$(CUDA_HOME)/targets/sbsa-linux/lib -L$(CUDA_HOME)/lib64 -lcudart -lcublas
@@ -58,19 +59,29 @@ HIPCC ?= $(shell command -v hipcc 2>/dev/null || echo /opt/rocm/bin/hipcc)
ROCM_ARCH ?= gfx1151
ROCM_HOST_CFLAGS ?= -fPIC
ROCM_CFLAGS ?= -O3 -ffast-math -g -fno-finite-math-only -pthread -D__HIP_PLATFORM_AMD__ -Wno-unused-command-line-argument --offload-arch=$(ROCM_ARCH)
-ROCM_LDLIBS ?= -lm -pthread -lhipblas -lhipblaslt -lrocblas
+ROCM_LDLIBS ?= -lm -pthread -lhipblas -lrocblas
ROCM_MMQ_Y ?= 64
ROCM_MMQ_FLAGS := $(ROCM_CFLAGS) -std=c++17 -DGGML_USE_HIP -DDS4_HIP_MMQ_Y=$(ROCM_MMQ_Y) $(MMQ_INCLUDES)
ROCM_MMQ_OBJS := cuda/mmq/ds4_ggml_stubs.rocm.o cuda/mmq/ds4_mmq.rocm.o cuda/mmq/quantize.rocm.o cuda/mmq/mmid.rocm.o cuda/mmq/mmvq.rocm.o cuda/mmq/d2r_stubs.rocm.o
+ROCM_CORE_OBJS := ds4.o ds4_image.o ds4_distributed.o ds4_tp.o ds4_ssd.o ds4_rocm.o ds4_rocm_compat.o ds4_rocm_unavailable.o ds4_layer_pack.o $(ROCM_MMQ_OBJS)
DS4_LINK ?= $(NVCC) $(NVCCFLAGS)
DS4_LINK_LIBS ?= $(CUDA_LDLIBS)
METAL_LDLIBS := $(LDLIBS)
endif
-.PHONY: all help clean test test-rocm test-glm53-kda-rocm test-metal-session-batch test-mxfp4-cuda test-mxfp4-rocm test-cuda-session-batch test-cuda-mixed-batch dspark-acceptance dspark-verify-depth mtp-verify-depth cpu cuda cuda-spark cuda-generic cuda-regression strix-halo rocm
+.PHONY: all help clean test test-ssd environment-docs test-quantizer-indexer-q4 test-rocm test-glm53-kda-rocm test-metal-session-batch test-metal-session-batch-ssd test-metal-q4-streams test-metal-q4-prefill-pair test-metal-indexer-q4 test-metal-q4-attn-exactn test-metal-q4-attn-out-a-direct test-metal-q4-qb-f16-cache test-metal-q4-qb-f16-cache-timing test-metal-exactn-oracle test-metal-dspark-capture test-metal-argmax-top1 bench-metal-argmax-top1 test-metal-iq2-midonly test-metal-iq2-ssd-grouped-mm test-metal-iq2-live-index test-mxfp4-metal test-mxfp4-cuda test-mxfp4-rocm test-mmq-parity-cuda test-mmq-q4-grouped-q81-cuda test-mmq-q4-16warp-cuda test-rocm-q4-parity test-rocm-q4-dense test-rocm-q4-pair test-rocm-q4-prefill test-strix-rocm-q4-parity test-strix-rocm-q4-prefill test-strix-rocm-q4-prefill-long test-cuda-session-batch test-cuda-mixed-batch dspark-acceptance dspark-verify-depth rocm-dspark-acceptance rocm-dspark-verify-depth mtp-verify-depth cpu cuda cuda-spark cuda-generic cuda-regression strix-halo rocm cuda-iq2-moe-prefill-bench cuda-q4-prefill-bench rocm-iq2-moe-prefill-bench rocm-q4-prefill-bench
+
+gguf-tools/deepseek4-quantize: gguf-tools/deepseek4-quantize.c gguf-tools/quants.c gguf-tools/quants.h
+ $(MAKE) -C gguf-tools deepseek4-quantize
+
+tests/test_quantizer_indexer_q4: tests/test_quantizer_indexer_q4.c gguf-tools/quants.c gguf-tools/quants.h
+ $(CC) -O2 -Wall -Wextra -std=c99 -Igguf-tools -o $@ tests/test_quantizer_indexer_q4.c gguf-tools/quants.c $(LDLIBS)
+
+test-quantizer-indexer-q4: gguf-tools/deepseek4-quantize tests/test_quantizer_indexer_q4
+ ./tests/test_quantizer_indexer_q4 ./gguf-tools/deepseek4-quantize
ifeq ($(UNAME_S),Darwin)
-.PHONY: metal-decode-schedule-bench metal-prefill-variant-bench check-mxfp4-half-lut
+.PHONY: metal-decode-schedule-bench metal-prefill-variant-bench metal-q4-dense-pair-bench metal-q4-prefill-pair-bench metal-q4-mm-tail-cull-bench metal-q4-attn-out-a-direct-bench metal-iq2-moe-tail-cull-bench metal-iq2-moe-top8-pair-bench check-mxfp4-half-lut test-mxfp4-metal
all: ds4 ds4-server ds4-bench ds4-eval ds4-agent
@@ -79,10 +90,35 @@ help:
@echo " make Build Metal ./ds4, ./ds4-server, ./ds4-bench, ./ds4-eval, and ./ds4-agent"
@echo " make cpu Build CPU-only ./ds4, ./ds4-server, ./ds4-bench, ./ds4-eval, and ./ds4-agent"
@echo " make test Build and run tests"
+ @echo " make test-ssd Run the model suite with cold SSD streaming"
+ @echo " make test-quantizer-indexer-q4 Check direct F16-to-Q4_K indexer conversion"
+ @echo " make environment-docs Generate and verify the environment variable inventory"
+ @echo " make test-metal-session-batch-ssd Exact-logit Metal SSD union control/candidate oracle"
+ @echo " make test-metal-q4-streams Check resident Q4 Metal stream overlap"
+ @echo " make test-metal-q4-prefill-pair Runtime oracle for the M1-M4 Q4 prefill pair"
+ @echo " make test-metal-indexer-q4 Check the production-shape Q4_K indexer projection"
+ @echo " make test-metal-q4-attn-exactn Bitwise/canary oracle for M1-M4 SSD-prefill Q4 attention output"
+ @echo " make test-metal-q4-attn-out-a-direct Production-shape oracle for M1-M4 Q4 output-A direct routing"
+ @echo " make test-metal-q4-qb-f16-cache Oracle for M1-M4 Q4 q_b sidecar and transient F16 paths"
+ @echo " make test-metal-q4-qb-f16-cache-timing Compare Q4 direct, sidecar, and transient production at N=4096"
+ @echo " make test-metal-dspark-capture Check fused DSpark HC capture bitwise"
+ @echo " make test-metal-argmax-top1 Check the resident production-shape Metal decode argmax"
+ @echo " make bench-metal-argmax-top1 Time full argsort versus resident top-1 without GGUF/SSD"
+ @echo " make test-metal-iq2-midonly Check M1 IQ2 addr mid-only output and sentinels"
+ @echo " make test-metal-iq2-live-index Check IQ2 SSD live-cache index policy and fallback"
+ @echo " make test-rocm-q4-parity Run ROCm Q4_K dense/pair/prefill oracle (or SKIP without HIP)"
+ @echo " make test-rocm-q4-prefill Run ROCm Q4 tiled-prefill parity/canary oracle"
@echo " make metal-decode-schedule-bench Build the balanced Metal decode schedule benchmark"
@echo " make metal-prefill-variant-bench Build the balanced Metal prefill variant benchmark"
+ @echo " make metal-q4-dense-pair-bench Build the resident Q4 decode pair kernel benchmark"
+ @echo " make metal-q4-prefill-pair-bench Build the resident Q4 prefill pair F16-RHS benchmark"
+ @echo " make metal-q4-mm-tail-cull-bench Build the resident Q4 prefill tail-cull kernel benchmark"
+ @echo " make metal-q4-attn-out-a-direct-bench Build the resident Q4 attention output-A direct benchmark"
+ @echo " make metal-iq2-moe-tail-cull-bench Build the resident IQ2 pair MoE tail-cull benchmark"
+ @echo " make metal-iq2-moe-top8-pair-bench Build the resident GLM-shape IQ2 top-8 pair-fusion benchmark"
@echo " make check-mxfp4-half-lut Verify the checked-in MXFP4 half LUT matches the generator"
@echo " make test-mxfp4-metal Check the MXFP4 half LUT, then run Metal MXFP4 exactness tests"
+ @echo " make test-metal-exactn-oracle Compare Metal exact-N state with sequential decode"
@echo " make dspark-verify-depth Run DSpark speculative verification smoke if support GGUF is present"
@echo " make mtp-verify-depth Run legacy MTP speculative verification smoke if MTP GGUF is present"
@echo " make clean Remove build outputs"
@@ -114,6 +150,193 @@ tests/test_metal_session_batch: tests/test_metal_session_batch.o $(CORE_OBJS)
test-metal-session-batch: tests/test_metal_session_batch
DS4_TEST_MODEL="$(DS4_TEST_MODEL)" ./tests/test_metal_session_batch
+test-metal-session-batch-ssd: tests/test_metal_session_batch
+ env -u DS4_METAL_ENABLE_Q4_SSD_SESSION_UNION \
+ -u DS4_METAL_REQUIRE_EXACT_ROWS_PERSISTENT_CACHE \
+ -u DS4_TEST_SSD_UNION_POLICY_SWITCH \
+ DS4_METAL_DISABLE_Q4_SSD_SESSION_UNION=1 \
+ DS4_METAL_REQUIRE_Q4_SSD_SESSION_UNION=1 \
+ DS4_METAL_DISABLE_EXACT_ROWS_PERSISTENT_CACHE=1 \
+ DS4_TEST_SSD_STREAMING=1 DS4_TEST_SESSION_COUNT=5 \
+ DS4_TEST_SSD_CACHE_EXPERTS="$(DS4_TEST_SSD_CACHE_EXPERTS)" \
+ DS4_TEST_SESSION_BATCH_TIMING=1 \
+ DS4_TEST_SESSION_BATCH_ARM=control \
+ DS4_TEST_MODEL="$(DS4_TEST_MODEL)" \
+ ./tests/test_metal_session_batch
+ env -u DS4_METAL_DISABLE_Q4_SSD_SESSION_UNION \
+ -u DS4_METAL_ENABLE_Q4_SSD_SESSION_UNION \
+ -u DS4_METAL_DISABLE_EXACT_ROWS_PERSISTENT_CACHE \
+ DS4_METAL_REQUIRE_Q4_SSD_SESSION_UNION=1 \
+ DS4_METAL_REQUIRE_EXACT_ROWS_PERSISTENT_CACHE=1 \
+ DS4_TEST_SSD_STREAMING=1 DS4_TEST_SESSION_COUNT=5 \
+ DS4_TEST_SSD_UNION_POLICY_SWITCH=1 \
+ DS4_TEST_SSD_CACHE_EXPERTS="$(DS4_TEST_SSD_CACHE_EXPERTS)" \
+ DS4_TEST_SESSION_BATCH_TIMING=1 \
+ DS4_TEST_SESSION_BATCH_ARM=candidate \
+ DS4_TEST_MODEL="$(DS4_TEST_MODEL)" \
+ ./tests/test_metal_session_batch
+
+tests/test_metal_q4_streams.o: tests/test_metal_q4_streams.c ds4.h ds4_gpu.h
+ $(CC) $(CFLAGS) -DDS4_TEST_HOOKS -I. -c -o $@ $<
+
+tests/test_metal_q4_streams: tests/test_metal_q4_streams.o ds4_metal_test_hooks.o ds4_image.o ds4_distributed.o ds4_tp.o ds4_ssd.o ds4_metal.o ds4_layer_pack.o
+ $(CC) $(CFLAGS) -o $@ $^ $(METAL_LDLIBS)
+
+test-metal-q4-streams: tests/test_metal_q4_streams
+ env -u DS4_METAL_MODEL_UNTRACKED ./tests/test_metal_q4_streams
+ DS4_METAL_MODEL_UNTRACKED=1 ./tests/test_metal_q4_streams
+
+tests/test_metal_q4_prefill_pair.o: tests/test_metal_q4_prefill_pair.c ds4_gpu.h
+ $(CC) $(CFLAGS) -I. -c -o $@ $<
+
+tests/test_metal_q4_prefill_pair: tests/test_metal_q4_prefill_pair.o ds4_image.o ds4_metal.o
+ $(CC) $(CFLAGS) -o $@ $^ $(METAL_LDLIBS)
+
+test-metal-q4-prefill-pair: tests/test_metal_q4_prefill_pair
+ env -u DS4_METAL_ENABLE_Q4_PREFILL_PAIR_F16_RHS \
+ -u DS4_METAL_DISABLE_Q4_PREFILL_PAIR_F16_RHS \
+ -u DS4_METAL_REQUIRE_Q4_PREFILL_PAIR_F16_RHS \
+ -u DS4_METAL_DISABLE_Q4_DENSE_PAIR \
+ -u DS4_METAL_DISABLE_CONTIG_F32_F16_COPY \
+ -u DS4_METAL_MODEL_UNTRACKED \
+ -u DS4_METAL_UNRETAINED_COMMAND_BUFFERS \
+ ./tests/test_metal_q4_prefill_pair
+ env -u DS4_METAL_ENABLE_Q4_PREFILL_PAIR_F16_RHS \
+ -u DS4_METAL_DISABLE_Q4_PREFILL_PAIR_F16_RHS \
+ -u DS4_METAL_REQUIRE_Q4_PREFILL_PAIR_F16_RHS \
+ -u DS4_METAL_DISABLE_Q4_DENSE_PAIR \
+ -u DS4_METAL_DISABLE_CONTIG_F32_F16_COPY \
+ -u DS4_METAL_MODEL_UNTRACKED \
+ DS4_METAL_UNRETAINED_COMMAND_BUFFERS=1 \
+ ./tests/test_metal_q4_prefill_pair
+
+tests/test_metal_indexer_q4.o: tests/test_metal_indexer_q4.c ds4_gpu.h
+ $(CC) $(CFLAGS) -I. -c -o $@ $<
+
+tests/test_metal_indexer_q4: tests/test_metal_indexer_q4.o ds4_image.o ds4_metal.o
+ $(CC) $(CFLAGS) -o $@ $^ $(METAL_LDLIBS)
+
+test-metal-indexer-q4: tests/test_metal_indexer_q4
+ ./tests/test_metal_indexer_q4
+
+tests/test_metal_q4_attn_exactn.o: tests/test_metal_q4_attn_exactn.c ds4_gpu.h
+ $(CC) $(CFLAGS) -I. -c -o $@ $<
+
+tests/test_metal_q4_attn_exactn: tests/test_metal_q4_attn_exactn.o ds4_image.o ds4_metal.o
+ $(CC) $(CFLAGS) -o $@ $^ $(METAL_LDLIBS)
+
+test-metal-q4-attn-exactn: tests/test_metal_q4_attn_exactn
+ env -u DS4_METAL_ENABLE_Q4_SSD_PREFILL_ATTN_OUT_EXACTN \
+ -u DS4_METAL_DISABLE_Q4_SSD_PREFILL_ATTN_OUT_EXACTN \
+ -u DS4_METAL_REQUIRE_Q4_SSD_PREFILL_ATTN_OUT_EXACTN \
+ -u DS4_METAL_DISABLE_Q4_SSD_PREFILL_ATTN_OUT_SCALE_META \
+ -u DS4_METAL_REQUIRE_Q4_SSD_PREFILL_ATTN_OUT_SCALE_META \
+ -u DS4_METAL_DISABLE_Q4_MV_CLASSIC \
+ ./tests/test_metal_q4_attn_exactn
+
+tests/test_metal_q4_attn_out_a_direct.o: tests/test_metal_q4_attn_out_a_direct.c ds4_gpu.h
+ $(CC) $(CFLAGS) -I. -c -o $@ $<
+
+tests/test_metal_q4_attn_out_a_direct: tests/test_metal_q4_attn_out_a_direct.o ds4_image.o ds4_metal.o
+ $(CC) $(CFLAGS) -o $@ $^ $(METAL_LDLIBS)
+
+test-metal-q4-attn-out-a-direct: tests/test_metal_q4_attn_out_a_direct
+ env -u DS4_METAL_DISABLE_Q4_ATTN_OUT_A_DIRECT \
+ -u DS4_METAL_REQUIRE_Q4_ATTN_OUT_A_DIRECT \
+ -u DS4_METAL_DISABLE_Q4_ATTN_OUT_B_F16_RHS \
+ -u DS4_METAL_REQUIRE_Q4_ATTN_OUT_B_F16_RHS \
+ ./tests/test_metal_q4_attn_out_a_direct
+
+tests/test_metal_q4_qb_f16_cache.o: tests/test_metal_q4_qb_f16_cache.c ds4_gpu.h
+ $(CC) $(CFLAGS) -I. -c -o $@ $<
+
+tests/test_metal_q4_qb_f16_cache: tests/test_metal_q4_qb_f16_cache.o ds4_image.o ds4_metal.o
+ $(CC) $(CFLAGS) -o $@ $^ $(METAL_LDLIBS)
+
+test-metal-q4-qb-f16-cache: tests/test_metal_q4_qb_f16_cache
+ env -u DS4_METAL_DISABLE_Q4_ATTN_Q_B_F16_CACHE \
+ -u DS4_METAL_ENABLE_Q4_ATTN_Q_B_F16_CACHE_WITH_SSD_STREAMING \
+ -u DS4_METAL_DISABLE_Q4_ATTN_Q_B_F16_RHS \
+ -u DS4_METAL_DISABLE_Q4_ATTN_Q_B_TRANSIENT_F16 \
+ -u DS4_METAL_Q4_ATTN_Q_B_TRANSIENT_F16_MIN_TOKENS \
+ -u DS4_METAL_UNRETAINED_COMMAND_BUFFERS \
+ -u DS4_TEST_METAL_Q4_QB_F16_CACHE_TIMING \
+ -u DS4_TEST_METAL_Q4_QB_F16_CACHE_TIMING_TOKENS \
+ DS4_METAL_Q4_ATTN_Q_B_F16_CACHE_MIN_TOKENS=32 \
+ DS4_METAL_REQUIRE_Q4_ATTN_Q_B_F16_CACHE=1 \
+ ./tests/test_metal_q4_qb_f16_cache
+ env -u DS4_METAL_DISABLE_Q4_ATTN_Q_B_F16_CACHE \
+ -u DS4_METAL_ENABLE_Q4_ATTN_Q_B_F16_CACHE_WITH_SSD_STREAMING \
+ -u DS4_METAL_DISABLE_Q4_ATTN_Q_B_F16_RHS \
+ -u DS4_METAL_DISABLE_Q4_ATTN_Q_B_TRANSIENT_F16 \
+ -u DS4_METAL_Q4_ATTN_Q_B_TRANSIENT_F16_MIN_TOKENS \
+ -u DS4_TEST_METAL_Q4_QB_F16_CACHE_TIMING \
+ -u DS4_TEST_METAL_Q4_QB_F16_CACHE_TIMING_TOKENS \
+ DS4_METAL_UNRETAINED_COMMAND_BUFFERS=1 \
+ DS4_METAL_Q4_ATTN_Q_B_F16_CACHE_MIN_TOKENS=32 \
+ DS4_METAL_REQUIRE_Q4_ATTN_Q_B_F16_CACHE=1 \
+ ./tests/test_metal_q4_qb_f16_cache
+
+test-metal-q4-qb-f16-cache-timing: tests/test_metal_q4_qb_f16_cache
+ env -u DS4_METAL_DISABLE_Q4_ATTN_Q_B_F16_CACHE \
+ -u DS4_METAL_ENABLE_Q4_ATTN_Q_B_F16_CACHE_WITH_SSD_STREAMING \
+ -u DS4_METAL_DISABLE_Q4_ATTN_Q_B_F16_RHS \
+ -u DS4_METAL_DISABLE_Q4_ATTN_Q_B_TRANSIENT_F16 \
+ -u DS4_METAL_Q4_ATTN_Q_B_TRANSIENT_F16_MIN_TOKENS \
+ DS4_METAL_Q4_ATTN_Q_B_F16_CACHE_MIN_TOKENS=32 \
+ DS4_METAL_REQUIRE_Q4_ATTN_Q_B_F16_CACHE=1 \
+ DS4_TEST_METAL_Q4_QB_F16_CACHE_TIMING=1 \
+ DS4_TEST_METAL_Q4_QB_F16_CACHE_TIMING_TOKENS=4096 \
+ ./tests/test_metal_q4_qb_f16_cache
+
+tests/test_metal_dspark_capture.o: tests/test_metal_dspark_capture.c ds4_gpu.h
+ $(CC) $(CFLAGS) -I. -c -o $@ $<
+
+tests/test_metal_dspark_capture: tests/test_metal_dspark_capture.o ds4_image.o ds4_metal.o
+ $(CC) $(CFLAGS) -o $@ $^ $(METAL_LDLIBS)
+
+test-metal-dspark-capture: tests/test_metal_dspark_capture
+ ./tests/test_metal_dspark_capture
+
+tests/test_metal_argmax_top1.o: tests/test_metal_argmax_top1.c ds4_gpu.h
+ $(CC) $(CFLAGS) -fno-fast-math -I. -c -o $@ $<
+
+tests/test_metal_argmax_top1: tests/test_metal_argmax_top1.o ds4_image.o ds4_metal.o
+ $(CC) $(CFLAGS) -o $@ $^ $(METAL_LDLIBS)
+
+test-metal-argmax-top1: tests/test_metal_argmax_top1
+ env -u DS4_TEST_METAL_ARGMAX_TOP1_TIMING ./tests/test_metal_argmax_top1
+
+bench-metal-argmax-top1: tests/test_metal_argmax_top1
+ DS4_TEST_METAL_ARGMAX_TOP1_TIMING=1 ./tests/test_metal_argmax_top1
+
+tests/test_metal_iq2_midonly.o: tests/test_metal_iq2_midonly.c ds4_gpu.h
+ $(CC) $(CFLAGS) -I. -c -o $@ $<
+
+tests/test_metal_iq2_midonly: tests/test_metal_iq2_midonly.o ds4_image.o ds4_metal.o
+ $(CC) $(CFLAGS) -o $@ $^ $(METAL_LDLIBS)
+
+test-metal-iq2-midonly: tests/test_metal_iq2_midonly
+ ./tests/test_metal_iq2_midonly
+
+tests/test_metal_iq2_ssd_grouped_mm.o: tests/test_metal_iq2_ssd_grouped_mm.c ds4_gpu.h
+ $(CC) $(CFLAGS) -I. -c -o $@ $<
+
+tests/test_metal_iq2_ssd_grouped_mm: tests/test_metal_iq2_ssd_grouped_mm.o ds4_image.o ds4_metal.o
+ $(CC) $(CFLAGS) -o $@ $^ $(METAL_LDLIBS)
+
+test-metal-iq2-ssd-grouped-mm: tests/test_metal_iq2_ssd_grouped_mm
+ ./tests/test_metal_iq2_ssd_grouped_mm
+
+tests/test_metal_iq2_live_index.o: tests/test_metal_iq2_live_index.c ds4_gpu.h
+ $(CC) $(CFLAGS) -I. -c -o $@ $<
+
+tests/test_metal_iq2_live_index: tests/test_metal_iq2_live_index.o ds4_image.o ds4_metal.o
+ $(CC) $(CFLAGS) -o $@ $^ $(METAL_LDLIBS)
+
+test-metal-iq2-live-index: tests/test_metal_iq2_live_index
+ ./tests/test_metal_iq2_live_index
+
speed-bench/metal_decode_schedule_bench.o: speed-bench/metal_decode_schedule_bench.c ds4.h
$(CC) $(CFLAGS) -I. -c -o $@ $<
@@ -130,10 +353,60 @@ speed-bench/metal_prefill_variant_bench: speed-bench/metal_prefill_variant_bench
metal-prefill-variant-bench: speed-bench/metal_prefill_variant_bench
+ds4_metal_test_hooks.o: ds4.c ds4.h ds4_gpu.h ds4_gpu_mgpu.h ds4_image.h ds4_layer_pack.h
+ $(CC) $(CFLAGS) -Wno-unused-function -DDS4_TEST_HOOKS -c -o $@ ds4.c
+
+tests/test_metal_exactn_oracle.o: tests/test_metal_exactn_oracle.c ds4.h
+ $(CC) $(CFLAGS) -DDS4_TEST_HOOKS -I. -c -o $@ $<
+
+tests/test_metal_exactn_oracle: tests/test_metal_exactn_oracle.o ds4_metal_test_hooks.o ds4_image.o ds4_distributed.o ds4_tp.o ds4_ssd.o ds4_metal.o ds4_layer_pack.o
+ $(CC) $(CFLAGS) -o $@ $^ $(METAL_LDLIBS)
+
+test-metal-exactn-oracle: tests/test_metal_exactn_oracle
+ DS4_TEST_REQUIRE_MODEL=1 \
+ DS4_TEST_MODEL="$(DS4_TEST_MODEL)" \
+ ./tests/test_metal_exactn_oracle
+
+speed-bench/metal_q4_dense_pair_bench: speed-bench/metal_q4_dense_pair_bench.m $(METAL_SRCS)
+ $(CC) $(OBJCFLAGS) -o $@ $< $(METAL_LDLIBS)
+
+metal-q4-dense-pair-bench: speed-bench/metal_q4_dense_pair_bench
+
+speed-bench/metal_q4_prefill_pair_bench: speed-bench/metal_q4_prefill_pair_bench.m $(METAL_SRCS)
+ $(CC) $(OBJCFLAGS) -o $@ $< $(METAL_LDLIBS)
+
+metal-q4-prefill-pair-bench: speed-bench/metal_q4_prefill_pair_bench
+
+speed-bench/metal_q4_mm_tail_cull_bench: speed-bench/metal_q4_mm_tail_cull_bench.m $(METAL_SRCS)
+ $(CC) $(OBJCFLAGS) -o $@ $< $(METAL_LDLIBS)
+
+metal-q4-mm-tail-cull-bench: speed-bench/metal_q4_mm_tail_cull_bench
+
+speed-bench/metal_q4_attn_out_a_direct_bench: speed-bench/metal_q4_attn_out_a_direct_bench.m $(METAL_SRCS)
+ $(CC) $(OBJCFLAGS) -o $@ $< $(METAL_LDLIBS)
+
+metal-q4-attn-out-a-direct-bench: speed-bench/metal_q4_attn_out_a_direct_bench
+
+speed-bench/metal_iq2_moe_tail_cull_bench.o: speed-bench/metal_iq2_moe_tail_cull_bench.c ds4_gpu.h
+ $(CC) $(CFLAGS) -I. -c -o $@ $<
+
+speed-bench/metal_iq2_moe_tail_cull_bench: speed-bench/metal_iq2_moe_tail_cull_bench.o ds4_image.o ds4_metal.o
+ $(CC) $(CFLAGS) -o $@ $^ $(METAL_LDLIBS)
+
+metal-iq2-moe-tail-cull-bench: speed-bench/metal_iq2_moe_tail_cull_bench
+
+speed-bench/metal_iq2_moe_top8_pair_bench.o: speed-bench/metal_iq2_moe_top8_pair_bench.c speed-bench/metal_iq2_moe_tail_cull_bench.c ds4_gpu.h
+ $(CC) $(CFLAGS) -I. -c -o $@ $<
+
+speed-bench/metal_iq2_moe_top8_pair_bench: speed-bench/metal_iq2_moe_top8_pair_bench.o ds4_image.o ds4_metal.o
+ $(CC) $(CFLAGS) -o $@ $^ $(METAL_LDLIBS)
+
+metal-iq2-moe-top8-pair-bench: speed-bench/metal_iq2_moe_top8_pair_bench
+
tests/test_mxfp4_metal.o: tests/test_mxfp4_metal.c ds4_gpu.h
$(CC) $(CFLAGS) -I. -c -o $@ $<
-tests/test_mxfp4_metal: tests/test_mxfp4_metal.o ds4_metal.o
+tests/test_mxfp4_metal: tests/test_mxfp4_metal.o ds4_image.o ds4_metal.o
$(CC) $(CFLAGS) -o $@ $^ $(METAL_LDLIBS)
check-mxfp4-half-lut:
@@ -159,12 +432,26 @@ help:
@echo " make cuda-spark Build CUDA for DGX Spark / GB10"
@echo " make cuda-generic Build CUDA for a generic local CUDA GPU"
@echo " make cuda CUDA_ARCH=sm_N Build CUDA with an explicit nvcc -arch value"
+ @echo " make test-mmq-parity-cuda CUDA_ARCH=sm_N Run quantized CUDA kernel parity tests"
+ @echo " make test-mmq-q4-grouped-q81-cuda CUDA_ARCH=sm_N Run focused grouped Q8_1 byte-parity tests"
+ @echo " make test-mmq-q4-16warp-cuda CUDA_ARCH=sm_N Run focused Q4 16-warp bitwise/canary oracle"
+ @echo " make test-rocm-q4-parity Run ROCm Q4_K dense/pair/prefill oracle"
+ @echo " make test-strix-rocm-q4-prefill Require gfx1151 and run tiled-prefill oracle"
+ @echo " make test-strix-rocm-q4-parity Require a visible gfx1151 device and run the Q4 tests"
@echo " make strix-halo Build ROCm for Strix Halo / gfx1151"
@echo " make rocm Alias for make strix-halo"
+ @echo " make rocm-dspark-acceptance Build ROCm and run the DSpark acceptance fixture"
+ @echo " make rocm-dspark-verify-depth Build ROCm and run the DSpark verifier invariant"
@echo " make test-mxfp4-rocm Build and run the synthetic ROCm MXFP4 MoE test"
+ @echo " make rocm-iq2-moe-prefill-bench Build the resident ROCm IQ2/Q2 WMMA A/B harness"
+ @echo " make rocm-q4-prefill-bench Build the resident ROCm Q4 projection/WMMA A/B harness"
+ @echo " make cuda-iq2-moe-prefill-bench CUDA_ARCH=sm_N Build the resident CUDA IQ2/Q2 profiling harness"
+ @echo " make cuda-q4-prefill-bench CUDA_ARCH=sm_N Build the resident CUDA Q4 dense/pair/q_b/output-A/output-B harness"
@echo " make test-rocm Core regression suite on ROCm-only hosts"
@echo " make cpu Build CPU-only ./ds4, ./ds4-server, ./ds4-bench, ./ds4-eval, and ./ds4-agent"
@echo " make test Build and run tests"
+ @echo " make test-ssd Run the model suite with cold SSD streaming"
+ @echo " make environment-docs Generate and verify the environment variable inventory"
@echo " make dspark-verify-depth Run DSpark speculative verification smoke if support GGUF is present"
@echo " make mtp-verify-depth Run legacy MTP speculative verification smoke if MTP GGUF is present"
@echo " make clean Remove build outputs"
@@ -184,8 +471,8 @@ cuda:
$(MAKE) -B ds4 ds4-server ds4-bench ds4-eval ds4-agent CUDA_ARCH="$(CUDA_ARCH)"
strix-halo:
- $(MAKE) -B ds4 ds4-server ds4-bench ds4-eval ds4-agent \
- CORE_OBJS="ds4.o ds4_image.o ds4_distributed.o ds4_tp.o ds4_ssd.o ds4_rocm.o ds4_rocm_compat.o ds4_rocm_unavailable.o ds4_layer_pack.o $(ROCM_MMQ_OBJS)" \
+ $(MAKE) -B ds4 ds4-server ds4-bench ds4-eval ds4-agent ds4_test \
+ CORE_OBJS="$(ROCM_CORE_OBJS)" \
CFLAGS="$(CFLAGS) $(ROCM_HOST_CFLAGS) -DDS4_ROCM_BUILD" \
DS4_LINK="$(HIPCC) $(ROCM_CFLAGS)" \
DS4_LINK_LIBS="$(ROCM_LDLIBS)"
@@ -200,7 +487,7 @@ test-rocm:
$(MAKE) -B ds4_test ds4_agent_test ds4-eval q4k-dot-test mxfp4-dot-test \
tests/test_layer_pack tests/test_engine_mgpu_placement tests/test_gpu_args tests/test_prompt_prefix \
ds4 ds4-server ds4-bench ds4-agent \
- CORE_OBJS="ds4.o ds4_image.o ds4_distributed.o ds4_tp.o ds4_ssd.o ds4_rocm.o ds4_rocm_compat.o ds4_rocm_unavailable.o ds4_layer_pack.o $(ROCM_MMQ_OBJS)" \
+ CORE_OBJS="$(ROCM_CORE_OBJS)" \
CFLAGS="$(CFLAGS) $(ROCM_HOST_CFLAGS) -DDS4_ROCM_BUILD" \
DS4_LINK="$(HIPCC) $(ROCM_CFLAGS)" \
DS4_LINK_LIBS="$(ROCM_LDLIBS)"
@@ -213,6 +500,41 @@ test-rocm:
./tests/test_gpu_args_cli.sh
./tests/test_prompt_prefix
+rocm-dspark-acceptance:
+ @if [ ! -f "$(DS4_DSPARK_MODEL)" ]; then \
+ echo "rocm-dspark-acceptance: missing model $(DS4_DSPARK_MODEL)" >&2; \
+ exit 1; \
+ elif [ ! -f "$(DS4_DSPARK_SUPPORT)" ]; then \
+ echo "rocm-dspark-acceptance: missing DSpark support $(DS4_DSPARK_SUPPORT)" >&2; \
+ exit 1; \
+ fi
+ $(MAKE) -B ds4 \
+ CORE_OBJS="$(ROCM_CORE_OBJS)" \
+ CFLAGS="$(CFLAGS) $(ROCM_HOST_CFLAGS) -DDS4_ROCM_BUILD" \
+ DS4_LINK="$(HIPCC) $(ROCM_CFLAGS)" \
+ DS4_LINK_LIBS="$(ROCM_LDLIBS)"
+ DS4_DSPARK_MODEL="$(DS4_DSPARK_MODEL)" \
+ DS4_DSPARK_SUPPORT="$(DS4_DSPARK_SUPPORT)" \
+ DS4_DSPARK_FIXTURE_BACKEND=rocm \
+ sh tests/dspark_acceptance_fixture.sh
+
+rocm-dspark-verify-depth:
+ @if [ ! -f "$(DS4_TEST_MODEL)" ]; then \
+ echo "rocm-dspark-verify-depth: missing model $(DS4_TEST_MODEL)" >&2; \
+ exit 1; \
+ elif [ ! -f "$(DS4_DSPARK_SUPPORT)" ]; then \
+ echo "rocm-dspark-verify-depth: missing DSpark support $(DS4_DSPARK_SUPPORT)" >&2; \
+ exit 1; \
+ fi
+ $(MAKE) -B ds4_test \
+ CORE_OBJS="$(ROCM_CORE_OBJS)" \
+ CFLAGS="$(CFLAGS) $(ROCM_HOST_CFLAGS) -DDS4_ROCM_BUILD" \
+ DS4_LINK="$(HIPCC) $(ROCM_CFLAGS)" \
+ DS4_LINK_LIBS="$(ROCM_LDLIBS)"
+ DS4_TEST_MODEL="$(DS4_TEST_MODEL)" \
+ DS4_TEST_DSPARK="$(DS4_DSPARK_SUPPORT)" \
+ ./ds4_test --dspark-verify-depth
+
ds4: ds4_cli.o ds4_help.o ds4_prompt_prefix.o linenoise.o ds4_gpu_args.o $(CORE_OBJS)
$(DS4_LINK) -o $@ $^ $(DS4_LINK_LIBS)
@@ -249,9 +571,65 @@ tests/test_mxfp4_cuda: tests/test_mxfp4_cuda.cu $(MMQ_OBJS)
test-mxfp4-cuda: tests/test_mxfp4_cuda
./tests/test_mxfp4_cuda
+
+cuda/mmq/test/test_mmq_parity: cuda/mmq/test/test_mmq_parity.cu cuda/mmq/ds4_mmq.h $(MMQ_OBJS)
+ $(NVCC) $(NVCCFLAGS) -std=c++17 $(MMQ_INCLUDES) -o $@ $< $(MMQ_OBJS) $(CUDA_LDLIBS)
+
+test-mmq-parity-cuda: cuda/mmq/test/test_mmq_parity
+ ./cuda/mmq/test/test_mmq_parity
+
+test-mmq-q4-grouped-q81-cuda: cuda/mmq/test/test_mmq_parity
+ ./cuda/mmq/test/test_mmq_parity --q4-grouped-q81
+
+test-mmq-q4-16warp-cuda: cuda/mmq/test/test_mmq_parity
+ ./cuda/mmq/test/test_mmq_parity --q4-16warp
+
+speed-bench/gpu_iq2_moe_prefill_bench_rocm.o: speed-bench/gpu_iq2_moe_prefill_bench.c ds4_gpu.h
+ $(CC) $(filter-out -ffast-math,$(CFLAGS)) $(ROCM_HOST_CFLAGS) -std=c11 -DDS4_ROCM_BUILD -DDS4_BENCH_ROCM -I. -c -o $@ $<
+
+speed-bench/gpu_iq2_moe_prefill_bench_rocm: speed-bench/gpu_iq2_moe_prefill_bench_rocm.o ds4_image.o ds4_rocm.o $(ROCM_MMQ_OBJS)
+ $(HIPCC) $(ROCM_CFLAGS) -o $@ $^ $(ROCM_LDLIBS)
+
+rocm-iq2-moe-prefill-bench:
+ $(MAKE) --no-print-directory -B speed-bench/gpu_iq2_moe_prefill_bench_rocm ROCM_ARCH="$(ROCM_ARCH)"
+
+speed-bench/rocm_q4_prefill_bench.o: speed-bench/rocm_q4_prefill_bench.cpp ds4_gpu.h
+ $(HIPCC) $(ROCM_CFLAGS) -DDS4_ROCM_BUILD -std=c++17 -fno-fast-math -I. -c -o $@ $<
+
+speed-bench/rocm_q4_prefill_bench: speed-bench/rocm_q4_prefill_bench.o ds4_image.o ds4_rocm.o $(ROCM_MMQ_OBJS) ds4_rocm_compat.o ds4_rocm_unavailable.o
+ $(HIPCC) $(ROCM_CFLAGS) -o $@ $^ $(ROCM_LDLIBS)
+
+rocm-q4-prefill-bench:
+ $(MAKE) --no-print-directory -B speed-bench/rocm_q4_prefill_bench ROCM_ARCH="$(ROCM_ARCH)"
+
+speed-bench/gpu_iq2_moe_prefill_bench_cuda.o: speed-bench/gpu_iq2_moe_prefill_bench.c ds4_gpu.h
+ $(CC) $(filter-out -ffast-math,$(CFLAGS)) -std=c11 -DDS4_BENCH_CUDA -I. -c -o $@ $<
+
+speed-bench/gpu_iq2_moe_prefill_bench_cuda: speed-bench/gpu_iq2_moe_prefill_bench_cuda.o ds4_image.o ds4_cuda.o $(MMQ_OBJS)
+ $(NVCC) $(NVCCFLAGS) -std=c++17 $(MMQ_INCLUDES) -o $@ $^ $(CUDA_LDLIBS)
+
+cuda-iq2-moe-prefill-bench:
+ $(MAKE) --no-print-directory -B speed-bench/gpu_iq2_moe_prefill_bench_cuda CUDA_ARCH="$(CUDA_ARCH)"
+
+speed-bench/cuda_q4_prefill_bench.o: speed-bench/cuda_q4_prefill_bench.cu ds4_gpu.h cuda/mmq/ds4_mmq.h cuda/mmq/ds4_mmq_q4_16warp.cuh
+ $(NVCC) $(NVCCFLAGS) -std=c++17 -DDS4_BENCH_CUDA -I. -c -o $@ $<
+
+speed-bench/cuda_q4_prefill_bench: speed-bench/cuda_q4_prefill_bench.o ds4_image.o ds4_cuda.o $(MMQ_OBJS)
+ $(NVCC) $(NVCCFLAGS) -std=c++17 $(MMQ_INCLUDES) -o $@ $^ $(CUDA_LDLIBS)
+
+cuda-q4-prefill-bench:
+ @if [ -z "$(strip $(CUDA_ARCH))" ]; then \
+ echo "error: specify CUDA_ARCH, for example: make cuda-q4-prefill-bench CUDA_ARCH=sm_121"; \
+ exit 2; \
+ fi
+ $(MAKE) --no-print-directory -B speed-bench/cuda_q4_prefill_bench CUDA_ARCH="$(CUDA_ARCH)"
endif
-ds4.o: ds4.c ds4.h ds4_ssd.h ds4_distributed.h ds4_gpu.h
+environment-docs:
+ python3 scripts/generate_environment_variables.py
+ python3 scripts/generate_environment_variables.py --check
+
+ds4.o: ds4.c ds4.h ds4_ssd.h ds4_distributed.h ds4_gpu.h ds4_image.h
$(CC) $(CFLAGS) -c -o $@ ds4.c
ds4_image.o: ds4_image.c ds4_image.h third_party/iris/jpeg.h third_party/iris/png.h
@@ -311,7 +689,7 @@ rax.o: rax.c rax.h rax_malloc.h
linenoise.o: linenoise.c linenoise.h
$(CC) $(CFLAGS) -c -o $@ linenoise.c
-ds4_cpu.o: ds4.c ds4.h ds4_ssd.h ds4_distributed.h ds4_gpu.h
+ds4_cpu.o: ds4.c ds4.h ds4_ssd.h ds4_distributed.h ds4_gpu.h ds4_image.h
$(CC) $(CFLAGS) -Wno-unused-function -DDS4_NO_GPU -c -o $@ ds4.c
ds4_cli_cpu.o: ds4_cli.c ds4.h ds4_ssd.h ds4_distributed.h ds4_help.h ds4_prompt_prefix.h linenoise.h
@@ -332,7 +710,7 @@ ds4_eval_cpu.o: ds4_eval.c ds4.h ds4_ssd.h ds4_distributed.h ds4_help.h
ds4_agent_cpu.o: ds4_agent.c ds4.h ds4_ssd.h ds4_distributed.h ds4_help.h ds4_prompt_prefix.h ds4_kvstore.h ds4_web.h linenoise.h
$(CC) $(CFLAGS) -DDS4_NO_GPU -c -o $@ ds4_agent.c
-ds4_metal.o: ds4_metal.m ds4_gpu.h $(METAL_SRCS)
+ds4_metal.o: ds4_metal.m ds4_gpu.h ds4_image.h $(METAL_SRCS)
$(CC) $(OBJCFLAGS) -c -o $@ ds4_metal.m
tests/test_glm53_kda.o: tests/test_glm53_kda.c ds4_gpu.h
@@ -365,10 +743,10 @@ tests/test_deepseek4_vision_image: tests/test_deepseek4_vision_image.o ds4_image
$(CC) $(CFLAGS) -o $@ $^ -lm
ifeq ($(UNAME_S),Darwin)
-$(GLM53_KDA_TEST): tests/test_glm53_kda.o ds4_metal.o
+$(GLM53_KDA_TEST): tests/test_glm53_kda.o ds4_image.o ds4_metal.o
$(CC) $(CFLAGS) -o $@ $^ $(METAL_LDLIBS)
else
-$(GLM53_KDA_TEST): tests/test_glm53_kda.o ds4_cuda.o $(MMQ_OBJS)
+$(GLM53_KDA_TEST): tests/test_glm53_kda.o ds4_image.o ds4_cuda.o $(MMQ_OBJS)
$(NVCC) $(NVCCFLAGS) -o $@ $^ $(CUDA_LDLIBS)
endif
@@ -379,7 +757,7 @@ test-glm53-kda: $(GLM53_KDA_TEST)
tests/test_glm53_kda_rocm.o: tests/test_glm53_kda.c ds4_gpu.h
$(CC) $(filter-out -ffast-math,$(CFLAGS)) $(ROCM_HOST_CFLAGS) -DDS4_ROCM_BUILD -I. -c -o $@ $<
-$(GLM53_KDA_ROCM_TEST): tests/test_glm53_kda_rocm.o ds4_rocm.o
+$(GLM53_KDA_ROCM_TEST): tests/test_glm53_kda_rocm.o ds4_image.o ds4_rocm.o
$(HIPCC) $(ROCM_CFLAGS) -o $@ $^ $(ROCM_LDLIBS)
test-glm53-kda-rocm: $(GLM53_KDA_ROCM_TEST)
@@ -391,15 +769,18 @@ ds4_cuda.o: ds4_cuda.cu ds4_gpu.h ds4_gpu_mgpu.h ds4_glm53_vision_gpu.cuh ds4_de
# Vendored mmq pieces (see cuda/mmq/VENDOR.md). ds4_mmq.cu transitively
# pulls in mmq.cuh which has heavy template instantiation -- each piece
# compiles in its own TU and links in.
-cuda/mmq/ds4_ggml_stubs.o: cuda/mmq/ds4_ggml_stubs.cu cuda/mmq/ds4_ggml_stubs.h cuda/mmq/common.cuh
+cuda/mmq/ds4_ggml_stubs.o: cuda/mmq/ds4_ggml_stubs.cu cuda/mmq/ds4_mmq.h cuda/mmq/ds4_ggml_stubs.h cuda/mmq/common.cuh
$(NVCC) $(NVCCFLAGS) -std=c++17 $(MMQ_INCLUDES) -c -o $@ $<
-cuda/mmq/ds4_mmq.o: cuda/mmq/ds4_mmq.cu cuda/mmq/ds4_mmq.h cuda/mmq/ds4_mmq_d2r.cuh cuda/mmq/mmq.cuh cuda/mmq/common.cuh cuda/mmq/ds4_ggml_stubs.h cuda/mmq/quantize.cuh cuda/mmq/mmid.cuh cuda/mmq/vecdotq.cuh cuda/mmq/mma.cuh
+cuda/mmq/ds4_mmq.o: cuda/mmq/ds4_mmq.cu cuda/mmq/ds4_mmq.h cuda/mmq/ds4_mmq_d2r.cuh cuda/mmq/ds4_mmq_q4_16warp.cuh cuda/mmq/mmq.cuh cuda/mmq/common.cuh cuda/mmq/ds4_ggml_stubs.h cuda/mmq/quantize.cuh cuda/mmq/mmid.cuh cuda/mmq/vecdotq.cuh cuda/mmq/mma.cuh
$(NVCC) $(NVCCFLAGS) -std=c++17 $(MMQ_INCLUDES) -c -o $@ $<
cuda/mmq/ds4_mmq_d2r.o: cuda/mmq/ds4_mmq_d2r.cu cuda/mmq/ds4_mmq_d2r.cuh cuda/mmq/mmq.cuh cuda/mmq/common.cuh cuda/mmq/ds4_ggml_stubs.h cuda/mmq/vecdotq.cuh cuda/mmq/mma.cuh
$(NVCC) $(NVCCFLAGS) -std=c++17 $(MMQ_INCLUDES) -c -o $@ $<
+cuda/mmq/ds4_mmq_q4_16warp.o: cuda/mmq/ds4_mmq_q4_16warp.cu cuda/mmq/ds4_mmq_q4_16warp.cuh cuda/mmq/mmq.cuh cuda/mmq/common.cuh cuda/mmq/ds4_ggml_stubs.h cuda/mmq/vecdotq.cuh cuda/mmq/mma.cuh
+ $(NVCC) $(NVCCFLAGS) -std=c++17 $(MMQ_INCLUDES) -c -o $@ $<
+
cuda/mmq/quantize.o: cuda/mmq/quantize.cu cuda/mmq/quantize.cuh cuda/mmq/common.cuh cuda/mmq/ds4_ggml_stubs.h cuda/mmq/mmq.cuh
$(NVCC) $(NVCCFLAGS) -std=c++17 $(MMQ_INCLUDES) -c -o $@ $<
@@ -436,13 +817,13 @@ cuda/mmq/d2r_stubs.rocm.o: cuda/mmq/test/d2r_stubs.cu cuda/mmq/ds4_mmq_d2r.cuh c
tests/test_mxfp4_rocm.o: tests/test_mxfp4_rocm.c ds4_gpu.h
$(CC) $(filter-out -ffast-math,$(CFLAGS)) $(ROCM_HOST_CFLAGS) -DDS4_ROCM_BUILD -I. -c -o $@ $<
-tests/test_mxfp4_rocm: tests/test_mxfp4_rocm.o ds4_rocm.o
+tests/test_mxfp4_rocm: tests/test_mxfp4_rocm.o ds4_image.o ds4_rocm.o
$(HIPCC) $(ROCM_CFLAGS) -o $@ $^ $(ROCM_LDLIBS)
tests/bench_mxfp4_rocm.o: tests/bench_mxfp4_rocm.c ds4_gpu.h
$(CC) $(filter-out -ffast-math,$(CFLAGS)) $(ROCM_HOST_CFLAGS) -DDS4_ROCM_BUILD -I. -c -o $@ $<
-tests/bench_mxfp4_rocm: tests/bench_mxfp4_rocm.o ds4_rocm.o
+tests/bench_mxfp4_rocm: tests/bench_mxfp4_rocm.o ds4_image.o ds4_rocm.o
$(HIPCC) $(ROCM_CFLAGS) -o $@ $^ $(ROCM_LDLIBS)
test-mxfp4-rocm: tests/test_mxfp4_rocm
@@ -454,7 +835,65 @@ ds4_rocm_compat.o: ds4_rocm_compat.cu ds4_gpu.h ds4_gpu_mgpu.h ds4_gpu_args.h
ds4_rocm_unavailable.o: ds4_rocm_unavailable.cu
$(HIPCC) $(ROCM_CFLAGS) -c -o $@ ds4_rocm_unavailable.cu
-tests/cuda_long_context_smoke: tests/cuda_long_context_smoke.o ds4_cuda.o $(MMQ_OBJS)
+tests/test_rocm_q4_dense_pair.o: tests/test_rocm_q4_dense_pair.cpp ds4_gpu.h
+ $(HIPCC) $(ROCM_CFLAGS) -DDS4_ROCM_BUILD -std=c++17 -fno-fast-math -I. -c -o $@ $<
+
+tests/test_rocm_q4_dense_pair: tests/test_rocm_q4_dense_pair.o ds4_image.o ds4_rocm.o $(ROCM_MMQ_OBJS) ds4_rocm_compat.o ds4_rocm_unavailable.o
+ $(HIPCC) $(ROCM_CFLAGS) -o $@ $^ $(ROCM_LDLIBS)
+
+# Keep the public test target usable on development hosts without ROCm. The
+# binary itself exits 77 when HIP is installed but no device is visible; an
+# explicitly required Strix run converts that condition into a hard failure.
+ROCM_Q4_TEST_ARGS ?= --all
+test-rocm-q4-parity:
+ @rocm_test_hipcc="$(strip $(HIPCC))"; \
+ if [ -z "$$rocm_test_hipcc" ]; then \
+ rocm_test_hipcc="$$(command -v hipcc 2>/dev/null || true)"; \
+ fi; \
+ rocm_test_probe="$${rocm_test_hipcc%% *}"; \
+ if [ -z "$$rocm_test_probe" ] || ! command -v "$$rocm_test_probe" >/dev/null 2>&1; then \
+ if [ -n "$(strip $(DS4_TEST_REQUIRE_ROCM_DEVICE))" ] && [ "$(strip $(DS4_TEST_REQUIRE_ROCM_DEVICE))" != "0" ]; then \
+ echo "ROCm Q4 dense/pair/prefill oracle: FAIL (hipcc not found, device required)"; \
+ exit 1; \
+ fi; \
+ echo "ROCm Q4 dense/pair/prefill oracle: SKIP (hipcc not found)"; exit 0; \
+ fi; \
+ $(MAKE) --no-print-directory tests/test_rocm_q4_dense_pair HIPCC="$$rocm_test_hipcc" || exit $$?; \
+ if [ -n "$(strip $(DS4_TEST_REQUIRE_ROCM_DEVICE))" ] && [ "$(strip $(DS4_TEST_REQUIRE_ROCM_DEVICE))" != "0" ]; then \
+ DS4_TEST_REQUIRE_ROCM_DEVICE="$(strip $(DS4_TEST_REQUIRE_ROCM_DEVICE))" \
+ ./tests/test_rocm_q4_dense_pair $(ROCM_Q4_TEST_ARGS); \
+ else \
+ env -u DS4_TEST_REQUIRE_ROCM_DEVICE \
+ ./tests/test_rocm_q4_dense_pair $(ROCM_Q4_TEST_ARGS); \
+ fi; \
+ rc=$$?; \
+ if [ $$rc -eq 77 ]; then \
+ echo "ROCm Q4 dense/pair/prefill oracle: SKIP (no visible HIP device)"; \
+ exit 0; \
+ fi; \
+ exit $$rc
+
+test-rocm-q4-dense:
+ $(MAKE) --no-print-directory test-rocm-q4-parity ROCM_Q4_TEST_ARGS=--dense
+
+test-rocm-q4-pair:
+ $(MAKE) --no-print-directory test-rocm-q4-parity ROCM_Q4_TEST_ARGS=--pair
+
+test-rocm-q4-prefill:
+ $(MAKE) --no-print-directory test-rocm-q4-parity ROCM_Q4_TEST_ARGS=--prefill
+
+test-strix-rocm-q4-parity:
+ $(MAKE) --no-print-directory -B test-rocm-q4-parity ROCM_ARCH=gfx1151 DS4_TEST_REQUIRE_ROCM_DEVICE=1
+
+test-strix-rocm-q4-prefill:
+ $(MAKE) --no-print-directory -B test-rocm-q4-parity ROCM_ARCH=gfx1151 \
+ DS4_TEST_REQUIRE_ROCM_DEVICE=1 ROCM_Q4_TEST_ARGS=--prefill
+
+test-strix-rocm-q4-prefill-long:
+ $(MAKE) --no-print-directory -B test-rocm-q4-parity ROCM_ARCH=gfx1151 \
+ DS4_TEST_REQUIRE_ROCM_DEVICE=1 ROCM_Q4_TEST_ARGS=--prefill-long
+
+tests/cuda_long_context_smoke: tests/cuda_long_context_smoke.o ds4_image.o ds4_cuda.o $(MMQ_OBJS)
$(NVCC) $(NVCCFLAGS) -o $@ $^ $(CUDA_LDLIBS)
tests/test_layer_pack.o: tests/test_layer_pack.c ds4_layer_pack.h
@@ -488,22 +927,22 @@ ifneq ($(UNAME_S),Darwin)
tests/test_gpu_xdev.o: tests/test_gpu_xdev.c ds4_gpu.h ds4_gpu_mgpu.h
$(CC) $(CFLAGS) -I. -I$(CUDA_HOME)/include -c -o $@ $<
-tests/test_gpu_xdev: tests/test_gpu_xdev.o ds4_cuda.o $(MMQ_OBJS)
+tests/test_gpu_xdev: tests/test_gpu_xdev.o ds4_image.o ds4_cuda.o $(MMQ_OBJS)
$(NVCC) $(NVCCFLAGS) -o $@ $^ $(CUDA_LDLIBS)
tests/test_gpu_model_cache.o: tests/test_gpu_model_cache.c ds4_gpu.h
$(CC) $(CFLAGS) -I. -I$(CUDA_HOME)/include -c -o $@ $<
-tests/test_gpu_model_cache: tests/test_gpu_model_cache.o ds4_cuda.o $(MMQ_OBJS)
+tests/test_gpu_model_cache: tests/test_gpu_model_cache.o ds4_image.o ds4_cuda.o $(MMQ_OBJS)
$(NVCC) $(NVCCFLAGS) -o $@ $^ $(CUDA_LDLIBS)
tests/test_gpu_lookup_cache_strict.o: tests/test_gpu_lookup_cache_strict.c ds4_gpu.h ds4_gpu_mgpu.h
$(CC) $(CFLAGS) -I. -I$(CUDA_HOME)/include -c -o $@ $<
-tests/test_gpu_lookup_cache_strict: tests/test_gpu_lookup_cache_strict.o ds4_cuda.o $(MMQ_OBJS)
+tests/test_gpu_lookup_cache_strict: tests/test_gpu_lookup_cache_strict.o ds4_image.o ds4_cuda.o $(MMQ_OBJS)
$(NVCC) $(NVCCFLAGS) -o $@ $^ $(CUDA_LDLIBS)
-ds4_cuda_test_hooks.o: ds4.c ds4.h ds4_gpu.h ds4_gpu_mgpu.h ds4_layer_pack.h
+ds4_cuda_test_hooks.o: ds4.c ds4.h ds4_gpu.h ds4_gpu_mgpu.h ds4_image.h ds4_layer_pack.h
$(CC) $(CFLAGS) -Wno-unused-function -DDS4_TEST_HOOKS -I$(CUDA_HOME)/include -c -o $@ ds4.c
tests/test_engine_mgpu_refusal.o: tests/test_engine_mgpu_refusal.c ds4.h ds4_gpu_mgpu.h
@@ -515,7 +954,7 @@ tests/test_engine_mgpu_refusal: tests/test_engine_mgpu_refusal.o ds4_gpu_args.o
tests/test_engine_mgpu_runtime.o: tests/test_engine_mgpu_runtime.c ds4.h ds4_gpu_mgpu.h
$(CC) $(CFLAGS) -DDS4_TEST_HOOKS -I. -I$(CUDA_HOME)/include -c -o $@ $<
-tests/test_engine_mgpu_runtime: tests/test_engine_mgpu_runtime.o ds4_cuda_test_hooks.o ds4_gpu_args.o ds4_kvstore.o rax.o ds4_distributed.o ds4_tp.o ds4_ssd.o ds4_cuda.o ds4_layer_pack.o $(MMQ_OBJS)
+tests/test_engine_mgpu_runtime: tests/test_engine_mgpu_runtime.o ds4_cuda_test_hooks.o ds4_gpu_args.o ds4_kvstore.o rax.o ds4_image.o ds4_distributed.o ds4_tp.o ds4_ssd.o ds4_cuda.o ds4_layer_pack.o $(MMQ_OBJS)
$(NVCC) $(NVCCFLAGS) -o $@ $^ $(CUDA_LDLIBS)
tests/test_engine_correctness.o: tests/test_engine_correctness.c ds4.h ds4_gpu_mgpu.h
@@ -536,7 +975,7 @@ test-cuda-session-batch: tests/test_cuda_session_batch
tests/test_cuda_mixed_batch.o: tests/test_cuda_mixed_batch.c ds4.h ds4_gpu_args.h ds4_gpu_mgpu.h
$(CC) $(CFLAGS) -DDS4_TEST_HOOKS -I. -I$(CUDA_HOME)/include -c -o $@ $<
-tests/test_cuda_mixed_batch: tests/test_cuda_mixed_batch.o ds4_cuda_test_hooks.o ds4_gpu_args.o ds4_kvstore.o rax.o ds4_distributed.o ds4_tp.o ds4_ssd.o ds4_cuda.o ds4_layer_pack.o $(MMQ_OBJS)
+tests/test_cuda_mixed_batch: tests/test_cuda_mixed_batch.o ds4_cuda_test_hooks.o ds4_gpu_args.o ds4_kvstore.o rax.o ds4_image.o ds4_distributed.o ds4_tp.o ds4_ssd.o ds4_cuda.o ds4_layer_pack.o $(MMQ_OBJS)
$(NVCC) $(NVCCFLAGS) -o $@ $^ $(CUDA_LDLIBS)
test-cuda-mixed-batch: tests/test_cuda_mixed_batch
@@ -565,18 +1004,27 @@ tests/test_prompt_prefix: tests/test_prompt_prefix.o ds4_prompt_prefix.o
test: ds4_test ds4_agent_test ds4-eval q4k-dot-test mxfp4-dot-test \
tests/test_layer_pack tests/test_engine_mgpu_placement tests/test_gpu_args \
+ tests/test_quantizer_indexer_q4 gguf-tools/deepseek4-quantize \
tests/test_deepseek4_vision_image tests/test_prompt_prefix $(SAMPLING_TEST) ds4 ds4-server ds4-bench ds4-agent
./ds4-eval --self-test-extractors
./ds4_agent_test
- ./ds4_test
+ # Avoid adding the Q4 resident sidecar's 2.69 GiB to this broad suite.
+ # This does not enable SSD streaming; use `make test-ssd` for oversized models.
+ DS4_METAL_DISABLE_Q4_ATTN_Q_B_F16_CACHE=1 ./ds4_test
./tests/test_layer_pack
./tests/test_engine_mgpu_placement
./tests/test_gpu_args
./tests/test_gpu_args_cli.sh
./tests/test_prompt_prefix
./tests/test_sampling
+ ./tests/test_quantizer_indexer_q4 ./gguf-tools/deepseek4-quantize
./tests/test_deepseek4_vision_image
+test-ssd:
+ DS4_TEST_SSD_STREAMING=1 \
+ DS4_TEST_SSD_STREAMING_COLD=1 \
+ $(MAKE) test
+
dspark-acceptance: ds4
DS4_DSPARK_MODEL="$(DS4_DSPARK_MODEL)" \
DS4_DSPARK_SUPPORT="$(DS4_DSPARK_SUPPORT)" \
@@ -611,4 +1059,5 @@ mxfp4-dot-test: tests/test_mxfp4_dot.c
./tests/test_mxfp4_dot
clean:
- rm -f ds4 ds4-server ds4-bench ds4-eval ds4-agent ds4_cpu ds4_native ds4_server_test ds4_test ds4_agent_test gguf-tools/quality-testing/score_official gguf-tools/quality-testing/score_official.o speed-bench/metal_decode_schedule_bench speed-bench/metal_prefill_variant_bench speed-bench/*.o tests/test_q4k_dot tests/test_mxfp4_dot tests/test_mxfp4_metal tests/test_mxfp4_rocm tests/test_mxfp4_cuda tests/test_metal_session_batch tests/test_glm53_kda tests/test_glm53_kda_rocm tests/test_glm53_vision_engine tests/test_glm53_vision_prompt tests/test_deepseek4_vision_image tests/test_prompt_prefix tests/test_gpu_xdev tests/test_gpu_model_cache tests/test_gpu_lookup_cache_strict tests/test_engine_mgpu_refusal tests/test_engine_mgpu_runtime tests/test_engine_correctness tests/test_sampling tests/test_cuda_session_batch tests/test_cuda_mixed_batch tests/*.o *.o tests/cuda_long_context_smoke tests/cuda_long_context_smoke.o
+ rm -f speed-bench/metal_iq2_moe_top8_pair_bench
+ rm -f ds4 ds4-server ds4-bench ds4-eval ds4-agent ds4_cpu ds4_native ds4_server_test ds4_test ds4_agent_test gguf-tools/quality-testing/score_official gguf-tools/quality-testing/score_official.o speed-bench/metal_decode_schedule_bench speed-bench/metal_prefill_variant_bench speed-bench/metal_q4_dense_pair_bench speed-bench/metal_q4_prefill_pair_bench speed-bench/metal_q4_mm_tail_cull_bench speed-bench/metal_q4_attn_out_a_direct_bench speed-bench/metal_iq2_moe_tail_cull_bench speed-bench/gpu_iq2_moe_prefill_bench_rocm speed-bench/gpu_iq2_moe_prefill_bench_cuda speed-bench/rocm_q4_prefill_bench speed-bench/cuda_q4_prefill_bench speed-bench/*.o tests/test_q4k_dot tests/test_mxfp4_dot tests/test_quantizer_indexer_q4 tests/test_mxfp4_metal tests/test_mxfp4_rocm tests/bench_mxfp4_rocm tests/test_mxfp4_cuda tests/test_rocm_q4_dense_pair tests/test_metal_session_batch tests/test_metal_q4_streams tests/test_metal_q4_prefill_pair tests/test_metal_indexer_q4 tests/test_metal_q4_attn_exactn tests/test_metal_q4_attn_out_a_direct tests/test_metal_q4_qb_f16_cache tests/test_metal_exactn_oracle tests/test_metal_dspark_capture tests/test_metal_argmax_top1 tests/test_metal_iq2_midonly tests/test_metal_iq2_ssd_grouped_mm tests/test_metal_iq2_live_index tests/test_glm53_kda tests/test_glm53_kda_rocm tests/test_glm53_vision_engine tests/test_glm53_vision_prompt tests/test_deepseek4_vision_image tests/test_prompt_prefix tests/test_gpu_xdev tests/test_gpu_model_cache tests/test_gpu_lookup_cache_strict tests/test_engine_mgpu_refusal tests/test_engine_mgpu_runtime tests/test_engine_correctness tests/test_sampling tests/test_cuda_session_batch tests/test_cuda_mixed_batch tests/*.o *.o cuda/mmq/*.o cuda/mmq/test/*.o tests/cuda_long_context_smoke tests/cuda_long_context_smoke.o
diff --git a/QA_BEFORE_RELEASES.md b/QA_BEFORE_RELEASES.md
index 746db73e5c..c25d39b3f2 100644
--- a/QA_BEFORE_RELEASES.md
+++ b/QA_BEFORE_RELEASES.md
@@ -232,8 +232,8 @@ Use the normal Flash GGUF that 128 GB users run.
### DSpark / DeepSpec Runtime
DSpark is opt-in, but it mutates the verifier, target-hidden capture, support
-model loading, and scheduler paths. Run these whenever DSpark support,
-speculative verification, confidence/scheduler policy, target hidden capture,
+model loading, and proposal paths. Run these whenever DSpark support,
+speculative verification, confidence policy, target hidden capture,
tiny routed-MoE verifier kernels, or shared `--mtp-model` support-model code changes:
Use the 0731 DSpark support GGUF only with a Flash 0731 target. A support model
@@ -267,6 +267,247 @@ than a failure. `--dspark-strict` remains the byte-identical target-only mode.
`DS4_DSPARK_FIXTURE_CONFIDENCE=0 DS4_DSPARK_FIXTURE_TOKENS=8 DS4_DSPARK_FIXTURE_REQUIRE_PARTIAL=1 DS4_DSPARK_MODEL=/Users/antirez/ds4/gguf/DeepSeek-V4-Flash-IQ2XXS-w2Q2K-AProjQ8-SExpQ8-OutQ8-chat-v2-imatrix-0731.gguf DS4_DSPARK_SUPPORT=/Users/antirez/ds4/gguf/DeepSeek-V4-Flash-DSpark-support-0731.gguf make dspark-acceptance`.
- DSpark verifier invariant smoke:
`DS4_TEST_MODEL=/Users/antirez/ds4/gguf/DeepSeek-V4-Flash-IQ2XXS-w2Q2K-AProjQ8-SExpQ8-OutQ8-chat-v2-imatrix-0731.gguf DS4_DSPARK_SUPPORT=/Users/antirez/ds4/gguf/DeepSeek-V4-Flash-DSpark-support-0731.gguf make dspark-verify-depth`.
+- For Metal DSpark verifier/proposer/replay changes, run this same-machine A/B
+ matrix with `DS4_DSPARK_STATS=1`, greedy decoding, the same prompt and token
+ limit, and no other environment changes:
+
+ | Target expert cache | Expected DSpark depth | Legacy control | Candidate |
+ | ---: | ---: | --- | --- |
+ | 16 | 2 | `DS4_METAL_DSPARK_PROPOSER_BLOCK_MAX=0 DS4_METAL_DSPARK_ACCEPTANCE_ONLY_VERIFY=0 DS4_METAL_DSPARK_HEADLESS_REPLAY=0` | Leave proposer/headless unset; keep acceptance-only `=0` |
+ | 32 | 5 | `DS4_DSPARK_SSD_VERIFY_BLOCK_MAX=5 DS4_METAL_DSPARK_ACCEPTANCE_ONLY_VERIFY=0 DS4_METAL_DSPARK_HEADLESS_REPLAY=0` | Keep the verifier cap, set acceptance-only `=1`, and leave proposer/headless unset |
+
+ Use `--ssd-streaming-cache-experts 16` or `32` to match the row. The 0731
+ top-6 verifier needs 30 effective slots for five draft rows; 32 leaves a small
+ margin. Require byte-identical stdout between control and candidate and
+ `errors=0`, `verifier_unavailable=0`, `proposed>0`, and
+ `accepted_draft>0`. Record generation t/s, acceptance, `propose`, `verify`,
+ `replay`, `prop_capped`, `prop_scheduled_rows`, `metal_accept_only`,
+ `metal_verify_rows_saved`, and `metal_replay_headless`. In the candidate,
+ eligible `N >= 3` verification cycles should save one target row; aligned
+ ratio-4 boundaries intentionally remain on the legacy path. The
+ depth-2 run exercises proposer capping and headless replay while retaining
+ the legacy verifier; the depth-5 run should retain the checkpoint's native
+ five proposal rows and exercise acceptance-only verification.
+ On low-memory Metal, repeat the depth-5 candidate once with
+ `DS4_METAL_DSPARK_PIN_MAIN_PROJ=1`. Require a startup log confirming the
+ locked byte count, identical stdout and acceptance, and compare
+ `prop_setup`, total `propose`, page faults, and generation t/s. A lock
+ failure or a slower median keeps this optimization opt-in.
+- For the experimental Metal SSD exact-2 verifier, repeat the depth-2 row
+ above with `DS4_METAL_DSPARK_EXACT2=0` as the control and `=1` as the only
+ candidate change. Set `DS4_DSPARK_FIXTURE_REQUIRE_EXACT2=1` only on the
+ candidate. Require byte-identical stdout against both control and
+ target-only output, `exact2_attempt>0`, `exact2_full>0`,
+ `exact2_fallback=0`, and `errors=0`. Record generation t/s, `verify`, and
+ `replay`; then repeat for at least 100 generated tokens to catch cumulative
+ state drift. Do not infer that the generic five-row batch state is directly
+ committable from this two-row result.
+- For Metal exact-union or the AProjQ4/HC decode fusions, first run the
+ model-backed oracle with the target AProjQ4 GGUF:
+ `DS4_TEST_MODEL=/path/to/deepseek-v4-flash-aprojq4.gguf make test-metal-exactn-oracle`.
+ Require its N=2..5 cases to be byte-identical to sequential decode for
+ serialized KV/compressor state, logits, and the four-token continuation.
+ The matrix must include full accepts for N=2,3,4,5, all N=5 partial prefixes
+ 1..4, and EOS in the first and a middle row. This is a correctness gate, not
+ evidence of a speedup.
+- The Q8 Q-A/KV compound rows below require a separate AProjQ8 target whose
+ metadata includes both ratio-4 and ratio-128 compressor layers. An AProjQ4
+ oracle cannot exercise that compound and is a failed coverage gate even if
+ greedy output remains correct.
+- Then run isolated, same-machine greedy A/B pairs with identical prompt,
+ context, cache, token limit, and `DS4_DSPARK_STATS=1`. Change only the gate
+ named by the row:
+
+ | Metal fusion | Reference control | Candidate |
+ | --- | --- | --- |
+ | HC RMSNorm + F16 mixer on M1-M4 | `DS4_METAL_DISABLE_PRE_M5_HC_NORM_MIX_FUSE=1` | Leave the disable switch unset |
+ | HC RMSNorm + F16 mixer on another Apple generation | Leave both HC norm/mix switches unset | `DS4_METAL_ENABLE_HC_NORM_MIX_FUSE=1` |
+ | HC producer + split/Sinkhorn/destination RMSNorm on M1-M5 | `DS4_METAL_DISABLE_HC_PRODUCER_PRE_NORM_FUSE=1` | Leave the disable switch unset |
+ | Q4 Q-A/KV + compressor store in exact-union | `DS4_METAL_DSPARK_EXACTN_UNION=1` with the Q4 enable switch unset | Keep exact-union `=1`; set `DS4_METAL_ENABLE_Q4_QKV_COMPRESSOR_FUSE=1` |
+ | Q4 Q-A/KV + compressor store in ordinary `FULL` decode | Leave `DS4_METAL_ENABLE_Q4_QKV_COMPRESSOR_FUSE` unset | Set `DS4_METAL_ENABLE_Q4_QKV_COMPRESSOR_FUSE=1` |
+ | Q8 Q-A/KV + compressor store in SSD `FULL` (AProjQ8) | Leave the Q8 enable/require switches unset | Set `DS4_METAL_ENABLE_Q8_QKV_COMPRESSOR_FUSE=1 DS4_METAL_REQUIRE_Q8_QKV_COMPRESSOR_FUSE=1` |
+ | Q8 Q-A/KV + compressor store in SSD exact-union (AProjQ8) | `DS4_METAL_DSPARK_EXACTN_UNION=1` with the Q8 enable/require switches unset | Keep exact-union `=1`; set `DS4_METAL_ENABLE_Q8_QKV_COMPRESSOR_FUSE=1 DS4_METAL_REQUIRE_Q8_QKV_COMPRESSOR_FUSE=1` |
+ | Q4 attention-output tiny batch in the generic verifier | Set `DS4_METAL_DSPARK_EXACTN_UNION=0 DS4_METAL_DSPARK_EXACTN=0 DS4_METAL_DSPARK_EXACT2=0`; leave tiny enable/require unset | Keep all three exact gates `=0`; set `DS4_METAL_REQUIRE_Q4_ATTN_OUT_TINY_BATCH=1` and require at least one proposed block of depth 3–5 (the acceptance-only suffix evaluates one fewer row) |
+ | F16 attention+indexer quad compressor store in `FULL` decode | `DS4_METAL_DISABLE_COMPRESSOR_QUAD_STORE=1` | Leave the disable switch unset |
+ | F16 attention+indexer quad compressor store in exact-union | `DS4_METAL_DSPARK_EXACTN_UNION=1 DS4_METAL_DISABLE_COMPRESSOR_QUAD_STORE=1` | Keep exact-union `=1`; leave the quad disable switch unset |
+ | Exact ratio-4 one-row compressor pool on M1-M5 | `DS4_METAL_DISABLE_COMPRESSOR_EXACT_POOL_RATIO4=1` | Leave the disable switch unset |
+ | Q4 attention-output B + HC expansion | `DS4_METAL_DISABLE_Q4_ATTN_OUT_HC_FUSE=1` | Leave the disable switch unset |
+ | FlashAttention pad/block PSO memo | `DS4_METAL_DISABLE_PRE_M5_FLASH_ATTN_PAD_BLK_MEMO=1` | Leave the disable switch unset |
+ | FlashAttention batched/vector PSO memo | `DS4_METAL_DISABLE_PRE_M5_FLASH_ATTN_BATCHED_MEMO=1` | Leave the disable switch unset |
+ | Exact-union asynchronous routed tails | `DS4_METAL_DSPARK_EXACTN_UNION=1` with `DS4_METAL_DSPARK_EXACT_ROWS_ASYNC_TAILS` unset | Keep exact-union `=1`; set `DS4_METAL_DSPARK_EXACT_ROWS_ASYNC_TAILS=1` |
+
+ The Q4 Q-A/KV compound is opt-in in both exact-union and ordinary `FULL`
+ decode; it is enabled only when the explicit enable variable is present.
+ Require byte-identical stdout and `errors=0`; for exact-union also
+ require `exactn_union_attempt>0` and `exactn_union_error_fallback=0`.
+ Partial-accept fallback is expected when the draft diverges. Record
+ `exactn_union_full`, `exactn_union_partial_fallback`, `propose`, `verify`,
+ `replay`, stage timings, page faults, and generation t/s. A candidate that
+ is correct but slower remains disabled or opt-in according to its gate.
+ For asynchronous tails, also repeat the model-backed oracle with the switch
+ set and run enough exact-union cycles to cross cache eviction and raw-ring
+ wrap boundaries. The candidate removes a CPU wait but retains private expert
+ buffers until command-buffer completion; serialized state and process memory
+ after synchronization must match the synchronous control.
+ Before the model-backed runs, build `ds4_test` and run
+ `./ds4_test --metal-kernels`. This covers the isolated compound HC, F16 quad
+ compressor-store, exact ratio-4 pool, and tie-heavy Metal routing kernels.
+ For the exact one-row pool candidate, repeat once with
+ `DS4_METAL_REQUIRE_COMPRESSOR_EXACT_POOL_RATIO4=1`; the run must exercise the
+ specialization instead of silently falling back. Also exercise the global
+ kill switches plus the matching pre-M5 or M5 HC/pool rollback on the target
+ machine. Treat the FlashAttention memo rows as host-dispatch A/B tests: the
+ selected specialization and output must remain identical, and any timing
+ comparison must use repeated warm runs.
+- For the default M1 IQ2 address-table mid-only path, first run
+ `make test-metal-iq2-midonly`. It must cover 12,288 full-shape top-6 mid
+ words in both unmasked and complementary masked address-table modes with
+ both mid mismatch counters at zero, no canonical unwritten rows, zero
+ candidate gate/up writes, and zero guard mismatches. Then use the same greedy
+ IQ2_XXS/Q2_K SSD-streaming model, prompt, cache state, and token count for
+ three decode runs: leave all switches unset for the automatic candidate,
+ set `DS4_METAL_REQUIRE_M1_IQ2_MID_ONLY=1` for fail-closed coverage, and set
+ `DS4_METAL_DISABLE_M1_IQ2_MID_ONLY=1` for the canonical control and
+ kill-switch fallback.
+ Enable the routed-MoE stage profiler on one candidate layer and require path
+ `iq2_stream_addr_mid_only_4096x2048` or
+ `iq2_stream_addr_mask_mid_only_4096x2048`; absence of both is failed model
+ coverage. Require byte-identical greedy output and top-logprobs, and report
+ prefill separately from decode: this one-token routed producer is not a
+ prefill optimization. Compare repeated hot-cache medians, then repeat a
+ cold-cache sanity run to exclude a change in SSD cache behavior.
+- For the removed Metal 512-column streaming top-k path, there is no runtime
+ candidate gate. Compare the current binary with a build immediately before
+ its removal only if historical timing is needed. First require
+ `./ds4_test --metal-kernels` to pass, including tie-heavy routing cases, then
+ require identical selected expert ids and greedy output. Correct deterministic
+ ordering takes precedence over a timing difference.
+- For the default CPU unrolled argmax, run `tests/test_sampling`, then compare
+ an otherwise identical greedy workload with
+ `DS4_CPU_DISABLE_UNROLLED_ARGMAX=1` (scalar control) and with the variable
+ unset (candidate). Require identical tokens for ordinary, excluded-id,
+ cross-lane-tie, and vocabulary-tail cases; record median generation t/s over
+ repeated runs without claiming a speedup from the implementation alone.
+- For the experimental resident-CUDA exact-2 verifier, use three controlled
+ runs with verifier cap two on the same single-GPU host: native proposer plus
+ legacy verifier
+ (`DS4_CUDA_DSPARK_EXACT2=0 DS4_CUDA_DSPARK_PROPOSER_BLOCK_MAX=0 DS4_DSPARK_SSD_VERIFY_BLOCK_MAX=2`),
+ two-row proposer plus legacy verifier
+ (`DS4_CUDA_DSPARK_EXACT2=0 DS4_CUDA_DSPARK_PROPOSER_BLOCK_MAX=2 DS4_DSPARK_SSD_VERIFY_BLOCK_MAX=2`),
+ and two-row proposer plus exact-2
+ (`DS4_CUDA_DSPARK_EXACT2=1 DS4_CUDA_DSPARK_PROPOSER_BLOCK_MAX=2 DS4_DSPARK_SSD_VERIFY_BLOCK_MAX=2`).
+ This separates the non-causal proposer-width change from the verifier and
+ replay change. Then compare uncapped legacy DSpark against exact-2 as an
+ end-to-end policy test. Keep SSD streaming and TP disabled. Require
+ byte-identical stdout, `errors=0`, and `verifier_unavailable=0` from every
+ run; set `DS4_DSPARK_FIXTURE_REQUIRE_EXACT2=1` on the exact-2 run so the
+ fixture enforces `exact2_attempt>0` and `exact2_fallback=0`.
+ Record `prop_scheduled_rows/cycles`, `propose`, `verify`, `replay`, `net_saved`,
+ `miss_first`, `no_draft`, `avg_accept`, and generation t/s from every run.
+- For resident CUDA exact-N, keep exact-2 disabled and compare
+ `DS4_CUDA_DSPARK_EXACTN=0` against `=1` with the native five-row proposer
+ and `DS4_DSPARK_SSD_VERIFY_BLOCK_MAX=5`. Repeat N=2,3,4,5 with explicit
+ proposer/verifier caps, then exercise the kill switch with both
+ `DS4_CUDA_DSPARK_EXACTN=1` and
+ `DS4_CUDA_DISABLE_DSPARK_EXACTN=1`. Require byte-identical greedy stdout,
+ `errors=0`, `verifier_unavailable=0`, `cuda_exactn_attempt>0`, and at least
+ one `cuda_exactn_full`; partial cases must increment the partial and
+ aggregate fallback counters, never the error counter, and continue
+ identically through legacy replay. Include
+ EOS as the first and a middle draft, a raw-ring wrap boundary, a context
+ capacity cut, and prefill workspaces below five rows. Record
+ `cuda_exactn_rows`, its full/partial/error counters, `snapshot`, `verify`,
+ `replay`, acceptance, and generation t/s. Run with CUDA decode graphs both
+ enabled and disabled. Do not promote the gate without a CUDA device build
+ and serialized KV/compressor-state oracle; host syntax tests do not execute
+ this path. On candidate fixture runs set
+ `DS4_DSPARK_FIXTURE_REQUIRE_CUDA_EXACTN=1`; it requires aggregate
+ `cuda_exactn_attempt>0` and `cuda_exactn_error_fallback=0`. It reports but
+ does not reject aggregate `cuda_exactn_fallback`, because valid partial
+ matches increment both the partial and aggregate fallback counters before
+ legacy replay.
+- For CUDA DSpark non-causal proposer attention, compare the reference with
+ `DS4_CUDA_ENABLE_DSPARK_NONCAUSAL_ONLINE=0` against the candidate with `=1`.
+ Repeat at proposal depths two and five, across every raw-ring start index,
+ and once with both the enable variable and
+ `DS4_CUDA_DISABLE_DSPARK_NONCAUSAL_ONLINE=1` to prove the kill switch restores
+ the reference dispatch. On the short diagnostic runs also set
+ `DS4_DSPARK_VERIFY_NONCAUSAL=1`; record all three reported `max_abs` and
+ `max_rel` comparisons and reject non-finite values or a material error
+ regression. Then run the acceptance fixture without the diagnostic host
+ readbacks and require byte-identical target stdout, `errors=0`, and
+ `verifier_unavailable=0`. Record proposal time, acceptance, generation t/s,
+ and the startup dispatch log. Draft logits or acceptance may differ slightly
+ because online softmax changes the floating-point reduction order; that is
+ not permission for the verified target continuation to differ.
+- For CUDA HC and tiny routed-MoE kernel changes, keep
+ `DS4_CUDA_DSPARK_EXACT2` unset and repeat the resident acceptance fixture
+ with these explicit A/B pairs: HC control
+ `DS4_CUDA_DISABLE_HC_SPLIT_NORM_FUSED=1` versus candidate with that variable
+ absent; routed-MoE control `DS4_CUDA_DSPARK_TINY_ALIGNED_VEC=0` versus
+ candidate `=1`. Require byte-identical stdout, `errors=0`, and
+ `verifier_unavailable=0`; record `prop_chain`, `verify_layer`, total
+ proposal/verify time, acceptance, and generation t/s. Also run
+ `--decode-consistency 64` and the logprob-vector regression before enabling
+ a numerically different kernel by default.
+- For the CUDA AProjQ4 ports, run an isolated A/B for each dispatch:
+ Q-A/KV pair control `DS4_CUDA_DISABLE_Q4_DENSE_PAIR=1` versus candidate with
+ that variable absent; HC norm/mix control
+ `DS4_CUDA_DISABLE_HC_NORM_MIX_FUSE=1` versus candidate
+ `DS4_CUDA_ENABLE_HC_NORM_MIX_FUSE=1 DS4_CUDA_NO_F16_CUBLAS_ONE=1`; and Q4
+ attention-output/HC control `DS4_CUDA_DISABLE_Q4_ATTN_OUT_HC_FUSE=1` versus
+ the graph-compatible canonical candidate with that variable absent. Run a separate
+ non-captured diagnostic with `DS4_CUDA_Q4_ATTN_OUT_HC_ORACLE=1`; require
+ the summary to be present with `calls>0`, `skips=0`, and
+ `epilogue_mismatches=0`, while `q8k_mismatches` records the expected
+ numerical distance from the optional one-dispatch Q8_K experiment. A
+ zero-call summary is a failed coverage gate. Only
+ test `DS4_CUDA_Q4_ATTN_OUT_HC_Q8K_EXPERIMENT=1` as a promotion candidate if
+ its oracle mismatches are also zero. Repeat the pair and attention-output
+ cases with `DS4_CUDA_MMQ=0` to exercise the canonical Q8_K fallback
+ separately from the default MMVQ/Q8_1 path. Require byte-identical stdout
+ and full-logit/tensor equivalence before promoting an opt-in gate. Run with
+ decode graphs both enabled and disabled, and record target, proposer,
+ verifier, replay, acceptance, and generation t/s. A CUDA build and hardware
+ run are mandatory; a host-only build does not compile the device kernels.
+- When DSpark, support-model mapping, or SSD streaming changes, repeat both
+ the acceptance fixture and verifier invariant on every advertised graph
+ backend. Apply the backend and SSD options to the target-only baseline as
+ well as the DSpark run:
+
+ ```sh
+ DS4_DSPARK_MODEL=/path/to/flash-0731.gguf \
+ DS4_DSPARK_SUPPORT=/path/to/DeepSeek-V4-Flash-DSpark-support-0731.gguf \
+ DS4_DSPARK_FIXTURE_BACKEND=cuda \
+ DS4_DSPARK_FIXTURE_SSD_STREAMING=1 \
+ DS4_DSPARK_FIXTURE_SSD_STREAMING_CACHE_EXPERTS=32 \
+ DS4_DSPARK_FIXTURE_CONFIDENCE=0 \
+ make dspark-acceptance
+
+ DS4_TEST_MODEL=/path/to/flash-0731.gguf \
+ DS4_DSPARK_SUPPORT=/path/to/DeepSeek-V4-Flash-DSpark-support-0731.gguf \
+ DS4_TEST_SSD_STREAMING=1 \
+ DS4_TEST_SSD_STREAMING_CACHE_EXPERTS=32 \
+ make dspark-verify-depth
+ ```
+
+ On Strix Halo use the same variables with
+ `DS4_DSPARK_FIXTURE_BACKEND=rocm make rocm-dspark-acceptance` and
+ `make rocm-dspark-verify-depth`. Do not use the generic targets after a ROCm
+ build: on non-Apple hosts their default object set is CUDA. For the 0731
+ Flash layout, ROCm needs at least 30 expert slots; use 32 in release tests.
+- The fixture must report aggregate `proposed>0`, `accepted_draft>0`,
+ `verifier_unavailable=0`, and `errors=0`; stdout must remain byte-identical
+ to the target-only SSD baseline. The verifier smoke must report
+ `max_chunk>1`, `nspec>64`, and `worst_argmax_gap<=2`.
+- Preserve baseline and DSpark `generation` t/s from the same fixture run,
+ with the same host, model, cache, runtime settings, thermal state, and
+ background load. A DSpark path that is materially slower than the target-only
+ SSD path without a documented correctness tradeoff is a release blocker.
+- On ROCm, also run one `DS4_DSPARK_PROBE=1`
+ generation and require the non-causal attention and stage-chain probes to
+ pass. This covers the HIP draft-attention kernel before the end-to-end
+ verifier gate.
- If shared support-model or verifier structures changed, also run legacy MTP:
`make mtp-verify-depth` with `DS4_TEST_MTP` set to a one-stage MTP support
GGUF, or confirm the target skips only because the optional file is missing.
@@ -274,7 +515,7 @@ than a failure. `--dspark-strict` remains the byte-identical target-only mode.
`replay_fallbacks`, `errors=0`, `verify_layer`, `net_saved`, and
`output_match` for both 32-token and 64-token runs. At least one direct commit
must occur. A faster run with lower proposal quality is a regression unless
- it was an intentional scheduler change.
+ it was an intentional confidence-policy change.
- If verifier MoE kernels changed, run one diagnostic `c_add` profile with
`DS4_DSPARK_VERIFY_SELECTED_PROFILE=1` or the Metal MoE stage profiler and
record the selected-expert footprint or stage timing in the DSpark log.
@@ -737,6 +978,122 @@ Do not use high-performance Hugging Face Xet mode while vLLM is resident.
receiving explicit permission to use `192.168.60.250` for this QA pass.
- Run:
`make cuda-regression`.
+- On a single GB10 (`sm_121`), validate the imported Q2 decode fast paths with
+ the AProjQ8/OutQ8 Flash GGUF. Compare the default against a rollback process
+ that sets all of:
+ `DS4_CUDA_NO_DIRECT_Q2_PREFILL=1`,
+ `DS4_CUDA_NO_F16_PAIR_COMPRESSOR_STORE=1`,
+ `DS4_CUDA_NO_F16_PAIR_COMPRESSOR_TRANSPOSE=1`,
+ `DS4_CUDA_NO_F16_PAIR_COMPRESSOR_TRANSPOSE_PREFETCH8=1`,
+ `DS4_CUDA_NO_Q8_FUSED_ALIGNED=1`,
+ `DS4_CUDA_NO_Q8_ALIGNED_PERSISTENT=1`,
+ `DS4_CUDA_NO_Q8_ALIGNED_DENSE_SCRATCH=1`, and
+ `DS4_CUDA_NO_HC_SPLIT_NORM_SPLIT4096=1`. Use separate processes, require
+ byte-identical greedy stdout and per-token logprobs, then run the same pair
+ under Compute Sanitizer. Record prefill, decode, and steady decode rather
+ than copying the upstream PR numbers into a release claim.
+- Repeat the GB10 comparison with AProjQ4/OutQ8. First run
+ `make test-mmq-parity-cuda CUDA_ARCH=sm_121`; its Q4 cases must report zero
+ bit mismatches for persistent scratch, grouped attention-A, and the
+ opt-in K1024 persistent kernel. For the model A/B, use
+ `DS4_CUDA_NO_Q4_GB10_FAST=1` in the control and leave it unset in the
+ candidate. Run a separate generic-verifier candidate with
+ `DS4_CUDA_DISABLE_DSPARK_EXACTN=1`,
+ `DS4_CUDA_ENABLE_Q4_GROUPED_ATTN_A_BATCH=1`,
+ `DS4_CUDA_REQUIRE_Q4_GROUPED_ATTN_A_BATCH=1`, and
+ `DS4_CUDA_Q4_GROUPED_ATTN_A_ORACLE=1`; require `batch_candidates>0`,
+ `batch_calls>0`, `batch_mismatches=0`, and `batch_skips=0`, plus
+ byte-identical stdout. Build the resident prefill harness and run
+ `./speed-bench/cuda_q4_prefill_bench --path mmq --case outa --tokens
+ 127,128,129,257,512,2048,4096 --samples 16 --warmup 4`; require bitwise
+ equality between `pack8_mmq_unpack` and `grouped_8_grids`, finite/canary/CPU
+ oracle success, and record the paired median. Run
+ `make test-mmq-q4-grouped-q81-cuda CUDA_ARCH=sm_121`, then isolate the new
+ Q8_1 front-end with
+ `--grouped-q81-kernel --tokens 512,1024,2048,4096,6144,8192`; require
+ byte-identical direct parity, bitwise final output, and a repeatable paired
+ median win between `grouped_generic_q81` and
+ `grouped_k4096_g8x2_q81`. Then compare full-model
+ prefills with the default environment against the dominant
+ `DS4_CUDA_NO_Q4_GROUPED_ATTN_A_PREFILL=1` rollback, and separately against
+ the narrow `DS4_CUDA_NO_Q4_GROUPED_ATTN_A_Q81=1` rollback. Keep the
+ single-grid and 16-warp experiments unset in this promotion comparison.
+ Benchmark the K1024
+ persistent kernel as a
+ separate fail-closed arm with both
+ `DS4_CUDA_ENABLE_Q4_K1024_PERSISTENT=1` and
+ `DS4_CUDA_REQUIRE_Q4_K1024_PERSISTENT=1`; its rollback is
+ `DS4_CUDA_NO_Q4_K1024_PERSISTENT=1`. Then run a non-captured oracle process
+ with `DS4_CUDA_DECODE_GRAPHS=0`,
+ `DS4_CUDA_Q4_K1024_PERSISTENT_ORACLE=1`, and
+ `DS4_CUDA_Q4_K1024_PERSISTENT_STATS=1`; require `candidates>0`, `uses>0`,
+ `oracle_calls>0`, `oracle_mismatches=0`, and `oracle_skips=0`. The parity
+ test must also show a nonzero REQUIRE failure with the local kill set,
+ proving admission fails before enqueue, and a canonical reference forced by
+ that same kill. The counters are host dispatches and intentionally exclude
+ CUDA graph replays. The persistent OutQ8
+ vocabulary, compressor, HC split, direct routed-MoE paths, Q4 scratch,
+ grouped attention-A, and canonical B+HC epilogue remain relevant, while
+ the Q8-only attention-projection consumers are intentionally ineligible.
+- Validate the experimental HC-to-consumer Q8_1 producer fold in separate
+ processes. Use `DS4_CUDA_NO_Q8_FOLD=1` for the control and
+ `DS4_CUDA_ENABLE_Q8_FOLD=1` for the candidate, first with the normal graph
+ setting and then with `DS4_CUDA_DECODE_GRAPHS=0`. For the non-captured arm,
+ also set `DS4_CUDA_Q8_FOLD_ORACLE=1` and require `hits>0`, `byte_calls>0`,
+ `output_calls>0`, `byte_mismatches=0`, `output_mismatches=0`, and `skips=0`.
+ The reached consumer must be reported as aligned Q8 or IQ2 MoE rather than
+ inferred from producer counters alone. Require byte-identical greedy stdout
+ and per-token logprobs, then repeat the control/candidate pair under Compute
+ Sanitizer. Keep the oracle off for the graph-on timing arm: capture is an
+ intentional fail-closed miss and is checked for safety, not fold coverage.
+ Run these arms through the ordinary serialized inference dispatcher; the
+ opt-in fold does not support concurrent host-thread submission to one CUDA
+ stream.
+- If the umbrella AProjQ4 A/B changes logits, do not attribute that change to
+ "the Q4 fast path" as a unit. Run the fail-closed component matrix from a
+ clean `cuda-spark` build. The output directory is intentionally explicit so
+ the six independent-process arms, two oracle arms, raw logs, and diffs are
+ retained:
+
+ ```sh
+ make clean && make cuda-spark
+ make gguf-tools/quality-testing/score_official CUDA_ARCH=sm_121
+
+ DS4_CUDA_Q4_MATRIX_SSD_STREAMING=1 \
+ DS4_CUDA_Q4_MATRIX_SSD_CACHE=16GB \
+ DS4_CUDA_Q4_MATRIX_DECODE_GRAPHS=1 \
+ tests/cuda_q4_gb10_fast_matrix.sh \
+ /path/to/DeepSeek-V4-Flash-AProjQ4-OutQ8.gguf \
+ gguf-tools/quality-testing/data/flash/manifest.tsv \
+ /tmp/q4-gb10-graphs-on
+
+ DS4_CUDA_Q4_MATRIX_SSD_STREAMING=1 \
+ DS4_CUDA_Q4_MATRIX_SSD_CACHE=16GB \
+ DS4_CUDA_Q4_MATRIX_DECODE_GRAPHS=0 \
+ tests/cuda_q4_gb10_fast_matrix.sh \
+ /path/to/DeepSeek-V4-Flash-AProjQ4-OutQ8.gguf \
+ gguf-tools/quality-testing/data/flash/manifest.tsv \
+ /tmp/q4-gb10-graphs-off
+ ```
+
+ The matrix first proves that the three local rollback switches reproduce
+ `DS4_CUDA_NO_Q4_GB10_FAST=1`; failure of `local_control` means the matrix is
+ incomplete and no component claim is valid. It then enables exactly one of
+ persistent Q8_1 scratch, grouped attention-A, or the graph-compatible B+HC
+ call, with K1024 persistent kept disabled because it is a separate opt-in.
+ The grouped and HC oracle summaries must have `calls>0`, `skips=0`, and zero
+ relevant mismatches. `summary.txt` must say `promotion_gate=pass`. When it
+ is blocked, use the named `*_differences` arms and their `.diff` or
+ `.comparison.txt` files to identify a component; if no single arm differs
+ but `default_fast` does, report an interaction rather than blaming an
+ individual kernel. The tensor oracles and synthetic parity test are the
+ bit-exact component gates; the top-128 smoke dump and every scorer TSV row
+ are complementary end-to-end drift detectors, not a full-logit proof.
+- Exercise CUDA DSpark at verifier/proposer depth 5 with the fast paths enabled
+ and disabled. Require identical final output, zero verifier errors, and
+ matching full/partial acceptance histograms. Test both the generic batch
+ verifier (direct Q2 path) and CUDA exact-N (one-row decode paths); do not
+ infer speculative speedup from the target-only benchmark.
- For native MXFP4 changes, run
`make test-mxfp4-cuda CUDA_ARCH=native` on the multi-GPU CUDA host only after
receiving explicit permission for `192.168.60.250`, and
@@ -811,6 +1168,20 @@ a substitute for CUDA or Metal release testing.
- Do not use the mixed q2-q4 or Q4 Flash GGUFs for routine Strix Halo QA yet.
They are dangerous on this machine for now because the ROCm path can hit
system OOM instead of failing cleanly.
+- When ROCm Q4 code changes, run `make test-strix-rocm-q4-parity` and
+ `make test-strix-rocm-q4-prefill` before attempting a model. The prefill
+ oracle must compare the TILE8 default with
+ `DS4_ROCM_DISABLE_Q4_PREFILL_TILE8=1` at K=256, 1024, and 4096 and at token
+ counts covering a partial tile and the 128-token production chunk. Require
+ bitwise dense, pair, Q4-attention-B, and Q8-attention-B parity with intact
+ canaries. A REQUIRE-plus-DISABLE arm must fail before modifying output.
+- Keep ROCm grouped attention-A decode opt-in until a model A/B wins. Its
+ fail-closed test uses `DS4_ROCM_ENABLE_Q4_GROUPED_ATTN_A=1`,
+ `DS4_ROCM_REQUIRE_Q4_GROUPED_ATTN_A=1`, and
+ `DS4_ROCM_Q4_GROUPED_ATTN_A_STATS=1`; require dispatches and groups above
+ zero, with zero fallbacks/failures and bitwise equality to the per-group
+ reference. This synthetic coverage does not supersede the Q4-model OOM
+ warning above.
- Run a short CLI prompt:
`./ds4 -m gguf/DeepSeek-V4-Flash-IQ2XXS-w2Q2K-AProjQ8-SExpQ8-OutQ8-chat-v2-imatrix-0731.gguf --ctx 4096 --nothink -p "Reply with exactly: OK"`.
- For DeepSeek Flash and GLM 5.3 Flash decode, confirm the default path uses
diff --git a/README.md b/README.md
index 503f00c630..07d8fe1761 100644
--- a/README.md
+++ b/README.md
@@ -87,6 +87,9 @@ next sections.
guide for contributors. **Read this before sending a pull request**.
- [QA_BEFORE_RELEASES.md](QA_BEFORE_RELEASES.md): the complete release test
matrix, including the remote Metal, CUDA, and ROCm machines.
+- [ENVIRONMENT_VARIABLES.md](ENVIRONMENT_VARIABLES.md): complete runtime,
+ test, and tooling environment-variable inventory, with a curated quick
+ reference for supported rollback, fail-closed, and diagnostic switches.
- [gguf-tools/README.md](gguf-tools/README.md): offline GGUF generation,
imatrix collection, quantization tooling, and quality checks.
- [gguf-tools/imatrix/README.md](gguf-tools/imatrix/README.md): how the
@@ -382,10 +385,11 @@ GGUF of about 5.6 GiB. It is not a standalone model. Download it once:
The support file can be used with the 0731 Flash `ds4f-q2`, `ds4f-q2-q4`, and
`ds4f-q4` models listed above. It is checkpoint-specific
and must not be paired with an older Flash model. For now **DeepSeek V4 PRO**
-is not supported. On Metal, the main model may be resident or use
-`--ssd-streaming`; the support model still adds its own weights and runtime
-state to the memory requirement. DSpark replaces the legacy one-stage MTP
-support model for that run rather than stacking with it.
+is not supported. On Metal, CUDA, and ROCm, the main model may be resident or
+use `--ssd-streaming`; the support model is kept separately mapped or
+device-cached and adds its own weights and runtime state to the memory
+requirement. DSpark replaces the legacy one-stage MTP support model for that
+run rather than stacking with it.
Run it with the normal sampling defaults:
@@ -428,13 +432,623 @@ The same DSpark flags work with `ds4-agent` and with non-batched
`ds4-server` requests. Session-batched serving currently uses ordinary target
decoding.
+On a single accelerator, the main model can instead stream its routed experts
+from SSD while the DSpark support model remains mapped or device-cached
+separately. On Metal the support mapping is file-backed and pageable; CUDA and
+ROCm prepare a separate device cache. Select the backend with `--metal`,
+`--cuda`, or `--rocm`:
+
+```sh
+./ds4 -m ds4flash.gguf \
+ --mtp-model gguf/DeepSeek-V4-Flash-DSpark-support-0731.gguf \
+ --dspark --metal --ssd-streaming \
+ --ssd-streaming-cache-experts 16 --temp 0
+```
+
+Use `--cuda` in a CUDA build. On ROCm, use `--rocm` and a verification-safe
+cache, for example `--ssd-streaming-cache-experts 32`.
+
+For memory-constrained Metal systems, use a small graph workspace as well as a
+small expert cache. A practical 16 GiB starting point is:
+
+```sh
+./ds4 -m ds4flash.gguf \
+ --mtp-model gguf/DeepSeek-V4-Flash-DSpark-support-0731.gguf \
+ --dspark --metal --ssd-streaming \
+ --ssd-streaming-cache-experts 16 \
+ --ctx 4096 --prefill-chunk 128 --temp 0
+```
+
+When DSpark+SSD runs on a Mac with at most 24 GiB and neither
+`--prefill-chunk` nor `DS4_METAL_PREFILL_CHUNK` is set, the runtime selects 128
+automatically. Set `DS4_DSPARK_LOW_MEMORY_PREFILL_CHUNK=0` to retain the normal
+workspace policy, or set it to another row count.
+
+The Metal SSD verifier already supports the checkpoint's full five-draft
+speculative block. With top-6 routing it needs at least 30 effective target
+expert-cache slots; `--ssd-streaming-cache-experts 32` is the practical
+five-draft setting. Smaller caches automatically limit the verifier to the
+number of complete top-k rows that fit (a 16-expert cache normally selects two
+rows). The Metal proposer follows that effective verifier/cache cap, avoiding
+work on a suffix that cannot be consumed. Set
+`DS4_METAL_DSPARK_PROPOSER_BLOCK_MAX=0` to restore the checkpoint's native
+five-row proposer for an A/B control, or set a positive value to cap it
+explicitly. Override the verifier policy independently with
+`DS4_DSPARK_SSD_VERIFY_BLOCK_MAX=N`.
+
+Metal can experimentally mirror the final target-hidden prefill row from the
+HC weighted-sum kernel itself, avoiding a separate 16 KiB blit and
+compute/blit encoder transition on each captured target layer. Enable it with
+`DS4_METAL_ENABLE_DSPARK_CAPTURE_FUSED_LAST=1`; the historical
+weighted-sum-plus-blit sequence remains the default because short M1 Pro SSD
+A/B runs were bit-identical but did not show a repeatable throughput win.
+`DS4_METAL_DISABLE_DSPARK_CAPTURE_FUSED_LAST=1` is the dominant kill switch.
+
+An experimental single-device Metal verifier can use the current target
+logits for the first draft and evaluate only the remaining `N-1` target rows.
+Enable it with `DS4_METAL_DSPARK_ACCEPTANCE_ONLY_VERIFY=1`; it remains opt-in
+because the smaller batch did not improve throughput on the measured M1 Pro
+SSD path. Two-draft blocks retain the legacy verifier
+because its one-row SSD routed-FFN path does not yet use the tiny-batch expert
+table. A five-draft block starting exactly on a ratio-4 compressor boundary
+also retains the legacy path so acceptance arithmetic does not switch to the
+aligned compressor kernel. After verification rolls back,
+the exact replay also skips the output head and logits readback for accepted
+prefix tokens whose logits would be discarded; set
+`DS4_METAL_DSPARK_HEADLESS_REPLAY=0` to restore the legacy replay. With
+`DS4_DSPARK_STATS=1`, `metal_accept_only`, `metal_verify_rows_saved`, and
+`metal_replay_headless` show how often these paths were exercised.
+
+On very small unified-memory Macs, an additional diagnostic can keep only the
+stage-0 `main_norm` and `main_proj` support tensors resident. Set
+`DS4_METAL_DSPARK_PIN_MAIN_PROJ=1`; the 0731 support file locks about 51 MiB,
+not the full 5.6 GiB GGUF. A failed lock is non-fatal and leaves the existing
+pageable path active. Keep this opt-in until a same-machine A/B shows lower
+`prop_setup`/generation time without reducing target-only throughput.
+
+An experimental two-draft Metal SSD verifier can commit a full accept without
+the normal rollback/replay pass:
+
+```sh
+DS4_METAL_DSPARK_EXACT2=1 DS4_DSPARK_STATS=1 \
+./ds4 -m ds4flash.gguf \
+ --mtp-model gguf/DeepSeek-V4-Flash-DSpark-support-0731.gguf \
+ --dspark --metal --ssd-streaming \
+ --ssd-streaming-cache-experts 16 --ctx 4096 --prefill-chunk 128 \
+ --temp 0
+```
+
+It uses the canonical one-row decode kernels in layer order, restores and
+replays token zero on a partial accept, and defaults both proposal and verify
+width to two. Keep it opt-in until a long same-machine run is byte-identical,
+has `exact2_attempt>0` and `exact2_fallback=0`, and improves throughput. The
+generic Metal verifier can already evaluate five drafts together with a
+32-expert cache, but its batch state is not numerically interchangeable with
+ordinary decode and therefore still requires rollback plus exact replay.
+
+`DS4_METAL_DSPARK_EXACTN_UNION=1` enables a separate experimental Metal SSD
+verifier for two through five draft tokens. It executes canonical one-row
+target decode in layer order, loads the union of the rows' routed experts once
+per layer, and commits its verifier state directly after a full accept. On a
+partial match it restores the frontier once, skips the boundary oracle,
+exact-two path, and legacy token-by-token verifier, then exactly replays only
+the already verified prefix. With `DS4_DSPARK_STATS=1`,
+`exactn_union_partial_replay` and `exactn_union_verify_skip` should advance
+together; `exactn_union_partial_replay_ms` isolates the required commit replay.
+Set `DS4_DSPARK_FIXTURE_REQUIRE_METAL_EXACTN_PARTIAL=1` to require at least one
+such partial match, equal replay/skip counts, no exact-union error fallback,
+and byte-identical fixture output. The model-backed
+`test-metal-exactn-oracle` is byte-identical to sequential decode for N=2..5,
+including every N=5 partial prefix, EOS in the first or a middle row, serialized
+KV/compressor state, logits, and a four-token continuation. Five drafts plus
+the target token already available at the start of the cycle cover the
+six-token speculative-cycle limit. Exact-union remains opt-in: correctness
+does not imply a throughput improvement on a particular memory configuration.
+
+For an independent Q8 output-head A/B inside exact-union, set
+`DS4_METAL_DSPARK_EXACTN_BATCH_HEAD=1`. HC collapse and normalization remain on
+the canonical one-row kernels, while one bit-exact decode-row dispatch projects
+all two through five verifier rows to vocabulary logits. Non-Q8 output weights
+are ineligible and a dispatch failure falls back to the ordinary per-row heads.
+`DS4_METAL_DISABLE_DSPARK_EXACTN_BATCH_HEAD=1` is the unconditional kill switch
+and wins if both variables are set. The
+`metal_exactn_batch_head_attempt`, `metal_exactn_batch_head_use`, and
+`metal_exactn_batch_head_fallback` counters identify the selected path; set
+`DS4_DSPARK_FIXTURE_REQUIRE_METAL_EXACTN_BATCH_HEAD=1` to require a nonzero,
+fallback-free use with byte-identical output.
+
+The generic model-backed exact-N oracle keeps this Q8-only experiment disabled,
+so it remains valid for target models with another output quantization. To add
+model-backed batch-head coverage, use an OutQ8 target explicitly:
+
+```sh
+DS4_TEST_METAL_EXACTN_BATCH_HEAD=1 \
+DS4_TEST_MODEL=/path/to/target-OutQ8.gguf \
+make test-metal-exactn-oracle
+```
+
+The Metal proposer also has an independent experiment for confidence/Markov
+synchronization overhead. Set `DS4_METAL_DSPARK_DEVICE_PROPOSER=1` when the
+final confidence projection and both Markov matrices are Q8_0. On an eligible
+single-device, tier-zero run it keeps the previous token, confidence decisions,
+and Markov argmax chain on Metal, reuses the first confidence already computed
+by the proposer, and returns one result for the complete draft block. Unlike
+the CUDA experiment, the Metal path is eligible with SSD streaming; tensor
+placement and proposal-quality mode remain excluded. It stops at the first
+rejected confidence row and preserves the smaller-token argmax tie break.
+Unsupported layouts, an incomplete result, or a CPU sigmoid-policy mismatch
+fall back to the existing per-row implementation.
+
+`DS4_METAL_DSPARK_NO_DEVICE_PROPOSER=1` is the unconditional kill switch;
+`DS4_DSPARK_NO_GPU_MARKOV=1` and `DS4_DSPARK_NO_MARKOV=1` also keep the path
+disabled. This remains opt-in because Q8 confidence accumulation moves from the
+host CPU to Metal and therefore needs a same-machine greedy oracle and A/B.
+With `DS4_DSPARK_STATS=1`, require
+`metal_device_proposer_attempt == metal_device_proposer_use > 0`,
+`metal_device_proposer_fallback=0`, and
+`metal_device_proposer_policy_mismatch=0`. The acceptance fixture enforces
+those conditions and byte-identical output with
+`DS4_DSPARK_FIXTURE_REQUIRE_METAL_DEVICE_PROPOSER=1`.
+
+Exact-union normally waits for every layer's routed-tail command buffer before
+releasing its private expert-address scope. For an isolated A/B,
+`DS4_METAL_DSPARK_EXACT_ROWS_ASYNC_TAILS=1` commits that tail without the CPU
+wait, retains all scope resources until command-buffer completion, and lets the
+next layer's router boundary provide the required ordering. The switch has no
+effect outside exact-union and is also opt-in; unset it for the synchronous
+control. Validate serialized state and greedy output as well as verifier time,
+because removing a host wait is not by itself evidence of an end-to-end gain.
+
+The AProjQ4 Metal decode path has several exact dispatch fusions relevant to
+this verifier:
+
+- HC RMSNorm plus the narrow F16 HC mixer is the M1-M4 default, including SSD
+ split phases such as `TO_ROUTER`. Use
+ `DS4_METAL_DISABLE_PRE_M5_HC_NORM_MIX_FUSE=1` for the reference control;
+ `DS4_METAL_ENABLE_HC_NORM_MIX_FUSE=1` is the explicit non-default gate on
+ other Apple generations.
+- The Q4 Q-A/KV projections can share a dispatch with eligible F16 compressor
+ projection/store work. It remains opt-in in both exact-union and ordinary
+ `FULL` decode via `DS4_METAL_ENABLE_Q4_QKV_COMPRESSOR_FUSE=1`; the first M1
+ Pro SSD A/B reduced dispatch count but did not improve verifier time. In
+ either scope,
+ `DS4_METAL_DISABLE_Q4_QKV_COMPRESSOR_FUSE=1` selects the existing fallback.
+- The eligible Q4 attention-output B projection can perform the following HC
+ expansion in the same dispatch. Use
+ `DS4_METAL_DISABLE_Q4_ATTN_OUT_HC_FUSE=1` as its isolated A/B control.
+- For an AProjQ4 multi-row attention-output batch with either attention B in
+ Q8 or Q4_K, the opt-in
+ `DS4_METAL_ENABLE_Q4_ATTN_OUT_TINY_BATCH=1` evaluates two through five rows
+ in two dispatches while retaining the canonical one-row reduction order for
+ every row. This covers the generic suffix verifier; the exact-union tape is
+ intentionally still row-by-row and does not select this helper. Other
+ output formats, unsupported shapes, a disabled Q4 classic matvec, or a
+ dispatch setup failure return to the existing row-wise path.
+ `DS4_METAL_DISABLE_Q4_ATTN_OUT_TINY_BATCH=1` is the unconditional kill
+ switch and wins when both variables are set. For a fail-closed model-backed
+ generic-verifier test, `DS4_METAL_REQUIRE_Q4_ATTN_OUT_TINY_BATCH=1` implies
+ the enable gate for N=2..5 and turns an ineligible shape, the kill switch, or
+ a dispatch failure into a hard error instead of a silent row-wise fallback.
+
+The AProjQ8 Q-A/KV plus compressor compound remains the M1-M5 default for
+eligible resident `FULL` decode. For an SSD-streaming A/B, including the
+exact-union `TO_ROUTER` collection prefix, set
+`DS4_METAL_ENABLE_Q8_QKV_COMPRESSOR_FUSE=1`. Ratio-4 layers combine the Q8
+Q-A/KV pair with both attention and indexer F16 compressor pairs; ratio-128
+layers combine it with the attention pair. The kernel preserves the canonical
+NSG=4 Q8 and NR0=2 F16 reduction trees. A diagnostic Q8 NSG override or the
+experimental NR0=4 compressor schedule therefore selects the separate
+dispatches. `DS4_METAL_REQUIRE_Q8_QKV_COMPRESSOR_FUSE=1` turns such a fallback
+into a visible error for model-backed tests. The existing ratio-specific
+pre-M5/M5 QKV compound disable variables remain authoritative. Keep the SSD
+extension opt-in until warm and cold A/B runs show a gain: it removes a launch
+per row and layer but reads the same model bytes, and a compound grid can
+change the order in which distant GGUF pages are faulted.
+
+Additional PR #755 ports keep their established kernels as shape/resource
+fallbacks:
+
+- On Apple M1 through M5, an eligible one-row HC producer combines the F16
+ RMSNorm/mixer, HC split and Sinkhorn-weighted sum, and destination RMSNorm in
+ one compound dispatch for both attention and FFN producers. The global
+ rollback is `DS4_METAL_DISABLE_HC_PRODUCER_PRE_NORM_FUSE=1`; the narrower
+ controls are `DS4_METAL_DISABLE_PRE_M5_HC_PRODUCER_PRE_NORM_FUSE=1` and
+ `DS4_METAL_DISABLE_M5_HC_PRODUCER_PRE_NORM_FUSE=1`. The existing
+ `DS4_METAL_DISABLE_PRE_M5_DECODE_PORTS=1` umbrella also disables it before
+ M5. `DS4_METAL_ENABLE_HC_PRODUCER_PRE_NORM_FUSE=1` permits a focused trial
+ on another eligible Metal device.
+- For an eligible ratio-4 layer on Apple M1 through M5, the standalone F16 compressor path can
+ project the attention and indexer KV/gate pairs and append both recurrent
+ states in one quad dispatch. It is the default in ordinary `FULL` decode and
+ the exact-union collection prefix when the larger Q4 compound dispatch did
+ not already store those states. Use
+ `DS4_METAL_DISABLE_COMPRESSOR_QUAD_STORE=1` for the reference path;
+ `DS4_METAL_DISABLE_PRE_M5_COMPRESSOR_QUAD_STORE=1` is an additional
+ compatibility rollback. `DS4_METAL_ENABLE_COMPRESSOR_QUAD_STORE=1` permits
+ a focused trial on another Metal device and widens the phase scope for
+ diagnostics.
+- The exact ratio-4, one-compressed-row pool specialization is the M1-M5
+ default for supported 128- and 512-element head shapes. Disable it globally
+ with `DS4_METAL_DISABLE_COMPRESSOR_EXACT_POOL_RATIO4=1`, or use the
+ pre-M5/M5 controls
+ `DS4_METAL_DISABLE_PRE_M5_COMPRESSOR_EXACT_POOL_RATIO4=1` and
+ `DS4_METAL_DISABLE_M5_COMPRESSOR_EXACT_POOL_RATIO4=1`. For a diagnostic run,
+ `DS4_METAL_REQUIRE_COMPRESSOR_EXACT_POOL_RATIO4=1` turns an unavailable
+ exact dispatch into a visible failure instead of silently selecting the
+ legacy reduction sequence.
+
+Metal FlashAttention pipeline selection also keeps a generation-aware
+one-entry host memo for hot specializations. This changes pipeline lookup, not
+kernel arithmetic. Disable the pad/block memo with
+`DS4_METAL_DISABLE_PRE_M5_FLASH_ATTN_PAD_BLK_MEMO=1` and the batched/vector
+memo with `DS4_METAL_DISABLE_PRE_M5_FLASH_ATTN_BATCHED_MEMO=1` when isolating
+host-side dispatch overhead.
+
+The former 512-column streaming Metal top-k specialization has been removed;
+its ordering was not deterministic for every input. The regular deterministic
+top-k implementation is now used instead and has no runtime re-enable switch.
+Use a previous binary only as a performance control, and require identical
+selected ids on tie-heavy inputs before comparing timing.
+
+Apple M1 defaults to a specialized SSD-streaming decode path for the exact
+IQ2_XXS/Q2_K routed-MoE shape with 256 experts, top-6 routing, and a
+4096-to-2048 gate/up projection. It replaces the IQ2 address-table pair-SwiGLU
+producer, including complementary resident/missing cache masks.
+It preserves the canonical dot-product,
+reduction, clamp, activation, and route-weight order but writes `mid` directly
+instead of materializing the otherwise unused gate/up rows. Every other
+device, shape, streaming mode, unsupported mask/accumulate mode, or unavailable
+pipeline keeps the canonical producer. Set
+`DS4_METAL_DISABLE_M1_IQ2_MID_ONLY=1` to restore the canonical producer.
+For fail-closed model coverage, `DS4_METAL_REQUIRE_M1_IQ2_MID_ONLY=1` rejects
+an ineligible supported address-table dispatch; the kill switch still takes
+precedence. The former `DS4_METAL_ENABLE_M1_IQ2_MID_ONLY=1` opt-in is accepted
+as a harmless compatibility setting because the path is now automatic.
+`make test-metal-iq2-midonly` compares all 12,288 top-6
+output words bitwise at full shape for both unmasked and complementary masked
+address tables, verifies that the candidates leave gate/up sentinels untouched,
+and checks output guards. The routed-MoE stage profiler reports
+`iq2_stream_addr_mid_only_4096x2048` or
+`iq2_stream_addr_mask_mid_only_4096x2048` when the model path is actually
+covered.
+
+These gates change dispatch and intermediate-memory traffic, not model
+arithmetic. Compare byte-identical output, exact-union counters, stage timings,
+and generation rate on the same machine; do not infer a speedup from a lower
+dispatch count alone.
+
+CPU greedy decoding and the verifier's excluding-argmax scan use an unrolled
+eight-lane implementation by default, including scalar tail handling and
+first-index tie semantics. Set `DS4_CPU_DISABLE_UNROLLED_ARGMAX=1` to restore
+the scalar scan for an isolated A/B. `tests/test_sampling` compares both paths,
+including cross-lane ties, excluded ids, and non-multiple-of-eight vocabulary
+sizes.
+
+Exact file views for the two token embedding rows and repeatedly used Q8
+support tensors are automatic; the compatibility kill switches are
+`DS4_METAL_DISABLE_TOKEN_EMBED_EXACT_VIEW=1` and
+`DS4_METAL_DISABLE_SUPPORT_Q8_DECODE_EXACT_VIEWS=1`.
+
+DSpark attempts a proposal on every eligible cycle. Proposal cadence is not
+adaptively throttled, so the reported acceptance rate covers the full runtime
+sample. Quality and strict DSpark modes remain target-only.
+
+Tune the expert-cache count for the available accelerator memory. ROCm needs
+enough slots for a whole verification block (30 for the 0731 model; use at
+least 32), and currently supports the IQ2_XXS/Q2_K or all-Q2_K routed-expert
+layouts. CUDA uses a transient selected-expert cache for each target block.
+The DSpark support weights are included in the startup memory budget even when
+the Metal file-backed mapping remains pageable. This combination is
+single-device only; CPU, distributed or
+multi-GPU placement, tensor parallelism, and legacy MTP support models remain
+incompatible with DSpark plus SSD streaming.
+
+Resident single-GPU CUDA skips verifier captures that rollback/replay cannot
+consume, batches frontier snapshot/restore copies behind one device fence,
+computes the output head only for the final replayed token, pads the five-row
+Q8 proposer head to the tensor-core shape, and fuses proposer Q RMSNorm with
+RoPE. CUDA and ROCm also avoid the Metal-only mid-token submission split: on
+those backends the same flush is a device-wide synchronization and only drains
+the launch pipeline. The two kernel-selection kill switches for before/after
+measurements are
+`DS4_CUDA_DSPARK_NO_PADDED_HEAD=1` and
+`DS4_CUDA_DSPARK_NO_Q_NORM_ROPE_FUSION=1`.
+
+CUDA fuses HC split, weighted sum, and RMSNorm across multiple batch rows,
+including the DSpark proposer and verifier; use
+`DS4_CUDA_DISABLE_HC_SPLIT_NORM_FUSED=1` for an A/B fallback to the separate
+kernels. AProjQ4 CUDA decode can also share the activation quantization for
+the Q-A/KV dense pair; `DS4_CUDA_DISABLE_Q4_DENSE_PAIR=1` selects the two
+standalone projections. The canonical Q4 path submits to the decode stream so
+these projections and the attention-output tail can participate in CUDA
+decode graphs.
+
+Single-token resident CUDA can also experiment with folding the canonical
+Q8_1 activation emitted by the 4096-wide HC split plus RMSNorm stage into its
+next MMVQ consumer. This remains opt-in pending GB10/DGX validation: set
+`DS4_CUDA_ENABLE_Q8_FOLD=1`; `DS4_CUDA_NO_Q8_FOLD=1` is the dominant kill
+switch. The sidecar is one-shot and keyed by model map, physical device,
+stream, source pointer, and session epoch. Capture, scratch growth, a model-map
+or device transition, and every lookup mismatch reject or invalidate it and
+fall back to the established quantizer. For a diagnostic run, disable decode
+graphs and add `DS4_CUDA_Q8_FOLD_ORACLE=1`; the oracle compares canonical Q8_1
+bytes and the reached aligned-Q8 or IQ2 MoE consumer output, then always keeps
+the freshly quantized reference. Require nonzero fold hits, `byte_calls`, and
+`output_calls`, with zero mismatches and skips before considering promotion.
+The experiment supports ds4's serialized, single-inference-host-thread CUDA
+runtime only; embeddings that submit concurrently to the same CUDA stream
+must leave it disabled.
+
+On a single DGX Spark/GB10, the AProjQ4 path also mirrors the safe parts of
+the aligned-Q8 decode work while retaining canonical Q4_K MMVQ/Q8_1
+arithmetic:
+
+- dense and paired Q4 projections reuse the persistent 1-MiB Q8_1 scratch;
+ `DS4_CUDA_NO_Q4_DENSE_SCRATCH=1` restores pool allocation;
+- attention-output A evaluates all output groups through one channel-grouped
+ MMVQ dispatch per token, preserving the one-row reduction tree of every
+ group. For DSpark verification widths 2--8,
+ `DS4_CUDA_ENABLE_Q4_GROUPED_ATTN_A_BATCH=1` flattens `(token, group)` into
+ MMVQ channels and replaces the per-token loop with one grouped MMVQ
+ dispatch while keeping `ncols_dst=1`;
+ `DS4_CUDA_NO_Q4_GROUPED_ATTN_A_BATCH=1` restores the per-token grouped loop
+ and `DS4_CUDA_NO_Q4_GROUPED_ATTN_A=1` restores the per-group loop;
+- for prefill widths above eight, the default eligible GB10 path quantizes the
+ strided `[token][group][K]` input in one launch and writes each group directly
+ into `[token][group][rank]`. It removes the eight F32 pack/unpack copies while
+ keeping one established stream-K MMQ reduction per group. On the production
+ `groups=8`, `K=4096`, `rank=1024` shape, a fixed-layout eight-warp Q8_1
+ producer is also the default: each warp emits two canonical 128-value DS4
+ records, reducing quantizer CTA count by four while preserving every output
+ byte. `DS4_CUDA_NO_Q4_GROUPED_ATTN_A_Q81=1` restores only the generic
+ strided Q8_1 producer, and
+ `DS4_CUDA_REQUIRE_Q4_GROUPED_ATTN_A_Q81=1` fails closed if the specialized
+ producer is not selected. Set
+ `DS4_CUDA_NO_Q4_GROUPED_ATTN_A_PREFILL=1` for the dominant local rollback;
+ exact `DS4_CUDA_ENABLE_Q4_GROUPED_ATTN_A_PREFILL=0` is also a compatibility
+ opt-out. Add `DS4_CUDA_REQUIRE_Q4_GROUPED_ATTN_A_PREFILL=1` for fail-closed
+ tests. The separate single-grid/grid.z submission remains opt-in. The
+ unrelated 16-warp MMQ experiment also remains opt-in and is not used by
+ this producer;
+- attention-output B keeps its canonical MMVQ result and the ordinary HC
+ epilogue inside the graph-compatible fused call. The row-packed epilogue
+ remains oracle-only until a GB10 device run proves it bit-exact;
+- the exact Q-b shape `32768x1024` has an experimental persistent-CTA kernel
+ behind `DS4_CUDA_ENABLE_Q4_K1024_PERSISTENT=1`, with
+ `DS4_CUDA_NO_Q4_K1024_PERSISTENT=1` taking precedence. Tests can add
+ `DS4_CUDA_REQUIRE_Q4_K1024_PERSISTENT=1` to fail instead of silently using
+ canonical MMVQ when the persistent dispatch is unavailable; this admission
+ now fails before quantization, output clearing, or any kernel enqueue. Set
+ `DS4_CUDA_Q4_K1024_PERSISTENT_STATS=1` for host-dispatch candidate/use/
+ fallback counters. For a bitwise model-backed check, run with
+ `DS4_CUDA_DECODE_GRAPHS=0 DS4_CUDA_Q4_K1024_PERSISTENT_ORACLE=1`; the oracle
+ forces the candidate, compares it with canonical MMVQ, and always retains
+ canonical output.
+
+`DS4_CUDA_NO_Q4_GB10_FAST=1` is the umbrella rollback for these new GB10
+choices; it does not disable the older cross-CUDA Q-A/KV pair itself. For a
+fail-closed grouped attention comparison, set
+`DS4_CUDA_ENABLE_Q4_GROUPED_ATTN_A_BATCH=1`,
+`DS4_CUDA_REQUIRE_Q4_GROUPED_ATTN_A_BATCH=1`, and
+`DS4_CUDA_Q4_GROUPED_ATTN_A_ORACLE=1`. The oracle computes the established per-group
+MMVQ reference (or the established per-token grouped loop for a multi-token
+candidate), reports aggregate calls/mismatches/skips plus separate
+batch_candidates/batch_calls/batch_mismatches/batch_skips, and retains
+canonical output. A valid multi-token test has nonzero candidates/calls and
+zero batch mismatches/skips. The
+oracle disables decode-graph capture. For a multi-token candidate, if it
+encounters another active capture or cannot allocate comparison scratch, it
+directly enqueues the canonical reference instead of consuming an unchecked
+candidate. The scratch, grouped, and persistent paths are also covered by
+`make test-mmq-parity-cuda CUDA_ARCH=sm_121`.
+
+CUDA Q4_K MMQ performs its non-finite output guard in the final write-back
+(or after the final stream-K fixup) instead of launching a separate
+full-output sanitizer. Finite results and the per-group reduction order are
+unchanged; the resident CUDA prefill harness checks them bit-for-bit against
+the former pack/MMQ/unpack path.
+
+Two additional CUDA fusions remain experimental until a device oracle passes
+on the target GPU. `DS4_CUDA_ENABLE_HC_NORM_MIX_FUSE=1` combines HC RMSNorm
+with the narrow F16 mixer when the selected standalone kernels have the same
+reduction order; with the normal one-token cuBLAS path, also set
+`DS4_CUDA_NO_F16_CUBLAS_ONE=1` to exercise it. The controls are
+`DS4_CUDA_DISABLE_HC_NORM_MIX_FUSE=1` and
+`DS4_CUDA_DISABLE_Q4_ATTN_OUT_HC_FUSE=1`. The Q4 attention-output B plus HC
+path is automatic when MMQ is disabled, where the existing one-dispatch Q8_K
+implementation is bit-compatible with its fallback. With the normal
+MMVQ/Q8_1 decode path, the GB10 graph-compatible call preserves both the
+canonical MMVQ projection and the ordinary HC expansion. The specialized
+row-packed epilogue is evaluated only by the oracle below and is never
+consumed by normal decoding. The older, truly single-dispatch Q8_K experiment
+is isolated behind
+`DS4_CUDA_Q4_ATTN_OUT_HC_Q8K_EXPERIMENT=1` and may differ numerically from
+MMVQ/Q8_1.
+
+For a fail-closed hardware comparison, set
+`DS4_CUDA_Q4_ATTN_OUT_HC_ORACLE=1`. It retains the canonical MMVQ/Q8_1 output,
+compares both the row-packed epilogue and the Q8_K compound bit-for-bit, and
+prints `epilogue_mismatches`, `q8k_mismatches`, and `skips` at exit. The
+oracle avoids readback while CUDA graph capture is active; run a separate
+non-captured diagnostic and require `calls>0`, `skips=0`, and
+`epilogue_mismatches=0` before promoting the row-packed path back into normal
+decoding. A zero-call summary is therefore an explicit failed coverage gate,
+not a silent pass.
+
+An experimental resident-CUDA path can run the existing aligned
+IQ2_XXS/Q2_K vector MoE kernels for two-to-five-draft routed batches,
+preserving the established fused-SoA path as an automatic fallback:
+
+```sh
+DS4_CUDA_DSPARK_TINY_ALIGNED_VEC=1 DS4_DSPARK_STATS=1 \
+./ds4 --cuda -m ds4flash.gguf \
+ --mtp-model gguf/DeepSeek-V4-Flash-DSpark-support-0731.gguf \
+ --dspark --temp 0 -p 'Write a Python quicksort function with comments.'
+```
+
+Keep the aligned tiny-batch path opt-in until the same-machine acceptance,
+decode-consistency, and throughput comparisons pass on CUDA hardware.
+
+An experimental exact two-token resident-CUDA verifier is available for a
+DGX Spark A/B test. It uses the ordinary decode kernels, commits a two-token
+full accept without rollback/replay, and replays only the first token on a
+partial accept. By default the switch runs both the proposer and verifier at
+width two, instead of evaluating the checkpoint's native five-row proposal
+when only two drafts can be consumed:
+
+```sh
+DS4_CUDA_DSPARK_EXACT2=1 DS4_DSPARK_STATS=1 \
+./ds4 --cuda -m ds4flash.gguf \
+ --mtp-model gguf/DeepSeek-V4-Flash-DSpark-support-0731.gguf \
+ --dspark --temp 0 -p 'Write a Python quicksort function with comments.'
+```
+
+The support model uses non-causal attention across the proposal block, so a
+two-row proposal is not guaranteed to be a prefix-identical version of its
+native five-row proposal. The target verifier still protects the emitted
+greedy continuation. For isolated A/B tests,
+`DS4_CUDA_DSPARK_PROPOSER_BLOCK_MAX=0` preserves the native proposer and an
+explicit value such as `2` caps it independently of exact-2.
+
+CUDA also has an opt-in tiled online-softmax kernel for this non-causal support
+attention. It shares each raw KV row across a group of attention heads and is
+selected only for the DSpark raw-ring/head geometry it supports; every other
+shape keeps the reference kernel. Enable it with
+`DS4_CUDA_ENABLE_DSPARK_NONCAUSAL_ONLINE=1`. The emergency control
+`DS4_CUDA_DISABLE_DSPARK_NONCAUSAL_ONLINE=1` wins when both variables are set.
+The online reduction order can change draft floating-point results even though
+the target verifier still protects greedy output. Use
+`DS4_DSPARK_VERIFY_NONCAUSAL=1` to print the first three comparisons against a
+host double-precision reference, and require the final target continuation to
+remain byte-identical in the performance A/B.
+
+Keep this path opt-in until the CUDA acceptance fixture is byte-identical and
+the same-machine statistics show lower `propose`, `verify` plus `replay` time.
+The stats line reports `prop_capped`, `prop_scheduled_rows`, `exact2_attempt`,
+`exact2_full`, `exact2_partial`, and `exact2_fallback`; a valid run must
+exercise exact-2 and leave its fallback counter at zero.
+
+A separate resident exact-N CUDA experiment extends the same canonical
+one-token tape to two through five draft rows. It leaves hidden rows and all
+target weights on one GPU, submits the per-row ordinary decode kernels in one
+stream, and reads back only the `N-1` acceptance ids plus final logits. A full
+match therefore commits its already-exact KV/compressor state without replay;
+a partial match restores the pre-cycle frontier once and replays the prefix
+already proven by exact-N, without running the legacy verifier a second time.
+Only a backend error retains the legacy verifier/replay fallback. Enable it
+independently with:
+
+```sh
+DS4_CUDA_DSPARK_EXACTN=1 DS4_DSPARK_STATS=1 \
+./ds4 --cuda -m ds4flash.gguf \
+ --mtp-model gguf/DeepSeek-V4-Flash-DSpark-support-0731.gguf \
+ --dspark --temp 0 -p 'Write a Python quicksort function with comments.'
+```
+
+The default verifier cap under this gate is five (or the available prefill
+workspace when smaller). The proposer uses at most one fewer workspace row,
+because its support stage also carries the current target row; the existing
+explicit proposer and verifier cap variables still take precedence.
+`DS4_CUDA_DISABLE_DSPARK_EXACTN=1` is the
+kill switch and restores the previous path without changing the enable
+variable. Track `cuda_exactn_attempt`, `cuda_exactn_full`,
+`cuda_exactn_fallback`, its partial/error split, and `cuda_exactn_rows`. Keep
+this experiment disabled by default until a real CUDA oracle and a long greedy
+A/B show byte-identical output, no fallback errors, and a throughput win.
+
+The layer tape can separately reuse its position-independent CUDA decode
+islands with `DS4_CUDA_DSPARK_EXACTN_GRAPHS=1`. Graph keys use the stable
+device address (including each batch-row offset), not the short-lived tensor
+view wrapper. Four cache entries per layer/island remain reserved for ordinary
+decode and five more are isolated for exact-N rows, so a width-five verifier
+cannot evict the normal decode keys. The first encounter warms lazy allocators,
+the second captures/instantiates, and only later encounters are pure replay;
+benchmark at least 128--256 generated tokens rather than judging a short
+capture-heavy run. `DS4_CUDA_DISABLE_DSPARK_EXACTN_GRAPHS=1` is the dedicated
+kill switch, while `DS4_CUDA_DECODE_GRAPHS=0` still disables all decode graphs.
+The stats fields `cuda_exactn_graph_attempt`, `..._use`, `..._warm`,
+`..._capture`, `..._replay`, `..._no_slot`, and `..._failure` expose warmup,
+reuse, capacity misses, and retired captures. This first rollout is for
+serialized, single-session DGX testing; the graph cache and cuBLAS capture
+state remain process-global. The fixture can require a clean post-warmup
+replay (including zero no-slot/failure events) with
+`DS4_DSPARK_FIXTURE_REQUIRE_CUDA_EXACTN_GRAPHS=1`.
+
+For a separate output-head A/B, set
+`DS4_CUDA_DSPARK_EXACTN_BATCH_HEAD=1`. The experiment keeps HC collapse and
+normalization on the canonical one-row kernels, then runs the Q8 vocabulary
+projection for all exact-N rows through the bit-exact decode-row kernel. It is
+automatically ineligible for non-Q8 output weights and falls back to the
+ordinary per-row heads on a dispatch failure. The emergency kill switch is
+`DS4_CUDA_DISABLE_DSPARK_EXACTN_BATCH_HEAD=1` and wins when both variables are
+present.
+
+The CUDA proposer tail has a second, independent experiment for the fixed
+confidence/Markov synchronization overhead:
+
+```sh
+DS4_CUDA_DSPARK_DEVICE_PROPOSER=1
+```
+
+When the final confidence projection and both Markov matrices are Q8_0, this
+keeps the previous token, confidence decisions, and all Markov argmax steps on
+the decode stream and reads one 64-byte result for the whole draft block. It
+stops at the first rejected confidence row, preserves the Markov smaller-token
+tie break, and rechecks the returned confidence prefix with the established
+CPU sigmoid policy. Unsupported layouts, an incomplete result, or a policy
+mismatch fall back to the per-row implementation. The unconditional kill
+switch is `DS4_CUDA_DSPARK_NO_DEVICE_PROPOSER=1`; the older
+`DS4_DSPARK_NO_GPU_MARKOV` switch also keeps this path disabled.
+The initial gate is intentionally limited to resident, single-GPU, non-quality
+CUDA and reuses the already-computed first confidence value.
+
+This remains opt-in because the Q8 confidence accumulation moves from the host
+CPU to CUDA and must pass the DGX proposal/acceptance oracle before promotion.
+With `DS4_DSPARK_STATS=1`, require
+`cuda_device_proposer_attempt == cuda_device_proposer_use > 0`,
+`cuda_device_proposer_fallback=0`, and
+`cuda_device_proposer_policy_mismatch=0`. The acceptance fixture can enforce
+those conditions with
+`DS4_DSPARK_FIXTURE_REQUIRE_CUDA_DEVICE_PROPOSER=1`.
+
+The stats line separates `cuda_exactn_ms` into setup, layer, head, and read
+components, and reports restore, legacy-error-fallback verification, and
+partial replay time independently. `cuda_exactn_partial_replay` and
+`cuda_exactn_verify_skip` should advance together on valid partial matches;
+the batch-head attempt/use/fallback counters make its dispatch unambiguous.
+
+Set `DS4_DSPARK_FIXTURE_REQUIRE_CUDA_EXACTN=1` on the candidate acceptance
+fixture to require at least one `cuda_exactn_attempt` and zero
+`cuda_exactn_error_fallback`. The aggregate `cuda_exactn_fallback` is reported
+but is not required to be zero: it also includes valid partial draft matches,
+which deliberately restore the frontier and use exact replay.
+
+The acceptance fixture can exercise the same SSD path on both the target-only
+baseline and the DSpark run. It also requires real proposals and accepted
+draft tokens, so an unavailable verifier cannot pass as a silent no-op:
+
+```sh
+DS4_DSPARK_FIXTURE_BACKEND=cuda \
+DS4_DSPARK_FIXTURE_SSD_STREAMING=1 \
+DS4_DSPARK_FIXTURE_SSD_STREAMING_CACHE_EXPERTS=32 \
+make dspark-acceptance
+```
+
+For ROCm, use `make rocm-dspark-acceptance` with the same model, support, and
+SSD fixture environment variables. The ROCm-specific target preserves the HIP
+object set and linker; the generic target selects CUDA objects on non-Apple
+hosts. `make rocm-dspark-verify-depth` provides the corresponding verifier
+invariant test.
+
## Speed
The current q2 results use `ds4-bench` with the standard *Promessi sposi*
input, 2048-token context steps, and 128 greedy generation tokens at every
frontier. Each prefill number is for the next 2048-token chunk. The complete
sweeps are in [m5_max.csv](speed-bench/m5_max.csv) and
-[gb10.csv](speed-bench/gb10.csv).
+[gb10.csv](speed-bench/gb10.csv). The GB10 optimization methodology and
+validation are documented in
+[ds4_gb10_q2_cuda_port_results.md](speed-bench/ds4_gb10_q2_cuda_port_results.md).
| Machine | Backend | Context | Prefill | Generation |
| --- | --- | ---: | ---: | ---: |
@@ -442,10 +1056,10 @@ sweeps are in [m5_max.csv](speed-bench/m5_max.csv) and
| MacBook Pro M5 Max, 128 GB | Metal | 16384 | 572.53 t/s | 36.14 t/s |
| MacBook Pro M5 Max, 128 GB | Metal | 32768 | 557.04 t/s | 34.36 t/s |
| MacBook Pro M5 Max, 128 GB | Metal | 65536 | 398.50 t/s | 27.64 t/s |
-| DGX Spark GB10, 128 GB | CUDA | 2048 | 825.76 t/s | 18.05 t/s |
-| DGX Spark GB10, 128 GB | CUDA | 16384 | 872.44 t/s | 15.10 t/s |
-| DGX Spark GB10, 128 GB | CUDA | 32768 | 855.94 t/s | 14.43 t/s |
-| DGX Spark GB10, 128 GB | CUDA | 65536 | 822.98 t/s | 13.84 t/s |
+| DGX Spark GB10, 128 GB | CUDA | 2048 | 832.86 t/s | 20.58 t/s |
+| DGX Spark GB10, 128 GB | CUDA | 16384 | 883.81 t/s | 16.80 t/s |
+| DGX Spark GB10, 128 GB | CUDA | 32768 | 865.40 t/s | 15.99 t/s |
+| DGX Spark GB10, 128 GB | CUDA | 65536 | 833.44 t/s | 15.27 t/s |
Older measurements for machines and model variants not rerun in this pass are
kept for reference. They used the earlier CLI prompt procedure and are not
@@ -501,12 +1115,44 @@ context, and backend working-set limit leave less room. A plain number such as
`--ssd-streaming-cache-experts 4000` requests 4000 dynamic expert slots without
the two-layer reserve, but it can be reduced by the same final memory check.
Non-routed weights, KV cache, graph scratch, and activations need additional
-memory. The automatic cache budget takes
+memory.
+
+Metal SSD+DSpark also has an experimental, support-aware pre-cap for A/B tests.
+Set `DS4_METAL_DSPARK_SAFE_EXPERT_COUNT=1` to convert a numeric count to bytes
+and cap it, when measurable, after accounting for the target's non-routed
+weights, the context/KV estimate, and a 2 GiB active reserve for the mmap-backed
+support model. It does not yet price the complete batch-prefill workspace or a
+separate routed-prefill transient reserve. Startup reports requested/effective
+slots and the support reserve. If this policy cannot measure safe room, it
+retains the explicit count with a warning; the normal final memory check remains
+authoritative. The experiment does not affect `NGB` budgets or CUDA/ROCm.
+Prefer an `NGB` budget for normal use. The automatic cache budget takes
80% of the backend's recommended working set, subtracts non-routed weights, then
applies the same routed-prefill headroom before sizing the dynamic cache. Leave
the hot expert preload enabled for normal use; use `--ssd-streaming-cold` and
`--ssd-streaming-preload-experts N` only for measurements.
+For Metal IQ2_XXS/Q2_K models, eligible SSD prefill chunks automatically use
+grouped address matmuls when the dynamic cache can retain the complete expert
+domain. This includes normal 128-token chunks; the automatic range is 32–760
+tokens on the 256-expert Flash model and requires, for example,
+`--ssd-streaming-cache-experts 256`. Once that material condition is met,
+selection is fail-closed by default; no environment prefix is required. Set
+`DS4_METAL_ENABLE_IQ2_XXS_SSD_PREFILL_MM=0` or
+`DS4_METAL_DISABLE_IQ2_XXS_SSD_PREFILL_MM=1` for the legacy sparse-matvec
+rollback. `DS4_METAL_REQUIRE_IQ2_XXS_SSD_PREFILL_MM=0` keeps automatic
+selection but permits a fallback, while explicit `REQUIRE=1` also rejects an
+insufficient cache. Combining `REQUIRE=1` with `DISABLE=1` fails on an eligible
+grouped-MM candidate, while short tail chunks retain their normal fallback. The
+IQ2 live cache index remains automatic for its production shape, selected-load
+early commit remains off unless explicitly enabled, and grouped-MM statistics
+plus streaming timing summaries remain opt-in diagnostics. The grouped prefill
+loader also skips `F_RDADVISE` for chunks of at least 32 tokens because it
+immediately reads the same expert ranges with parallel `pread`; short chunks
+retain the hint. Set
+`DS4_METAL_ENABLE_STREAMING_PREFILL_EXPERT_READAHEAD=1` to restore the old
+hint-plus-read sequence for cold-storage A/B tests.
+
### Practical SSD streaming examples
On 64GB MacBooks, start with the 2-bit Flash GGUF and a moderate expert cache:
diff --git a/STRIXHALO.md b/STRIXHALO.md
index 611239b7f5..f5f7b5a8f4 100644
--- a/STRIXHALO.md
+++ b/STRIXHALO.md
@@ -18,7 +18,7 @@ sudo apt-get update
sudo apt-get install -y \
hipcc rocminfo rocm-smi \
libamdhip64-dev \
- libhipblas-dev libhipblaslt-dev \
+ libhipblas-dev \
librocblas-dev \
librocwmma-dev \
libhipcub-dev
diff --git a/cuda/mmq/ds4_ggml_stubs.cu b/cuda/mmq/ds4_ggml_stubs.cu
index 4e88c08f92..23224b6170 100644
--- a/cuda/mmq/ds4_ggml_stubs.cu
+++ b/cuda/mmq/ds4_ggml_stubs.cu
@@ -7,6 +7,7 @@
// CUDA uses stream-ordered allocation. HIP retains stream-local allocations
// because returning live MMQ scratch to its asynchronous pool is unreliable.
+#include "ds4_mmq.h"
#include "common.cuh" // pulls in ds4_ggml_stubs.h via redirect headers
#if defined(GGML_USE_HIP)
@@ -23,6 +24,20 @@
#include
#include
+/* Standalone MMQ tests do not link ds4_cuda.cu. Full ds4 links its strong,
+ * stream-aware registry implementation over this fail-closed weak miss. */
+#if defined(__GNUC__)
+extern "C" __attribute__((weak)) int ds4_cuda_q8_fold_take_q81(
+ const void *src, uint64_t in_dim, cudaStream_t stream,
+ const void **q81) {
+ (void)src;
+ (void)in_dim;
+ (void)stream;
+ if (q81) *q81 = nullptr;
+ return 0;
+}
+#endif
+
// ----------------------------------------------------------------------------
// Device info singleton.
//
@@ -133,10 +148,6 @@ extern "C" void ds4_pool_set_stream(cudaStream_t stream) {
t_ds4_pool_stream = stream;
}
-extern "C" cudaStream_t ds4_pool_get_stream(void) {
- return t_ds4_pool_stream;
-}
-
namespace {
struct ds4_naive_pool : public ggml_cuda_pool {
diff --git a/cuda/mmq/ds4_mmq.cu b/cuda/mmq/ds4_mmq.cu
index 36c3104419..90838bf16f 100644
--- a/cuda/mmq/ds4_mmq.cu
+++ b/cuda/mmq/ds4_mmq.cu
@@ -25,11 +25,15 @@
#include "quantize.cuh"
#include "mmid.cuh"
#include "ds4_mmq_d2r.cuh"
+#if !defined(GGML_USE_HIP)
+#include "ds4_mmq_q4_16warp.cuh"
+#endif
+#include
#include
#include
#include
-#include
+#include
#if defined(__has_include)
#if __has_include()
@@ -100,25 +104,38 @@ private:
// Init
// ----------------------------------------------------------------------------
-// Step 7 task #29: experimental persistent Q8_1 scratch buffer.
-//
-// Hypothesis: ggml_cuda_pool_alloc inside ds4_mmq_moe_vec_impl records a
-// cudaMallocAsync graph node into the captured layer graph. At replay
-// time the alloc node returns a (potentially different) address, but the
-// matvec kernel's pointer argument was baked in at capture time. Result:
-// the matvec reads stale/wrong memory and produces a different output
-// than eager execution, even with identical inputs.
-//
-// Mitigation under test: pre-allocate a persistent device buffer at
-// startup via plain cudaMalloc (NOT cudaMallocAsync, NOT inside any
-// capture). When the env flag DS4_CUDA_MMQ_Q81_PERSISTENT=1 is set,
-// ds4_mmq_moe_vec_impl uses this persistent buffer instead of pool_alloc.
-//
-// Sized for V4 Flash decode shapes: gate Q8_1 ~8 KB, down Q8_1 ~14 KB.
-// 256 KB allocation gives generous headroom for short prefill batches.
+// Experimental persistent Q8_1 scratch. The grouped raw prefill path below
+// aliases its input and down-Q8 staging in this arena: both ranges have the
+// same layout but disjoint lifetimes on the default stream. The feature stays
+// opt-in because a process-global address is only safe for the single-owner
+// GB10 dispatch covered by q81_grouped_persistent_acquire().
static void *g_q81_scratch_ptr = nullptr;
static size_t g_q81_scratch_bytes = 0;
-static bool g_q81_scratch_enabled = false;
+// A failed resize retirement can leave both allocations live. Keep the
+// unpublished replacement owned here so cleanup/reinit can retry its free.
+static void *g_q81_unpublished_replacement_ptr = nullptr;
+// Older vector wrappers still contain a generic persistent branch. Keep that
+// branch disabled: unlike grouped fused_raw it has no default-stream lease or
+// capture exclusion and therefore cannot safely share the owned arena.
+static constexpr bool g_q81_scratch_enabled = false;
+static bool g_q81_grouped_enabled = false;
+static bool g_q81_scratch_poisoned = false;
+static int g_q81_scratch_device = -1;
+static std::mutex g_q81_state_mutex; // Process-global state, not per-tensor.
+
+static uint64_t g_q81_grouped_candidates;
+static uint64_t g_q81_grouped_uses;
+static uint64_t g_q81_grouped_hits;
+static uint64_t g_q81_grouped_pool_fallbacks;
+static uint64_t g_q81_grouped_allocations;
+static uint64_t g_q81_grouped_resizes;
+static uint64_t g_q81_grouped_owner_rejects;
+static uint64_t g_q81_grouped_stream_rejects;
+static uint64_t g_q81_grouped_capture_rejects;
+static uint64_t g_q81_grouped_device_rejects;
+static uint64_t g_q81_grouped_size_rejects;
+static size_t g_q81_grouped_high_water;
+
static void *g_aligned_q81_scratch_ptr = nullptr;
static size_t g_aligned_q81_scratch_bytes = 0;
static int g_aligned_q81_scratch_device = -1;
@@ -140,6 +157,171 @@ struct mmq_pair_map_scratch {
static mmq_pair_map_scratch g_mmq_pair_maps[GGML_CUDA_MAX_DEVICES] = {};
+// Backend init/teardown owns transitions, but dispatch admission reads this
+// flag without taking the Q8_1 arena mutex. Keep those reads race-free while
+// retaining the mutex below for arena ownership and cleanup serialization.
+static std::atomic g_gb10_optimizations{false};
+
+static bool gb10_optimizations_enabled() {
+ return g_gb10_optimizations.load(std::memory_order_relaxed);
+}
+
+static constexpr size_t DS4_MMQ_Q81_ARENA_MIN_BYTES = 4u * 1024u * 1024u;
+
+enum q81_arena_result {
+ Q81_ARENA_REJECTED = 0,
+ Q81_ARENA_HIT,
+ Q81_ARENA_ALLOCATED,
+ Q81_ARENA_RESIZED,
+};
+
+static bool q81_persistent_requested() {
+ const char *value = getenv("DS4_CUDA_MMQ_Q81_PERSISTENT");
+ if (!value || value[0] == '\0' || strcmp(value, "0") == 0 ||
+ strcmp(value, "off") == 0 || strcmp(value, "OFF") == 0 ||
+ strcmp(value, "false") == 0 || strcmp(value, "FALSE") == 0 ||
+ strcmp(value, "no") == 0 || strcmp(value, "NO") == 0) {
+ return false;
+ }
+ return strcmp(value, "1") == 0 ||
+ strcmp(value, "on") == 0 || strcmp(value, "ON") == 0 ||
+ strcmp(value, "true") == 0 || strcmp(value, "TRUE") == 0 ||
+ strcmp(value, "yes") == 0 || strcmp(value, "YES") == 0;
+}
+
+static bool q81_is_gb10_owner(int device) {
+ if (!gb10_optimizations_enabled() || device < 0 ||
+ device >= ggml_cuda_info().device_count) {
+ return false;
+ }
+ const auto &info = ggml_cuda_info().devices[device];
+ return info.integrated && info.cc == GGML_CUDA_CC_DGX_SPARK;
+}
+
+static q81_arena_result q81_arena_ensure_locked(int device, size_t required) {
+ if (g_q81_scratch_poisoned || required > SIZE_MAX - 255u ||
+ (g_q81_scratch_ptr && g_q81_scratch_device != device)) {
+ return Q81_ARENA_REJECTED;
+ }
+ if (g_q81_scratch_ptr && required <= g_q81_scratch_bytes) {
+ g_q81_grouped_enabled = true;
+ return Q81_ARENA_HIT;
+ }
+
+ const size_t aligned = (required + 255u) & ~(size_t)255u;
+ const size_t bytes = aligned > DS4_MMQ_Q81_ARENA_MIN_BYTES
+ ? aligned : DS4_MMQ_Q81_ARENA_MIN_BYTES;
+ void *replacement = nullptr;
+ cudaError_t err = cudaMalloc(&replacement, bytes);
+ if (err != cudaSuccess || !replacement) {
+ fprintf(stderr,
+ "ds4_mmq: cudaMalloc(persistent Q8_1 arena %zu B) failed: %s; "
+ "using stream pool\n",
+ bytes, cudaGetErrorString(err));
+ (void)cudaGetLastError();
+ return Q81_ARENA_REJECTED;
+ }
+
+ if (g_q81_scratch_ptr) {
+ /* The lease excludes another host submission and the persistent path
+ * only accepts the legacy default stream. Drain the device before
+ * retiring the old address: allocation succeeds before any state is
+ * changed, so OOM leaves the previous arena usable. A drain/free
+ * failure is different -- pointer liveness is ambiguous and the
+ * feature stays poisoned until explicit cleanup. */
+ err = cudaDeviceSynchronize();
+ if (err == cudaSuccess) {
+ err = cudaFree(g_q81_scratch_ptr);
+ }
+ if (err != cudaSuccess) {
+ fprintf(stderr,
+ "ds4_mmq: persistent Q8_1 arena resize from %zu B to "
+ "%zu B failed while retiring the old arena: %s; "
+ "persistent reuse poisoned\n",
+ g_q81_scratch_bytes, bytes, cudaGetErrorString(err));
+ (void)cudaGetLastError();
+ const cudaError_t replacement_free_err = cudaFree(replacement);
+ if (replacement_free_err != cudaSuccess) {
+ fprintf(stderr,
+ "ds4_mmq: freeing unpublished Q8_1 replacement "
+ "failed: %s\n",
+ cudaGetErrorString(replacement_free_err));
+ (void)cudaGetLastError();
+ g_q81_unpublished_replacement_ptr = replacement;
+ }
+ g_q81_grouped_enabled = false;
+ g_q81_scratch_poisoned = true;
+ return Q81_ARENA_REJECTED;
+ }
+ }
+
+ const bool resized = g_q81_scratch_ptr != nullptr;
+ g_q81_scratch_ptr = replacement;
+ g_q81_scratch_bytes = bytes;
+ g_q81_scratch_device = device;
+ g_q81_grouped_enabled = true;
+ g_q81_grouped_allocations++;
+ if (resized) g_q81_grouped_resizes++;
+ fprintf(stderr,
+ "ds4_mmq: persistent Q8_1 arena %s (%zu B at %p, device %d)\n",
+ resized ? "resized" : "enabled", bytes,
+ g_q81_scratch_ptr, device);
+ return resized ? Q81_ARENA_RESIZED : Q81_ARENA_ALLOCATED;
+}
+
+// On success, lease remains locked until the complete host dispatch has been
+// submitted. A following dispatch therefore cannot interleave its writes;
+// default-stream ordering protects the device-side lifetime after unlock.
+static char *q81_grouped_persistent_acquire(
+ int device, cudaStream_t stream, size_t required,
+ std::unique_lock *lease) {
+ if (!lease || !q81_persistent_requested()) return nullptr;
+ lease->lock();
+ g_q81_grouped_candidates++;
+ if (required > g_q81_grouped_high_water) {
+ g_q81_grouped_high_water = required;
+ }
+ if (!q81_is_gb10_owner(device)) {
+ g_q81_grouped_device_rejects++;
+ } else if (stream != (cudaStream_t)0) {
+ g_q81_grouped_stream_rejects++;
+ } else {
+ int active_device = -1;
+ const cudaError_t device_err = cudaGetDevice(&active_device);
+ if (device_err != cudaSuccess || active_device != device ||
+ (g_q81_scratch_device >= 0 &&
+ g_q81_scratch_device != device)) {
+ (void)cudaGetLastError();
+ g_q81_grouped_owner_rejects++;
+ } else {
+ cudaStreamCaptureStatus capture = cudaStreamCaptureStatusNone;
+ const cudaError_t capture_err =
+ cudaStreamIsCapturing(stream, &capture);
+ if (capture_err != cudaSuccess ||
+ capture != cudaStreamCaptureStatusNone) {
+ (void)cudaGetLastError();
+ g_q81_grouped_capture_rejects++;
+ } else {
+ const q81_arena_result arena =
+ q81_arena_ensure_locked(device, required);
+ if (arena != Q81_ARENA_REJECTED &&
+ g_q81_grouped_enabled && !g_q81_scratch_poisoned &&
+ required <= g_q81_scratch_bytes) {
+ g_q81_grouped_uses++;
+ if (arena == Q81_ARENA_HIT) g_q81_grouped_hits++;
+ return (char *)g_q81_scratch_ptr;
+ }
+ if (g_q81_scratch_ptr && required > g_q81_scratch_bytes) {
+ g_q81_grouped_size_rejects++;
+ }
+ }
+ }
+ }
+ g_q81_grouped_pool_fallbacks++;
+ lease->unlock();
+ return nullptr;
+}
+
extern "C" void ds4_mmq_set_aligned_q81_scratch(void *ptr, size_t bytes) {
g_aligned_q81_scratch_ptr = ptr;
g_aligned_q81_scratch_bytes = ptr ? bytes : 0;
@@ -154,30 +336,204 @@ static void *ds4_mmq_aligned_q81_scratch(int device, size_t bytes) {
? g_aligned_q81_scratch_ptr : nullptr;
}
-// Read by ds4_mmq_moe_vec_impl; non-zero means use the persistent buffer.
-// Set by ds4_mmq_init once based on env. (Single-threaded GPU work; no
-// atomicity needed.)
-extern "C" int ds4_mmq_q81_persistent_enabled(void) {
- return g_q81_scratch_enabled ? 1 : 0;
+/* Test-only preflight hook. It deliberately traverses the production
+ * acquire path (including owner/default-stream/capture checks and resize
+ * retirement) without enqueueing a synthetic large MMQ fixture. */
+extern "C" int ds4_mmq_q81_persistent_preflight_for_test(
+ int device, size_t required) {
+ int previous = -1;
+ if (cudaGetDevice(&previous) != cudaSuccess ||
+ cudaSetDevice(device) != cudaSuccess) {
+ (void)cudaGetLastError();
+ return -1;
+ }
+ char *arena = nullptr;
+ {
+ std::unique_lock lease(
+ g_q81_state_mutex, std::defer_lock);
+ arena = q81_grouped_persistent_acquire(
+ device, (cudaStream_t)0, required, &lease);
+ }
+ const cudaError_t restore_err = previous != device
+ ? cudaSetDevice(previous) : cudaSuccess;
+ if (restore_err != cudaSuccess) {
+ (void)cudaGetLastError();
+ return -2;
+ }
+ return arena ? 0 : -3;
+}
+
+static uint64_t g_q8_fold_oracle_byte_calls;
+static uint64_t g_q8_fold_oracle_byte_mismatches;
+static uint64_t g_q8_fold_oracle_output_calls;
+static uint64_t g_q8_fold_oracle_output_mismatches;
+static uint64_t g_q8_fold_oracle_raw_moe_calls;
+static uint64_t g_q8_fold_oracle_aligned_q8_calls;
+static uint64_t g_q8_fold_oracle_aligned_iq2_calls;
+static uint64_t g_q8_fold_oracle_skips;
+static int g_q8_fold_oracle_report_registered;
+
+static cudaError_t ds4_mmq_q8_fold_oracle_free(
+ void *ptr, const char *label, cudaError_t prior_err) {
+ if (!ptr) return prior_err;
+ const cudaError_t free_err = cudaFree(ptr);
+ if (free_err != cudaSuccess) {
+ fprintf(stderr,
+ "ds4: CUDA Q8_1 fold oracle cudaFree(%s) failed: %s\n",
+ label, cudaGetErrorString(free_err));
+ if (prior_err == cudaSuccess) return free_err;
+ }
+ return prior_err;
+}
+
+static void ds4_mmq_q8_fold_oracle_report(void) {
+ fprintf(stderr,
+ "ds4: CUDA Q8_1 fold oracle: byte_calls=%llu "
+ "byte_mismatches=%llu output_calls=%llu "
+ "output_mismatches=%llu raw_moe_calls=%llu "
+ "aligned_q8_calls=%llu aligned_iq2_calls=%llu skips=%llu "
+ "(canonical reference retained)\n",
+ (unsigned long long)g_q8_fold_oracle_byte_calls,
+ (unsigned long long)g_q8_fold_oracle_byte_mismatches,
+ (unsigned long long)g_q8_fold_oracle_output_calls,
+ (unsigned long long)g_q8_fold_oracle_output_mismatches,
+ (unsigned long long)g_q8_fold_oracle_raw_moe_calls,
+ (unsigned long long)g_q8_fold_oracle_aligned_q8_calls,
+ (unsigned long long)g_q8_fold_oracle_aligned_iq2_calls,
+ (unsigned long long)g_q8_fold_oracle_skips);
+}
+
+static bool ds4_mmq_q8_fold_oracle_enabled() {
+ const char *env = getenv("DS4_CUDA_Q8_FOLD_ORACLE");
+ const bool enabled = env && strcmp(env, "1") == 0;
+ if (enabled && !g_q8_fold_oracle_report_registered) {
+ g_q8_fold_oracle_report_registered = 1;
+ (void)atexit(ds4_mmq_q8_fold_oracle_report);
+ }
+ return enabled;
+}
+
+__global__ static void q8_fold_output_compare_kernel(
+ uint32_t *mismatch, const float *candidate,
+ const float *reference, uint64_t n) {
+ const uint64_t i = (uint64_t)blockIdx.x * blockDim.x + threadIdx.x;
+ if (i < n && __float_as_uint(candidate[i]) !=
+ __float_as_uint(reference[i])) {
+ atomicExch(mismatch, 1u);
+ }
}
-extern "C" void *ds4_mmq_q81_scratch_ptr(void) {
- return g_q81_scratch_ptr;
+/* Byte oracle for every consumer. On mismatch the fresh canonical bytes
+ * overwrite the sidecar before it is consumed. Any setup/capture failure
+ * rejects the fold entirely so the established prelude quantizes again. */
+static bool ds4_mmq_q8_fold_oracle_bytes(
+ const float *X_f32, int64_t K, int64_t ne10_padded,
+ char *folded, cudaStream_t stream) {
+ if (!ds4_mmq_q8_fold_oracle_enabled()) return true;
+ if (!X_f32 || !folded || K <= 0 || ne10_padded != K ||
+ (K % QK8_1) != 0) {
+ g_q8_fold_oracle_skips++;
+ return false;
+ }
+ cudaStreamCaptureStatus capture = cudaStreamCaptureStatusNone;
+ const cudaError_t capture_err = cudaStreamIsCapturing(stream, &capture);
+ if (capture_err != cudaSuccess) {
+ fprintf(stderr,
+ "ds4_mmq: Q8 fold oracle stream-capture query failed: %s\n",
+ cudaGetErrorString(capture_err));
+ (void)cudaGetLastError();
+ g_q8_fold_oracle_skips++;
+ return false;
+ }
+ if (capture != cudaStreamCaptureStatusNone) {
+ fprintf(stderr,
+ "ds4_mmq: Q8 fold oracle skipped during stream capture\n");
+ g_q8_fold_oracle_skips++;
+ return false;
+ }
+ const size_t bytes = (size_t)ne10_padded * sizeof(block_q8_1) / QK8_1;
+ if (bytes == 0u || bytes > 16384u) {
+ g_q8_fold_oracle_skips++;
+ return false;
+ }
+ char *fresh = nullptr;
+ char *host = (char *)malloc(bytes * 2u);
+ if (!host) {
+ fprintf(stderr,
+ "ds4_mmq: Q8 fold oracle host allocation (%zu B) failed\n",
+ bytes * 2u);
+ g_q8_fold_oracle_skips++;
+ return false;
+ }
+ const cudaError_t fresh_alloc_err = cudaMalloc((void **)&fresh, bytes);
+ if (fresh_alloc_err != cudaSuccess || !fresh) {
+ fprintf(stderr,
+ "ds4_mmq: Q8 fold oracle device allocation (%zu B) failed: "
+ "%s%s\n",
+ bytes, cudaGetErrorString(fresh_alloc_err),
+ fresh_alloc_err == cudaSuccess ? " (null pointer)" : "");
+ free(host);
+ (void)cudaGetLastError();
+ g_q8_fold_oracle_skips++;
+ return false;
+ }
+ quantize_row_q8_1_cuda(
+ X_f32, /*ids=*/nullptr, fresh, GGML_TYPE_Q8_0,
+ /*ne00=*/K, /*s11=*/K, /*s12=*/K, /*s13=*/K,
+ /*ne0=*/ne10_padded, /*ne1=*/1, /*ne2=*/1, /*ne3=*/1,
+ stream);
+ bool setup_ok = cudaGetLastError() == cudaSuccess &&
+ cudaStreamSynchronize(stream) == cudaSuccess &&
+ cudaMemcpy(host, folded, bytes,
+ cudaMemcpyDeviceToHost) == cudaSuccess &&
+ cudaMemcpy(host + bytes, fresh, bytes,
+ cudaMemcpyDeviceToHost) == cudaSuccess;
+ if (!setup_ok) {
+ (void)cudaGetLastError();
+ cudaError_t cleanup_err = ds4_mmq_q8_fold_oracle_free(
+ fresh, "byte-fresh", cudaSuccess);
+ if (cleanup_err != cudaSuccess) (void)cudaGetLastError();
+ free(host);
+ g_q8_fold_oracle_skips++;
+ return false;
+ }
+ const bool match = memcmp(host, host + bytes, bytes) == 0;
+ g_q8_fold_oracle_byte_calls++;
+ if (!match) {
+ g_q8_fold_oracle_byte_mismatches++;
+ if (cudaMemcpyAsync(folded, fresh, bytes,
+ cudaMemcpyDeviceToDevice, stream) != cudaSuccess ||
+ cudaStreamSynchronize(stream) != cudaSuccess) {
+ (void)cudaGetLastError();
+ cudaError_t cleanup_err = ds4_mmq_q8_fold_oracle_free(
+ fresh, "byte-fresh", cudaSuccess);
+ if (cleanup_err != cudaSuccess) (void)cudaGetLastError();
+ free(host);
+ g_q8_fold_oracle_skips++;
+ return false;
+ }
+ }
+ cudaError_t cleanup_err = ds4_mmq_q8_fold_oracle_free(
+ fresh, "byte-fresh", cudaSuccess);
+ free(host);
+ if (cleanup_err != cudaSuccess) {
+ (void)cudaGetLastError();
+ g_q8_fold_oracle_skips++;
+ return false;
+ }
+ return true;
}
-// M2-Inc2a: registry of producer-emitted q8_1 activations (ds4_cuda.cu).
-// A hit returns canonical block_q8_1 codes for this exact activation
-// pointer (bit-exact vs quantize_row_q8_1_cuda), letting the caller skip
-// its quantize prelude. Only valid for single-token unpadded rows
-// (ne10_padded == K); the registry itself guarantees freshness (slots are
-// reset by the producing entry every layer and pops are one-shot).
-extern "C" int ds4_cuda_q8_fold_take_q81(const void *src, uint64_t in_dim,
- const void **q81);
static char *ds4_mmq_folded_q81(const float *X_f32, int64_t K, int n_tokens,
- int64_t ne10_padded) {
+ int64_t ne10_padded, cudaStream_t stream) {
if (n_tokens != 1 || ne10_padded != K) return nullptr;
const void *p = nullptr;
- if (!ds4_cuda_q8_fold_take_q81((const void *)X_f32, (uint64_t)K, &p)) return nullptr;
+ if (!ds4_cuda_q8_fold_take_q81(
+ (const void *)X_f32, (uint64_t)K, stream, &p)) return nullptr;
+ if (!ds4_mmq_q8_fold_oracle_bytes(
+ X_f32, K, ne10_padded, (char *)(uintptr_t)p, stream)) {
+ return nullptr;
+ }
static int logged = 0;
if (!logged) {
logged = 1;
@@ -308,10 +664,6 @@ static int64_t d2r_min_cols() {
return cached;
}
-extern "C" size_t ds4_mmq_q81_scratch_bytes(void) {
- return g_q81_scratch_bytes;
-}
-
extern "C" int ds4_mmq_init(int device) {
if (device < 0) {
fprintf(stderr, "ds4_mmq_init: invalid device %d\n", device);
@@ -349,29 +701,128 @@ extern "C" int ds4_mmq_init(int device) {
maps.expert_bounds = base + 2u * MMQ_GFX1151_PAIR_MAP_ROWS;
}
- // Step 7 task #29: pre-allocate persistent Q8_1 scratch if enabled.
- // Must happen here (before any layer-graph capture) so the cudaMalloc
- // is not forbidden by capture-mode restrictions, and so the kernel
- // pointer arg baked into the captured graph stays valid at replay.
- if (getenv("DS4_CUDA_MMQ_Q81_PERSISTENT") && !g_q81_scratch_ptr) {
- const size_t bytes = 256 * 1024;
- cudaError_t err = cudaMalloc(&g_q81_scratch_ptr, bytes);
- if (err != cudaSuccess) {
- fprintf(stderr, "ds4_mmq_init: cudaMalloc(q81_scratch %zu B) failed: %s; "
- "falling back to pool_alloc\n",
- bytes, cudaGetErrorString(err));
- g_q81_scratch_ptr = nullptr;
- g_q81_scratch_enabled = false;
- } else {
- g_q81_scratch_bytes = bytes;
- g_q81_scratch_enabled = true;
- fprintf(stderr, "ds4_mmq_init: persistent Q8_1 scratch enabled (%zu B at %p)\n",
- bytes, g_q81_scratch_ptr);
+ // Allocation is intentionally lazy. The first eligible grouped dispatch
+ // knows its exact maximum input/down staging requirement and resolves the
+ // arena during preflight, before it submits any device operation.
+ {
+ std::lock_guard lock(g_q81_state_mutex);
+ const bool requested = q81_persistent_requested();
+ g_q81_grouped_enabled = requested && q81_is_gb10_owner(device) &&
+ g_q81_scratch_ptr && !g_q81_scratch_poisoned &&
+ g_q81_scratch_device == device;
+ }
+ return 0;
+}
+
+extern "C" int ds4_mmq_q81_persistent_cleanup(void) {
+ std::lock_guard lock(g_q81_state_mutex);
+ g_q81_grouped_enabled = false;
+ if (!g_q81_scratch_ptr && !g_q81_unpublished_replacement_ptr) {
+ g_q81_scratch_bytes = 0;
+ g_q81_scratch_device = -1;
+ g_q81_scratch_poisoned = false;
+ return 0;
+ }
+
+ int previous = -1;
+ if (cudaGetDevice(&previous) != cudaSuccess ||
+ g_q81_scratch_device < 0 ||
+ cudaSetDevice(g_q81_scratch_device) != cudaSuccess) {
+ (void)cudaGetLastError();
+ g_q81_scratch_poisoned = true;
+ return -1;
+ }
+ cudaError_t sync_err = cudaDeviceSynchronize();
+ cudaError_t arena_free_err = cudaSuccess;
+ cudaError_t replacement_free_err = cudaSuccess;
+ if (sync_err == cudaSuccess) {
+ if (g_q81_scratch_ptr) {
+ arena_free_err = cudaFree(g_q81_scratch_ptr);
+ if (arena_free_err == cudaSuccess) {
+ g_q81_scratch_ptr = nullptr;
+ g_q81_scratch_bytes = 0;
+ } else {
+ (void)cudaGetLastError();
+ }
}
+ if (g_q81_unpublished_replacement_ptr) {
+ replacement_free_err = cudaFree(
+ g_q81_unpublished_replacement_ptr);
+ if (replacement_free_err == cudaSuccess) {
+ g_q81_unpublished_replacement_ptr = nullptr;
+ } else {
+ (void)cudaGetLastError();
+ }
+ }
+ } else {
+ (void)cudaGetLastError();
+ }
+ const cudaError_t restore_err = previous != g_q81_scratch_device
+ ? cudaSetDevice(previous) : cudaSuccess;
+ if (sync_err != cudaSuccess || arena_free_err != cudaSuccess ||
+ replacement_free_err != cudaSuccess) {
+ fprintf(stderr,
+ "ds4_mmq: persistent Q8_1 arena cleanup failed: "
+ "sync=%s arena_free=%s replacement_free=%s\n",
+ cudaGetErrorString(sync_err),
+ cudaGetErrorString(arena_free_err),
+ cudaGetErrorString(replacement_free_err));
+ g_q81_scratch_poisoned = true;
+ return -1;
+ }
+ // Both owned allocations are now retired; only now may reinit clear the
+ // poison and admit a new lazy allocation.
+ g_q81_scratch_device = -1;
+ g_q81_scratch_poisoned = false;
+ if (restore_err != cudaSuccess) {
+ fprintf(stderr,
+ "ds4_mmq: persistent Q8_1 arena freed, but restoring CUDA "
+ "device %d failed: %s\n",
+ previous, cudaGetErrorString(restore_err));
+ (void)cudaGetLastError();
+ return -2;
}
return 0;
}
+extern "C" void ds4_mmq_q81_persistent_counters(
+ uint64_t *candidates, uint64_t *uses, uint64_t *hits,
+ uint64_t *pool_fallbacks, uint64_t *allocations, uint64_t *resizes,
+ size_t *arena_bytes, size_t *high_water) {
+ std::lock_guard lock(g_q81_state_mutex);
+ if (candidates) *candidates = g_q81_grouped_candidates;
+ if (uses) *uses = g_q81_grouped_uses;
+ if (hits) *hits = g_q81_grouped_hits;
+ if (pool_fallbacks) *pool_fallbacks = g_q81_grouped_pool_fallbacks;
+ if (allocations) *allocations = g_q81_grouped_allocations;
+ if (resizes) *resizes = g_q81_grouped_resizes;
+ if (arena_bytes) *arena_bytes = g_q81_scratch_bytes;
+ if (high_water) *high_water = g_q81_grouped_high_water;
+}
+
+extern "C" void ds4_mmq_q81_persistent_report(void) {
+ std::lock_guard lock(g_q81_state_mutex);
+ fprintf(stderr,
+ "ds4: CUDA MMQ grouped Q8_1 persistent: candidates=%llu "
+ "uses=%llu hits=%llu pool_fallbacks=%llu allocations=%llu "
+ "resizes=%llu "
+ "arena=%zu high_water=%zu rejects(device/owner/stream/capture/size)="
+ "%llu/%llu/%llu/%llu/%llu poisoned=%d\n",
+ (unsigned long long)g_q81_grouped_candidates,
+ (unsigned long long)g_q81_grouped_uses,
+ (unsigned long long)g_q81_grouped_hits,
+ (unsigned long long)g_q81_grouped_pool_fallbacks,
+ (unsigned long long)g_q81_grouped_allocations,
+ (unsigned long long)g_q81_grouped_resizes,
+ g_q81_scratch_bytes, g_q81_grouped_high_water,
+ (unsigned long long)g_q81_grouped_device_rejects,
+ (unsigned long long)g_q81_grouped_owner_rejects,
+ (unsigned long long)g_q81_grouped_stream_rejects,
+ (unsigned long long)g_q81_grouped_capture_rejects,
+ (unsigned long long)g_q81_grouped_size_rejects,
+ g_q81_scratch_poisoned ? 1 : 0);
+}
+
// ----------------------------------------------------------------------------
// Gating: when should the caller choose mmq over dequant+cublas?
//
@@ -513,6 +964,323 @@ bool ds4_mmq_k_tile_supported(const char *tag, int K, int cc) {
return true;
}
+#if !defined(GGML_USE_HIP)
+static bool ds4_q4_test_q8_1_layout(
+ int N, int K, size_t *payload_bytes, size_t *total_bytes) {
+ if (N <= 0 || K <= 0 || (K % QK_K) != 0) return false;
+ const int64_t padded_k = GGML_PAD((int64_t)K, MATRIX_ROW_PADDING);
+ const size_t blocks_per_column =
+ (size_t)padded_k / (4u * (size_t)QK8_1);
+ if ((size_t)N > SIZE_MAX / blocks_per_column) return false;
+ const size_t blocks = (size_t)N * blocks_per_column;
+ if (blocks > SIZE_MAX / sizeof(block_q8_1_mmq)) return false;
+ const size_t payload = blocks * sizeof(block_q8_1_mmq);
+ const size_t slack = 128u * sizeof(block_q8_1_mmq);
+ if (payload > SIZE_MAX - slack) return false;
+ if (payload_bytes) *payload_bytes = payload;
+ if (total_bytes) *total_bytes = payload + slack;
+ return true;
+}
+
+/* The candidate and its caller-owned fixup buffer model canonical m128n128.
+ * Confirm the real canonical picker chooses that tile: a width limit alone is
+ * insufficient because resource constraints or a ceil-division plateau can
+ * retain a narrower width and change both partitioning and scratch size. */
+static bool ds4_q4_test_reference_uses_m128n128(
+ int device, int cc, int N) {
+ if (device < 0 || device >= GGML_CUDA_MAX_DEVICES || N <= 0 ||
+ get_mmq_y_host(cc) != 128) {
+ return false;
+ }
+ const size_t smpbo = ggml_cuda_info().devices[device].smpbo;
+ const int warp_size = ggml_cuda_info().devices[device].warp_size;
+ const int nwarps = mmq_get_nwarps_host(cc, warp_size);
+ const int mmq_x_max = get_mmq_x_max_host(cc);
+ int mmq_x_best = 0;
+ int64_t ntiles_x_best = INT64_MAX;
+ for (int mmq_x = 8;
+ mmq_x <= mmq_x_max && ntiles_x_best > 1;
+ mmq_x += 8) {
+ const int granularity = mmq_get_granularity_host(mmq_x, cc);
+ if (mmq_x % granularity != 0 ||
+ mmq_get_nbytes_shared(
+ mmq_x, 128, cc, warp_size, nwarps) > smpbo) {
+ continue;
+ }
+ const int64_t ntiles_x =
+ ((int64_t)N + mmq_x - 1) / mmq_x;
+ if (ntiles_x < ntiles_x_best) {
+ mmq_x_best = mmq_x;
+ ntiles_x_best = ntiles_x;
+ }
+ }
+ return mmq_x_best == 128;
+}
+
+extern "C" int
+ds4_mmq_q4_K_dense_preq_reference_m128n128_for_test(int N) {
+ const int dev = ggml_cuda_get_device();
+ if (dev < 0 || dev >= GGML_CUDA_MAX_DEVICES) return 0;
+ return ds4_q4_test_reference_uses_m128n128(
+ dev, ggml_cuda_info().devices[dev].cc, N) ? 1 : 0;
+}
+
+extern "C" size_t ds4_mmq_q4_K_q8_1_scratch_bytes(int N, int K) {
+ size_t total = 0;
+ return ds4_q4_test_q8_1_layout(N, K, nullptr, &total) ? total : 0;
+}
+
+extern "C" int ds4_mmq_q4_K_quantize_q8_1_for_test(
+ const float *X_f32, void *q8_ds4, size_t q8_bytes,
+ int N, int K, cudaStream_t stream) {
+ size_t total = 0;
+ if (!X_f32 || !q8_ds4 ||
+ !ds4_q4_test_q8_1_layout(N, K, nullptr, &total) ||
+ q8_bytes < total) {
+ return -1;
+ }
+ cudaError_t err = cudaMemsetAsync(q8_ds4, 0, total, stream);
+ if (err != cudaSuccess) return -2;
+ quantize_mmq_q8_1_cuda(
+ X_f32, /*ids=*/nullptr, q8_ds4, GGML_TYPE_Q4_K,
+ /*ne00=*/K, /*s11=*/(int64_t)K, /*s12=*/0, /*s13=*/0,
+ /*ne0=*/GGML_PAD((int64_t)K, MATRIX_ROW_PADDING),
+ /*ne1=*/N, /*ne2=*/1, /*ne3=*/1, stream);
+ err = cudaGetLastError();
+ return err == cudaSuccess ? 0 : -3;
+}
+
+extern "C" int ds4_mmq_q4_K_dense_preq_reference_for_test(
+ const void *W_q4_K, const void *q8_ds4, size_t q8_bytes,
+ float *out_f32, int M, int N, int K, int use_stream_k,
+ void *stream_k_fixup, size_t stream_k_fixup_bytes,
+ cudaStream_t stream) {
+ size_t payload = 0, total = 0;
+ if (!W_q4_K || !q8_ds4 || !out_f32 || M <= 0 ||
+ !ds4_q4_test_q8_1_layout(N, K, &payload, &total) ||
+ q8_bytes < total) {
+ return -1;
+ }
+ const int dev = ggml_cuda_get_device();
+ if (dev < 0 || dev >= GGML_CUDA_MAX_DEVICES) return -1;
+ const int cc = ggml_cuda_info().devices[dev].cc;
+ if (!ds4_mmq_k_tile_supported(
+ "ds4_mmq_q4_K_dense_preq_reference_for_test", K, cc)) {
+ return -1;
+ }
+ ggml_backend_cuda_context *ctx = get_ctx_for_device(dev);
+ if (!ctx) return -1;
+ if ((stream_k_fixup == nullptr && stream_k_fixup_bytes != 0u) ||
+ (stream_k_fixup != nullptr &&
+ ((uintptr_t)stream_k_fixup % alignof(float)) != 0) ||
+ (stream_k_fixup_bytes % sizeof(float)) != 0u) {
+ return -1;
+ }
+ if (stream_k_fixup != nullptr) {
+ if (!use_stream_k) return -1;
+ if (!ds4_q4_test_reference_uses_m128n128(dev, cc, N)) {
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ const size_t required =
+ ds4_mmq_q4_K_dense_16warp_streamk_scratch_bytes(
+ M, N, ggml_cuda_info().devices[dev].nsm);
+ if (required > stream_k_fixup_bytes) return -1;
+ }
+ ds4_pool_set_stream(stream);
+ const int64_t stride_row_x = (int64_t)K / QK_K;
+ const int64_t stride_y = (int64_t)(payload / sizeof(int));
+ const mmq_args args = {
+ /*x=*/(const char *)W_q4_K,
+ /*type_x=*/GGML_TYPE_Q4_K,
+ /*y=*/(const int *)q8_ds4,
+ /*ids_dst=*/nullptr,
+ /*expert_bounds=*/nullptr,
+ /*dst=*/out_f32,
+ /*ncols_x=*/(int64_t)K, /*nrows_x=*/(int64_t)M,
+ /*ncols_dst=*/(int64_t)N,
+ /*stride_row_x=*/stride_row_x, /*ncols_y=*/(int64_t)N,
+ /*nrows_dst=*/(int64_t)M,
+ /*nchannels_x=*/1, /*nchannels_y=*/1,
+ /*stride_channel_x=*/0, /*stride_channel_y=*/stride_y,
+ /*stride_channel_dst=*/0,
+ /*nsamples_x=*/1, /*nsamples_y=*/1,
+ /*stride_sample_x=*/0, /*stride_sample_y=*/stride_y,
+ /*stride_sample_dst=*/0,
+ /*use_stream_k=*/use_stream_k != 0,
+ /*ncols_max=*/(int64_t)N,
+ /*x_soa=*/nullptr,
+ /*soa_blocks=*/0,
+ /*stream_k_fixup=*/static_cast(stream_k_fixup),
+ /*stream_k_fixup_elements=*/stream_k_fixup_bytes / sizeof(float),
+ };
+ mul_mat_q_case(*ctx, args, stream);
+ const cudaError_t err = cudaGetLastError();
+ return err == cudaSuccess ? 0 : -2;
+}
+
+static int ds4_q4_16warp_prepare_once(int device);
+
+extern "C" int ds4_mmq_q4_K_dense_preq_16warp_for_test(
+ const void *W_q4_K, const void *q8_ds4, size_t q8_bytes,
+ float *out_f32, int M, int N, int K, cudaStream_t stream) {
+ size_t total = 0;
+ if (!W_q4_K || !q8_ds4 || !out_f32 ||
+ !ds4_q4_test_q8_1_layout(N, K, nullptr, &total) ||
+ q8_bytes < total) {
+ return -1;
+ }
+ // This Stream-K oracle hook deliberately accepts an N tail (the production
+ // selector is stricter until NVIDIA measurements justify broadening it),
+ // but it must reject shapes that cannot be represented by this kernel
+ // before enqueueing any work.
+ if (M < 128 || (M % 128) != 0 || N < 512 ||
+ K < 1024 || K > 8192 || (K % QK_K) != 0) {
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ const int dev = ggml_cuda_get_device();
+ const int cc = ggml_cuda_info().devices[dev].cc;
+ if (!ds4_mmq_q4_K_dense_16warp_available(cc) ||
+ ds4_q4_16warp_prepare_once(dev) != 0) {
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ ggml_backend_cuda_context *ctx = get_ctx_for_device(dev);
+ if (!ctx) return DS4_MMQ_NOT_APPLICABLE;
+ ds4_pool_set_stream(stream);
+ const int nsm = ggml_cuda_info().devices[dev].nsm;
+ const size_t fixup_bytes =
+ ds4_mmq_q4_K_dense_16warp_streamk_scratch_bytes(M, N, nsm);
+ ggml_cuda_pool_alloc fixup(ctx->pool());
+ if (fixup_bytes != 0u) fixup.alloc(fixup_bytes);
+ return ds4_mmq_q4_K_dense_16warp_streamk_enqueue(
+ W_q4_K, q8_ds4, out_f32, fixup.get(), fixup_bytes,
+ M, N, K, nsm, stream);
+}
+
+enum {
+ DS4_Q4_16WARP_REQUEST = 1,
+ DS4_Q4_16WARP_REQUIRE = 2,
+ DS4_Q4_16WARP_DISABLE = 4,
+};
+
+static bool ds4_q4_16warp_env_enabled(const char *name) {
+ const char *value = getenv(name);
+ return value && value[0] && !(value[0] == '0' && value[1] == '\0');
+}
+
+static int ds4_q4_16warp_mode(void) {
+ static const int cached = [] {
+ int mode = 0;
+ if (ds4_q4_16warp_env_enabled("DS4_CUDA_Q4_MMQ_16WARP")) {
+ mode |= DS4_Q4_16WARP_REQUEST;
+ }
+ if (ds4_q4_16warp_env_enabled(
+ "DS4_CUDA_REQUIRE_Q4_MMQ_16WARP")) {
+ mode |= DS4_Q4_16WARP_REQUEST | DS4_Q4_16WARP_REQUIRE;
+ }
+ if (ds4_q4_16warp_env_enabled("DS4_CUDA_NO_Q4_MMQ_16WARP")) {
+ mode |= DS4_Q4_16WARP_DISABLE;
+ }
+ return mode;
+ }();
+ return cached;
+}
+
+static int ds4_q4_16warp_prepare_once(int device) {
+ static std::mutex mutex;
+ static std::atomic state[GGML_CUDA_MAX_DEVICES];
+ if (device < 0 || device >= GGML_CUDA_MAX_DEVICES) return -1;
+ int cached = state[device].load(std::memory_order_acquire);
+ if (cached == 1) return 0;
+ if (cached < 0) return cached;
+ std::lock_guard lock(mutex);
+ cached = state[device].load(std::memory_order_relaxed);
+ if (cached == 1) return 0;
+ if (cached < 0) return cached;
+ const int rc = ds4_mmq_q4_K_dense_16warp_prepare();
+ state[device].store(rc == 0 ? 1 : rc, std::memory_order_release);
+ return rc;
+}
+
+/* Keep the 16-warp experiment on geometries with enough independent output
+ * tiles to occupy the device well. Below canonical's 90% whole-tile cutoff,
+ * the candidate mirrors canonical stream-K partitioning and fixup; this 80%
+ * gate is therefore only an admission/performance heuristic, not a numerical
+ * shortcut. On GB10 the Q-A/KV N=4096 shapes score 88%. */
+static bool ds4_q4_16warp_grid_efficient(int M, int N, int nsm) {
+ if (M <= 0 || N <= 0 || nsm <= 0) return false;
+ const int64_t tiles_m = ((int64_t)M + 127) / 128;
+ const int64_t tiles_n = ((int64_t)N + 127) / 128;
+ if (tiles_m > INT64_MAX / tiles_n) return false;
+ const int64_t tiles = tiles_m * tiles_n;
+ const int64_t waves = (tiles + nsm - 1) / nsm;
+ if (waves <= 0 || (int64_t)nsm > INT64_MAX / waves) return false;
+ return (100 * tiles) / ((int64_t)nsm * waves) >= 80;
+}
+
+static bool ds4_q4_16warp_pair_leg_shape_supported(
+ int cc, int M, int N, int K) {
+ return ds4_mmq_q4_K_dense_16warp_available(cc) &&
+ M >= 512 && (M % 128) == 0 &&
+ N >= 512 && (N % 128) == 0 &&
+ K >= 1024 && K <= 4096 && (K % QK_K) == 0;
+}
+
+/* Resolve the experiment before allocation or enqueue. The standalone path
+ * uses the public M>=1024 gate; a dense-pair leg may go down to M=512 because
+ * Q-A/KV pairs contain a 512-row leg. Each candidate grid must retain at least
+ * 80% whole-tile SM-wave efficiency; scheduling itself follows canonical
+ * stream-K whenever canonical would split K. */
+static int ds4_q4_16warp_select(
+ const char *tag, int device, int cc, int M, int N, int K,
+ bool pair_leg, bool *selected) {
+ if (!selected) return DS4_MMQ_NOT_APPLICABLE;
+ *selected = false;
+ const int mode = ds4_q4_16warp_mode();
+ const bool disabled = (mode & DS4_Q4_16WARP_DISABLE) != 0;
+ const bool requested = (mode & DS4_Q4_16WARP_REQUEST) != 0;
+ const bool required = (mode & DS4_Q4_16WARP_REQUIRE) != 0;
+ if (!requested) return 0;
+
+ const bool shape_supported = pair_leg
+ ? ds4_q4_16warp_pair_leg_shape_supported(cc, M, N, K)
+ : ds4_mmq_q4_K_dense_16warp_supported(cc, M, N, K) != 0;
+ // The exact oracle models canonical m128n128 MMQ. Check the selector's
+ // actual result, not only its upper bound: resource limits and equal
+ // ceil-division plateaus can make it retain a narrower tile.
+ const bool canonical_x128 =
+ ds4_q4_test_reference_uses_m128n128(device, cc, N);
+ const bool grid_efficient = ds4_q4_16warp_grid_efficient(
+ M, N, ggml_cuda_info().devices[device].nsm);
+ if (required && (disabled || !shape_supported || !canonical_x128 ||
+ !grid_efficient)) {
+ fprintf(stderr,
+ "%s: required Q4 16-warp path is ineligible "
+ "(scope=%s disabled=%d shape=%d x128=%d grid_eff=%d "
+ "M=%d N=%d K=%d)\n",
+ tag, pair_leg ? "pair-leg" : "dense",
+ disabled ? 1 : 0, shape_supported ? 1 : 0,
+ canonical_x128 ? 1 : 0, grid_efficient ? 1 : 0, M, N, K);
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ if (disabled || !shape_supported || !canonical_x128 || !grid_efficient) {
+ return 0;
+ }
+
+ const int prep = ds4_q4_16warp_prepare_once(device);
+ if (prep == 0) {
+ *selected = true;
+ return 0;
+ }
+ if (required) {
+ fprintf(stderr, "%s: required Q4 16-warp preflight failed: %d\n",
+ tag, prep);
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ (void)cudaGetLastError();
+ return 0;
+}
+#endif
+
template
int ds4_mmq_dense_impl(
const char * tag,
@@ -543,6 +1311,18 @@ int ds4_mmq_dense_impl(
const int cc = ggml_cuda_info().devices[dev].cc;
if (!ds4_mmq_k_tile_supported(tag, K, cc)) return -1;
+#if !defined(GGML_USE_HIP)
+ bool use_q4_16warp = false;
+ if constexpr (type == GGML_TYPE_Q4_K) {
+ const int select_rc = ds4_q4_16warp_select(
+ tag, dev, cc, M, N, K, /*pair_leg=*/false,
+ &use_q4_16warp);
+ if (select_rc != 0) {
+ return select_rc;
+ }
+ }
+#endif
+
ggml_backend_cuda_context * ctx = get_ctx_for_device(dev);
if (!ctx) {
fprintf(stderr, "%s: failed to get cuda context for device %d\n", tag, dev);
@@ -639,6 +1419,29 @@ int ds4_mmq_dense_impl(
(void)cudaMemsetAsync(out_f32, 0, (size_t)M * (size_t)N * sizeof(float), stream);
}
+#if !defined(GGML_USE_HIP)
+ if constexpr (type == GGML_TYPE_Q4_K) {
+ if (use_q4_16warp) {
+ const int nsm = ggml_cuda_info().devices[dev].nsm;
+ const size_t fixup_bytes =
+ ds4_mmq_q4_K_dense_16warp_streamk_scratch_bytes(
+ M, N, nsm);
+ ggml_cuda_pool_alloc fixup(ctx->pool());
+ if (fixup_bytes != 0u) fixup.alloc(fixup_bytes);
+ const int rc = ds4_mmq_q4_K_dense_16warp_streamk_enqueue(
+ W, src1_q8_1, out_f32, fixup.get(), fixup_bytes,
+ M, N, K, nsm, stream);
+ if (rc != 0) {
+ fprintf(stderr,
+ "%s: Q4 16-warp stream-K launch failed: %d\n",
+ tag, rc);
+ return -3;
+ }
+ return 0;
+ }
+ }
+#endif
+
const mmq_args args = {
/*x=*/(const char *)W,
/*type_x=*/type,
@@ -663,7 +1466,471 @@ int ds4_mmq_dense_impl(
fprintf(stderr, "%s: mul_mat_q_case launch failed: %s\n", tag, cudaGetErrorString(err));
return -3;
}
- ds4_mmq_sanitize_f32(out_f32, (uint64_t)M * (uint64_t)N, stream);
+ if constexpr (type != GGML_TYPE_Q4_K) {
+ ds4_mmq_sanitize_f32(out_f32, (uint64_t)M * (uint64_t)N, stream);
+ }
+ return 0;
+}
+
+/* Batched Q4_K pair for the prefill tier. The two ordinary dense calls
+ * differ only in their weight/output rows; their Q8_1 MMQ activation is
+ * byte-identical. Keep that activation alive across both established MMQ
+ * launches so Q-A and KV pay the quantize/tail-clear prelude once. */
+int ds4_mmq_q4_K_dense_pair_impl(
+ const void * W0,
+ const void * W1,
+ const float * X_f32,
+ float * out0_f32,
+ float * out1_f32,
+ int M0,
+ int M1,
+ int N,
+ int K,
+ cudaStream_t stream) {
+ const char *tag = "ds4_mmq_q4_K_dense_pair";
+ if (!W0 || !W1 || !X_f32 || !out0_f32 || !out1_f32) {
+ fprintf(stderr, "%s: null pointer\n", tag);
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ if (M0 <= 0 || M1 <= 0 || N <= 0 || K <= 0 || K % 256 != 0) {
+ fprintf(stderr, "%s: bad shape M0=%d M1=%d N=%d K=%d\n",
+ tag, M0, M1, N, K);
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ if ((size_t)M0 > SIZE_MAX / (size_t)N / sizeof(float) ||
+ (size_t)M1 > SIZE_MAX / (size_t)N / sizeof(float)) {
+ fprintf(stderr, "%s: output size overflow\n", tag);
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ const size_t out0_bytes = (size_t)M0 * (size_t)N * sizeof(float);
+ const size_t out1_bytes = (size_t)M1 * (size_t)N * sizeof(float);
+ const uintptr_t out0_addr = (uintptr_t)out0_f32;
+ const uintptr_t out1_addr = (uintptr_t)out1_f32;
+ const bool outputs_overlap = out0_addr <= out1_addr
+ ? (size_t)(out1_addr - out0_addr) < out0_bytes
+ : (size_t)(out0_addr - out1_addr) < out1_bytes;
+ if (outputs_overlap) {
+ fprintf(stderr, "%s: output ranges overlap\n", tag);
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+
+ const int dev = ggml_cuda_get_device();
+ const int cc = ggml_cuda_info().devices[dev].cc;
+ if (!ds4_mmq_k_tile_supported(tag, K, cc)) {
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+
+#if !defined(GGML_USE_HIP)
+ bool use_q4_16warp0 = false;
+ bool use_q4_16warp1 = false;
+ int select_rc = ds4_q4_16warp_select(
+ tag, dev, cc, M0, N, K, /*pair_leg=*/true,
+ &use_q4_16warp0);
+ if (select_rc != 0) return select_rc;
+ select_rc = ds4_q4_16warp_select(
+ tag, dev, cc, M1, N, K, /*pair_leg=*/true,
+ &use_q4_16warp1);
+ if (select_rc != 0) return select_rc;
+#endif
+
+ ggml_backend_cuda_context *ctx = get_ctx_for_device(dev);
+ if (!ctx) {
+ fprintf(stderr, "%s: failed to get cuda context for device %d\n",
+ tag, dev);
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ ds4_pool_set_stream(stream);
+
+ const int64_t ne10_padded = GGML_PAD((int64_t)K, MATRIX_ROW_PADDING);
+ const size_t blocks_per_col =
+ (size_t)ne10_padded / (4u * (size_t)QK8_1);
+ const size_t bytes_per_col =
+ blocks_per_col * sizeof(block_q8_1_mmq);
+ const size_t slack_blocks = (size_t)get_mmq_x_max_host(cc);
+ if ((size_t)N > SIZE_MAX / bytes_per_col ||
+ slack_blocks > SIZE_MAX / sizeof(block_q8_1_mmq)) {
+ fprintf(stderr, "%s: activation scratch size overflow\n", tag);
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ const size_t payload_bytes = (size_t)N * bytes_per_col;
+ const size_t slack_bytes = slack_blocks * sizeof(block_q8_1_mmq);
+ if (payload_bytes > SIZE_MAX - slack_bytes) {
+ fprintf(stderr, "%s: activation scratch size overflow\n", tag);
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ const size_t nbytes_q8_1 = payload_bytes + slack_bytes;
+
+ ggml_cuda_pool_alloc src1_q8_1(ctx->pool(), nbytes_q8_1);
+ ybuf_memset(src1_q8_1.get(), nbytes_q8_1, stream);
+ quantize_mmq_q8_1_cuda(
+ X_f32, /*ids=*/nullptr, (void *)src1_q8_1.get(),
+ GGML_TYPE_Q4_K, /*ne00=*/K, /*s11=*/(int64_t)K,
+ /*s12=*/0, /*s13=*/0,
+ /*ne0=*/ne10_padded, /*ne1=*/(int64_t)N,
+ /*ne2=*/1, /*ne3=*/1, stream);
+ cudaError_t err = cudaGetLastError();
+ if (err != cudaSuccess) {
+ fprintf(stderr, "%s: quantize failed: %s\n",
+ tag, cudaGetErrorString(err));
+ return -2;
+ }
+
+ const int64_t stride_row_x = (int64_t)K / QK_K;
+ const int64_t stride_channel_y =
+ (int64_t)(payload_bytes / sizeof(int));
+ const bool use_stream_k =
+ (GGML_CUDA_CC_IS_NVIDIA(cc) &&
+ ggml_cuda_highest_compiled_arch(cc) >= GGML_CUDA_CC_VOLTA) ||
+ GGML_CUDA_CC_IS_CDNA(cc);
+
+#if !defined(GGML_USE_HIP)
+ const int q4_16warp_nsm = ggml_cuda_info().devices[dev].nsm;
+ const size_t q4_16warp_fixup0 = use_q4_16warp0
+ ? ds4_mmq_q4_K_dense_16warp_streamk_scratch_bytes(
+ M0, N, q4_16warp_nsm)
+ : 0u;
+ const size_t q4_16warp_fixup1 = use_q4_16warp1
+ ? ds4_mmq_q4_K_dense_16warp_streamk_scratch_bytes(
+ M1, N, q4_16warp_nsm)
+ : 0u;
+ const size_t q4_16warp_fixup_bytes =
+ q4_16warp_fixup0 > q4_16warp_fixup1
+ ? q4_16warp_fixup0 : q4_16warp_fixup1;
+ // Both legs are ordered on the same stream, so one allocation can be
+ // cleared and reused after the first leg's fixup has consumed it.
+ ggml_cuda_pool_alloc q4_16warp_fixup(ctx->pool());
+ if (q4_16warp_fixup_bytes != 0u) {
+ q4_16warp_fixup.alloc(q4_16warp_fixup_bytes);
+ }
+#endif
+
+ if (out_memset_enabled()) {
+ cudaMemsetAsync(out0_f32, 0, out0_bytes, stream);
+ }
+ const mmq_args args0 = {
+ /*x=*/(const char *)W0,
+ /*type_x=*/GGML_TYPE_Q4_K,
+ /*y=*/(const int *)src1_q8_1.get(),
+ /*ids_dst=*/nullptr,
+ /*expert_bounds=*/nullptr,
+ /*dst=*/out0_f32,
+ /*ncols_x=*/(int64_t)K,
+ /*nrows_x=*/(int64_t)M0,
+ /*ncols_dst=*/(int64_t)N,
+ /*stride_row_x=*/stride_row_x,
+ /*ncols_y=*/(int64_t)N,
+ /*nrows_dst=*/(int64_t)M0,
+ /*nchannels_x=*/1,
+ /*nchannels_y=*/1,
+ /*stride_channel_x=*/0,
+ /*stride_channel_y=*/stride_channel_y,
+ /*stride_channel_dst=*/0,
+ /*nsamples_x=*/1,
+ /*nsamples_y=*/1,
+ /*stride_sample_x=*/0,
+ /*stride_sample_y=*/stride_channel_y,
+ /*stride_sample_dst=*/0,
+ /*use_stream_k=*/use_stream_k,
+ /*ncols_max=*/(int64_t)N,
+ };
+#if !defined(GGML_USE_HIP)
+ if (use_q4_16warp0) {
+ const int rc = ds4_mmq_q4_K_dense_16warp_streamk_enqueue(
+ W0, src1_q8_1.get(), out0_f32,
+ q4_16warp_fixup.get(), q4_16warp_fixup_bytes,
+ M0, N, K, q4_16warp_nsm, stream);
+ if (rc != 0) {
+ fprintf(stderr,
+ "%s: first Q4 16-warp stream-K launch failed: %d\n",
+ tag, rc);
+ return -3;
+ }
+ } else
+#endif
+ {
+ mul_mat_q_case(*ctx, args0, stream);
+ err = cudaGetLastError();
+ if (err != cudaSuccess) {
+ fprintf(stderr, "%s: first mul_mat_q_case launch failed: %s\n",
+ tag, cudaGetErrorString(err));
+ return -3;
+ }
+ }
+
+ if (out_memset_enabled()) {
+ cudaMemsetAsync(out1_f32, 0, out1_bytes, stream);
+ }
+ const mmq_args args1 = {
+ /*x=*/(const char *)W1,
+ /*type_x=*/GGML_TYPE_Q4_K,
+ /*y=*/(const int *)src1_q8_1.get(),
+ /*ids_dst=*/nullptr,
+ /*expert_bounds=*/nullptr,
+ /*dst=*/out1_f32,
+ /*ncols_x=*/(int64_t)K,
+ /*nrows_x=*/(int64_t)M1,
+ /*ncols_dst=*/(int64_t)N,
+ /*stride_row_x=*/stride_row_x,
+ /*ncols_y=*/(int64_t)N,
+ /*nrows_dst=*/(int64_t)M1,
+ /*nchannels_x=*/1,
+ /*nchannels_y=*/1,
+ /*stride_channel_x=*/0,
+ /*stride_channel_y=*/stride_channel_y,
+ /*stride_channel_dst=*/0,
+ /*nsamples_x=*/1,
+ /*nsamples_y=*/1,
+ /*stride_sample_x=*/0,
+ /*stride_sample_y=*/stride_channel_y,
+ /*stride_sample_dst=*/0,
+ /*use_stream_k=*/use_stream_k,
+ /*ncols_max=*/(int64_t)N,
+ };
+#if !defined(GGML_USE_HIP)
+ if (use_q4_16warp1) {
+ const int rc = ds4_mmq_q4_K_dense_16warp_streamk_enqueue(
+ W1, src1_q8_1.get(), out1_f32,
+ q4_16warp_fixup.get(), q4_16warp_fixup_bytes,
+ M1, N, K, q4_16warp_nsm, stream);
+ if (rc != 0) {
+ fprintf(stderr,
+ "%s: second Q4 16-warp stream-K launch failed: %d\n",
+ tag, rc);
+ return -4;
+ }
+ } else
+#endif
+ {
+ mul_mat_q_case(*ctx, args1, stream);
+ err = cudaGetLastError();
+ if (err != cudaSuccess) {
+ fprintf(stderr, "%s: second mul_mat_q_case launch failed: %s\n",
+ tag, cudaGetErrorString(err));
+ return -4;
+ }
+ }
+ return 0;
+}
+
+#if !defined(GGML_USE_HIP)
+static bool ds4_q4_grouped_q81_env_enabled(const char *name) {
+ const char *value = getenv(name);
+ return value && value[0] && !(value[0] == '0' && value[1] == '\0');
+}
+#endif
+
+/* Token-batched grouped Q4_K projection for attention output-A. The source
+ * is token-major [N][G][K], while MMQ stores directly into token-major
+ * [N][G][M]. Quantizing the strided source as G channels removes the old
+ * pack/unpack copies and shares one scratch allocation/quantizer launch.
+ *
+ * single_grid=false retains the established one-MMQ-launch-per-group path.
+ * single_grid=true maps groups to grid.z in one launch, but isolates each
+ * z-slice's stream-k coordinate space. Its grid.x, partial-K ownership and
+ * fixup order are therefore identical to the former per-group invocation. */
+int ds4_mmq_q4_K_grouped_dense_impl(
+ const void *W,
+ const float *X,
+ float *out,
+ int M,
+ int N,
+ int K,
+ int n_groups,
+ bool single_grid,
+ cudaStream_t stream) {
+ const char *tag = single_grid
+ ? "ds4_mmq_q4_K_grouped_dense_single_grid"
+ : "ds4_mmq_q4_K_grouped_dense";
+ const int pre_enqueue_failure = single_grid
+ ? DS4_MMQ_NOT_APPLICABLE
+ : -1;
+ if (!W || !X || !out) {
+ fprintf(stderr, "%s: null pointer\n", tag);
+ return pre_enqueue_failure;
+ }
+ if (M <= 0 || N <= 0 || K <= 0 || n_groups <= 0 ||
+ K % QK_K != 0) {
+ fprintf(stderr, "%s: bad shape M=%d N=%d K=%d groups=%d\n",
+ tag, M, N, K, n_groups);
+ return pre_enqueue_failure;
+ }
+
+ const int dev = ggml_cuda_get_device();
+ const int cc = ggml_cuda_info().devices[dev].cc;
+#if !defined(GGML_USE_HIP)
+ const bool q81_disable =
+ getenv("DS4_CUDA_NO_Q4_GROUPED_ATTN_A_Q81") != nullptr ||
+ getenv("DS4_CUDA_NO_Q4_GROUPED_ATTN_A_PREFILL") != nullptr ||
+ getenv("DS4_CUDA_NO_Q4_GROUPED_ATTN_A") != nullptr ||
+ getenv("DS4_CUDA_NO_Q4_GB10_FAST") != nullptr;
+ const bool q81_require = ds4_q4_grouped_q81_env_enabled(
+ "DS4_CUDA_REQUIRE_Q4_GROUPED_ATTN_A_Q81");
+ const bool q81_eligible =
+ gb10_optimizations_enabled() &&
+ cc == GGML_CUDA_CC_DGX_SPARK && M == 1024 && N > 8 &&
+ N <= INT32_MAX / (8*4096) && K == 4096 && n_groups == 8 &&
+ (((uintptr_t)X & 15u) == 0u);
+ if (q81_require && (q81_disable || !q81_eligible)) {
+ fprintf(stderr,
+ "%s: required grouped K4096/G8 Q8_1 quantizer is not "
+ "eligible\n",
+ tag);
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ const bool use_specialized_q81 = q81_eligible && !q81_disable;
+#endif
+ ggml_backend_cuda_context *ctx = get_ctx_for_device(dev);
+ if (!ctx) {
+ fprintf(stderr, "%s: failed to get cuda context for device %d\n",
+ tag, dev);
+ return pre_enqueue_failure;
+ }
+ ds4_pool_set_stream(stream);
+
+ const int64_t ne10_padded = GGML_PAD((int64_t)K, MATRIX_ROW_PADDING);
+ const size_t blocks_per_col =
+ (size_t)ne10_padded / (4u * (size_t)QK8_1);
+ const size_t bytes_per_col =
+ blocks_per_col * sizeof(block_q8_1_mmq);
+ if ((size_t)N > SIZE_MAX / bytes_per_col) return pre_enqueue_failure;
+ const size_t channel_bytes = (size_t)N * bytes_per_col;
+ if ((size_t)n_groups > SIZE_MAX / channel_bytes) {
+ return pre_enqueue_failure;
+ }
+ const size_t payload_bytes = (size_t)n_groups * channel_bytes;
+ const size_t slack_blocks = (size_t)get_mmq_x_max_host(cc);
+ if (slack_blocks > SIZE_MAX / sizeof(block_q8_1_mmq)) {
+ return pre_enqueue_failure;
+ }
+ const size_t slack_bytes = slack_blocks * sizeof(block_q8_1_mmq);
+ if (payload_bytes > SIZE_MAX - slack_bytes) return pre_enqueue_failure;
+
+ const int64_t row_blocks = (int64_t)K / QK_K;
+ if ((size_t)M > SIZE_MAX / (size_t)row_blocks /
+ sizeof(block_q4_K)) return pre_enqueue_failure;
+ const size_t group_weight_bytes =
+ (size_t)M * (size_t)row_blocks * sizeof(block_q4_K);
+ const int64_t group_weight_blocks = (int64_t)M * row_blocks;
+ const int64_t low_dim = (int64_t)M * n_groups;
+ if (low_dim > INT_MAX ||
+ (uint64_t)low_dim > UINT64_MAX / (uint64_t)N) {
+ return pre_enqueue_failure;
+ }
+ /* The grouped kernel ABI narrows strides and weight-block offsets to int.
+ * Reject before allocating or enqueueing so an optional caller can safely
+ * fall back to the established per-group launch loop. */
+ if (single_grid &&
+ (n_groups > 65535 || group_weight_blocks > INT_MAX ||
+ group_weight_blocks * (int64_t)n_groups > INT_MAX ||
+ channel_bytes / sizeof(int) > (size_t)INT_MAX)) {
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+
+ ggml_cuda_pool_alloc y_q8_1(
+ ctx->pool(), payload_bytes + slack_bytes);
+ ybuf_memset(y_q8_1.get(), payload_bytes + slack_bytes, stream);
+#if !defined(GGML_USE_HIP)
+ if (use_specialized_q81) {
+ quantize_mmq_q8_1_q4_grouped_k4096_g8x2_cuda(
+ X, (void *)y_q8_1.get(), N, stream);
+ } else
+#endif
+ {
+ quantize_mmq_q8_1_cuda(
+ X, /*ids=*/nullptr, (void *)y_q8_1.get(), GGML_TYPE_Q4_K,
+ /*ne00=*/K,
+ /*s01=*/(int64_t)n_groups * K,
+ /*s02=*/(int64_t)K,
+ /*s03=*/(int64_t)n_groups * N * K,
+ /*ne0=*/ne10_padded, /*ne1=*/N,
+ /*ne2=*/n_groups, /*ne3=*/1, stream);
+ }
+ cudaError_t err = cudaGetLastError();
+ if (err != cudaSuccess) {
+ fprintf(stderr, "%s: quantize failed: %s\n",
+ tag, cudaGetErrorString(err));
+ return -2;
+ }
+
+ if (out_memset_enabled()) {
+ cudaMemsetAsync(out, 0,
+ (size_t)N * (size_t)low_dim * sizeof(float), stream);
+ }
+ const bool use_stream_k =
+ (GGML_CUDA_CC_IS_NVIDIA(cc) &&
+ ggml_cuda_highest_compiled_arch(cc) >= GGML_CUDA_CC_VOLTA) ||
+ GGML_CUDA_CC_IS_CDNA(cc);
+ if (single_grid) {
+ const mmq_args args = {
+ /*x=*/(const char *)W,
+ /*type_x=*/GGML_TYPE_Q4_K,
+ /*y=*/(const int *)y_q8_1.get(),
+ /*ids_dst=*/nullptr,
+ /*expert_bounds=*/nullptr,
+ /*dst=*/out,
+ /*ncols_x=*/(int64_t)K,
+ /*nrows_x=*/(int64_t)M,
+ /*ncols_dst=*/(int64_t)N,
+ /*stride_row_x=*/row_blocks,
+ /*ncols_y=*/(int64_t)N,
+ /*nrows_dst=*/low_dim,
+ /*nchannels_x=*/(int64_t)n_groups,
+ /*nchannels_y=*/(int64_t)n_groups,
+ /*stride_channel_x=*/group_weight_blocks,
+ /*stride_channel_y=*/(int64_t)(channel_bytes / sizeof(int)),
+ /*stride_channel_dst=*/(int64_t)M,
+ /*nsamples_x=*/1,
+ /*nsamples_y=*/1,
+ /*stride_sample_x=*/0,
+ /*stride_sample_y=*/0,
+ /*stride_sample_dst=*/0,
+ /*use_stream_k=*/use_stream_k,
+ /*ncols_max=*/(int64_t)N,
+ };
+ mul_mat_q_case_grouped_channels(*ctx, args, stream);
+ err = cudaGetLastError();
+ if (err != cudaSuccess) {
+ fprintf(stderr, "%s: grouped launch failed: %s\n",
+ tag, cudaGetErrorString(err));
+ return -3;
+ }
+ return 0;
+ }
+ for (int g = 0; g < n_groups; ++g) {
+ const mmq_args args = {
+ /*x=*/(const char *)W + (size_t)g * group_weight_bytes,
+ /*type_x=*/GGML_TYPE_Q4_K,
+ /*y=*/(const int *)(y_q8_1.get() + (size_t)g * channel_bytes),
+ /*ids_dst=*/nullptr,
+ /*expert_bounds=*/nullptr,
+ /*dst=*/out + (int64_t)g * M,
+ /*ncols_x=*/(int64_t)K,
+ /*nrows_x=*/(int64_t)M,
+ /*ncols_dst=*/(int64_t)N,
+ /*stride_row_x=*/row_blocks,
+ /*ncols_y=*/(int64_t)N,
+ /*nrows_dst=*/low_dim,
+ /*nchannels_x=*/1,
+ /*nchannels_y=*/1,
+ /*stride_channel_x=*/0,
+ /*stride_channel_y=*/(int64_t)(channel_bytes / sizeof(int)),
+ /*stride_channel_dst=*/0,
+ /*nsamples_x=*/1,
+ /*nsamples_y=*/1,
+ /*stride_sample_x=*/0,
+ /*stride_sample_y=*/(int64_t)(channel_bytes / sizeof(int)),
+ /*stride_sample_dst=*/0,
+ /*use_stream_k=*/use_stream_k,
+ /*ncols_max=*/(int64_t)N,
+ };
+ mul_mat_q_case(*ctx, args, stream);
+ err = cudaGetLastError();
+ if (err != cudaSuccess) {
+ fprintf(stderr, "%s: group %d launch failed: %s\n",
+ tag, g, cudaGetErrorString(err));
+ return -3;
+ }
+ }
return 0;
}
@@ -895,6 +2162,62 @@ extern "C" int ds4_mmq_q4_K_dense(
return ds4_mmq_dense_impl("ds4_mmq_q4_K_dense", W, X, out, M, N, K, stream);
}
+extern "C" int ds4_mmq_q4_K_dense_pair(
+ const void * W0, const void * W1, const float * X,
+ float * out0, float * out1,
+ int M0, int M1, int N, int K, cudaStream_t stream) {
+ return ds4_mmq_q4_K_dense_pair_impl(
+ W0, W1, X, out0, out1, M0, M1, N, K, stream);
+}
+
+extern "C" int ds4_mmq_q4_K_grouped_dense(
+ const void *W, const float *X, float *out,
+ int M, int N, int K, int n_groups, cudaStream_t stream) {
+ return ds4_mmq_q4_K_grouped_dense_impl(
+ W, X, out, M, N, K, n_groups, false, stream);
+}
+
+extern "C" int ds4_mmq_q4_K_grouped_dense_single_grid(
+ const void *W, const float *X, float *out,
+ int M, int N, int K, int n_groups, cudaStream_t stream) {
+ return ds4_mmq_q4_K_grouped_dense_impl(
+ W, X, out, M, N, K, n_groups, true, stream);
+}
+
+#if !defined(GGML_USE_HIP)
+extern "C" size_t ds4_mmq_q4_K_grouped_q8_1_scratch_bytes_for_test(int N) {
+ if (N <= 0 || N > INT32_MAX / (8*4096)) return 0u;
+ constexpr size_t blocks_per_token = 8u * 4096u / (4u * QK8_1);
+ if ((size_t)N > SIZE_MAX / blocks_per_token /
+ sizeof(block_q8_1_mmq)) {
+ return 0u;
+ }
+ return (size_t)N * blocks_per_token * sizeof(block_q8_1_mmq);
+}
+
+extern "C" int ds4_mmq_q4_K_grouped_quantize_q8_1_for_test(
+ const float *X, void *q8, size_t q8_bytes, int N,
+ int use_specialized, cudaStream_t stream) {
+ const size_t required =
+ ds4_mmq_q4_K_grouped_q8_1_scratch_bytes_for_test(N);
+ if (!X || !q8 || required == 0u || q8_bytes < required ||
+ (((uintptr_t)X & 15u) != 0u)) {
+ return -1;
+ }
+ if (use_specialized) {
+ quantize_mmq_q8_1_q4_grouped_k4096_g8x2_cuda(
+ X, q8, N, stream);
+ } else {
+ quantize_mmq_q8_1_cuda(
+ X, /*ids=*/nullptr, q8, GGML_TYPE_Q4_K,
+ /*ne00=*/4096, /*s01=*/8*4096, /*s02=*/4096,
+ /*s03=*/(int64_t)N*8*4096,
+ /*ne0=*/4096, /*ne1=*/N, /*ne2=*/8, /*ne3=*/1, stream);
+ }
+ return cudaGetLastError() == cudaSuccess ? 0 : -2;
+}
+#endif
+
extern "C" int ds4_mmq_mxfp4_dense(
const void * W, const float * X, float * out,
int M, int N, int K, cudaStream_t stream) {
@@ -1163,7 +2486,7 @@ int ds4_mmq_moe_impl(
fprintf(stderr, "%s: mul_mat_q_case (moe) launch failed: %s\n", tag, cudaGetErrorString(err));
return -4;
}
- if (sanitize_out) {
+ if (sanitize_out && type != GGML_TYPE_Q4_K) {
ds4_mmq_sanitize_f32(out_f32, (uint64_t)M * (uint64_t)ne_get_rows, stream);
}
return 0;
@@ -1336,6 +2659,16 @@ int ds4_mmq_moe_pair_impl(
const int64_t s01 = (int64_t)K / blck;
const int64_t s02 = (int64_t)M * s01;
+ // Past the shared-memory cap the launcher takes the bit-identical global
+ // variant unless the authoritative large-map kill switch rejects it.
+ if ((size_t)n_tokens * 4u > ggml_cuda_info().devices[dev].smpbo &&
+ !ds4_mmid_large_enabled()) {
+ fprintf(stderr,
+ "%s: n_tokens=%d exceeds mm_ids_helper shared-mem cap; "
+ "falling back\n", tag, n_tokens);
+ return -1;
+ }
+
ggml_cuda_pool_alloc ids_src1_alloc;
ggml_cuda_pool_alloc ids_dst_alloc;
ggml_cuda_pool_alloc expert_bounds_alloc;
@@ -1408,29 +2741,63 @@ int ds4_mmq_moe_pair_impl(
ids_src1 = (int32_t *)ids_src1_raw;
ids_dst = (int32_t *)ids_dst_raw;
expert_bounds = (int32_t *)expert_bounds_raw;
- } else if (persistent_pair_maps) {
- const auto & maps = g_mmq_pair_maps[dev];
- ids_src1 = maps.ids_src1;
- ids_dst = maps.ids_dst;
- expert_bounds = maps.expert_bounds;
- } else {
- ids_src1 = ids_src1_alloc.alloc(ctx->pool(), ne_get_rows);
- ids_dst = ids_dst_alloc.alloc(ctx->pool(), ne_get_rows);
- expert_bounds = expert_bounds_alloc.alloc(ctx->pool(), n_experts + 1);
}
- const int si1 = n_expert_used;
- const int sis1 = 1;
+ /* `fused_raw` is the only grouped path that owns neither aligned weights
+ * nor caller scratch. Its input Q8 is dead after gate/up, before down Q8
+ * is produced, so one max-sized range can back both phases. Resolve the
+ * opt-in arena (or allocate its one-block pool fallback) before the first
+ * expert-map enqueue; no mid-pipeline allocation failure can strand a
+ * partially submitted candidate. */
+ const bool grouped_raw_q81 = profile_fused_prefill &&
+ type == GGML_TYPE_IQ2_XXS && fused_down != nullptr &&
+ !direct_gateup_q8 && xa_soa == nullptr && xb_soa == nullptr &&
+ fused_down->W_soa == nullptr;
+ size_t grouped_down_q8_bytes = 0;
+ size_t grouped_q81_required = 0;
+ std::unique_lock grouped_q81_lease(
+ g_q81_state_mutex, std::defer_lock);
+ ggml_cuda_pool_alloc grouped_q81_pool;
+ char *grouped_q81_scratch = nullptr;
+ if (grouped_raw_q81 && q81_persistent_requested()) {
+ const int64_t down_padded = GGML_PAD((int64_t)M, MATRIX_ROW_PADDING);
+ const size_t tail =
+ (size_t)get_mmq_x_max_host(cc) * sizeof(block_q8_1_mmq);
+ if ((size_t)ne_get_rows > SIZE_MAX / (size_t)down_padded ||
+ (size_t)ne_get_rows * (size_t)down_padded >
+ (SIZE_MAX - tail) / sizeof(block_q8_1)) {
+ return -98;
+ }
+ grouped_down_q8_bytes =
+ (size_t)ne_get_rows * (size_t)down_padded *
+ sizeof(block_q8_1) / QK8_1 + tail;
+ grouped_q81_required = nbytes_src1_q8_1 > grouped_down_q8_bytes
+ ? nbytes_src1_q8_1 : grouped_down_q8_bytes;
+ grouped_q81_scratch = q81_grouped_persistent_acquire(
+ dev, stream, grouped_q81_required, &grouped_q81_lease);
+ if (!grouped_q81_scratch) {
+ grouped_q81_scratch = grouped_q81_pool.alloc(
+ ctx->pool(), grouped_q81_required);
+ }
+ }
- // Same cap guard as ds4_mmq_moe_impl (see comment there): past the smem
- // cap the launcher takes the bit-identical global variant (P5); only
- // refuse with DS4_MMID_LARGE=0.
- if ((size_t)n_tokens * 4u > ggml_cuda_info().devices[dev].smpbo && !ds4_mmid_large_enabled()) {
- fprintf(stderr, "%s: n_tokens=%d exceeds mm_ids_helper shared-mem cap; falling back\n",
- tag, n_tokens);
- return -1;
+ if (!direct_gateup_q8) {
+ if (persistent_pair_maps) {
+ const auto & maps = g_mmq_pair_maps[dev];
+ ids_src1 = maps.ids_src1;
+ ids_dst = maps.ids_dst;
+ expert_bounds = maps.expert_bounds;
+ } else {
+ ids_src1 = ids_src1_alloc.alloc(ctx->pool(), ne_get_rows);
+ ids_dst = ids_dst_alloc.alloc(ctx->pool(), ne_get_rows);
+ expert_bounds = expert_bounds_alloc.alloc(
+ ctx->pool(), n_experts + 1);
+ }
}
+ const int si1 = n_expert_used;
+ const int sis1 = 1;
+
cudaError_t err = cudaSuccess;
{
ds4_mmq_nvtx_scope stage(
@@ -1478,7 +2845,9 @@ int ds4_mmq_moe_pair_impl(
ggml_cuda_pool_alloc src1_q8_1_alloc;
char *src1_q8_1 = direct_gateup_q8
? (char *)fused_down->input_q8_scratch
- : src1_q8_1_alloc.alloc(ctx->pool(), nbytes_src1_q8_1);
+ : (grouped_q81_scratch
+ ? grouped_q81_scratch
+ : src1_q8_1_alloc.alloc(ctx->pool(), nbytes_src1_q8_1));
// S1.1a fix (same as the dense/moe paths): zero the over-allocated mmq Y buffer
// so the kernel's unconditional masked-out tail-tile read (mmq.cuh:3528) returns
@@ -1760,8 +3129,11 @@ int ds4_mmq_moe_pair_impl(
(size_t)ne_get_rows * (size_t)down_ne10_padded * sizeof(block_q8_1) / QK8_1;
const size_t tail_q8_bytes =
(size_t)get_mmq_x_max_host(cc) * sizeof(block_q8_1_mmq);
- ggml_cuda_pool_alloc down_q8_1(
- ctx->pool(), logical_q8_bytes + tail_q8_bytes);
+ const size_t down_q8_bytes = logical_q8_bytes + tail_q8_bytes;
+ ggml_cuda_pool_alloc down_q8_1_pool;
+ char *down_q8_1 = grouped_q81_scratch
+ ? grouped_q81_scratch
+ : down_q8_1_pool.alloc(ctx->pool(), down_q8_bytes);
const uint64_t mid_values = (uint64_t)ne_get_rows * (uint64_t)M;
{
@@ -1769,7 +3141,7 @@ int ds4_mmq_moe_pair_impl(
"ds4/prefill/moe/swiglu_down_quant",
ds4_mmq_nvtx_payload((uint32_t)ne_get_rows, (uint32_t)M),
nvtx_prefill);
- ybuf_memset(down_q8_1.get(), logical_q8_bytes + tail_q8_bytes, stream);
+ ybuf_memset(down_q8_1, down_q8_bytes, stream);
ds4_swiglu_weighted_f32<<<
(uint32_t)((mid_values + 255u) / 256u), 256, 0, stream>>>(
out_a, out_b, fused_down->router_weights,
@@ -1782,7 +3154,7 @@ int ds4_mmq_moe_pair_impl(
}
quantize_mmq_q8_1_cuda(
- fused_down->mid_f32, ids_dst, (void *)down_q8_1.get(),
+ fused_down->mid_f32, ids_dst, (void *)down_q8_1,
GGML_TYPE_Q2_K, /*ne00=*/M, /*s01=*/M,
/*s02=*/(int64_t)M, /*s03=*/(int64_t)M * ne_get_rows,
/*ne0=*/down_ne10_padded, /*ne1=*/ne_get_rows,
@@ -1807,7 +3179,7 @@ int ds4_mmq_moe_pair_impl(
const mmq_args down_args = {
/*x=*/(const char *)fused_down->W,
/*type_x=*/GGML_TYPE_Q2_K,
- /*y=*/(const int *)down_q8_1.get(),
+ /*y=*/(const int *)down_q8_1,
/*ids_dst=*/ids_dst,
/*expert_bounds=*/expert_bounds,
/*dst=*/fused_down->out,
@@ -1848,7 +3220,7 @@ int ds4_mmq_moe_pair_impl(
down_done = ds4_mmq_q2_K_moe_d2r_launch(
fused_down->W_soa,
fused_down->soa_blocks,
- down_q8_1.get(),
+ down_q8_1,
ids_dst,
expert_bounds,
fused_down->out,
@@ -1876,7 +3248,7 @@ int ds4_mmq_moe_pair_impl(
}
}
}
- if (sanitize_out) {
+ if (sanitize_out && type != GGML_TYPE_Q4_K) {
ds4_mmq_sanitize_f32(out_a, (uint64_t)M * (uint64_t)ne_get_rows, stream);
ds4_mmq_sanitize_f32(out_b, (uint64_t)M * (uint64_t)ne_get_rows, stream);
}
@@ -2110,6 +3482,100 @@ extern "C" int ds4_mmq_iq2_xxs_q2_K_moe_fused_direct_scratch_sizes(
return 0;
}
+/* Canonical-GGUF/raw counterpart of the materialized aligned-SoA pipeline.
+ * SSD streaming compacts the selected experts and remaps ids before this
+ * boundary, so n_experts describes the compact table rather than the model's
+ * global expert count. Keep all preflight ahead of the single pair_impl
+ * invocation: after that point map/quantize/MMQ work may already be queued and
+ * a negative result must be propagated instead of being converted into the
+ * retryable NOT_APPLICABLE result. */
+extern "C" int ds4_mmq_iq2_xxs_q2_K_moe_fused_raw(
+ const void * W_gate, const void * W_up, const void * W_down,
+ const float * X, const int32_t * ids, const float * router_weights,
+ float * gate, float * up, float * mid_f32, float * down,
+ int expert_mid_dim, int expert_in_dim, int out_dim,
+ int n_tokens, int n_experts, int n_expert_used,
+ float clamp, cudaStream_t stream) {
+ if (!W_gate || !W_up || !W_down || !X || !ids || !router_weights ||
+ !gate || !up || !mid_f32 || !down ||
+ expert_mid_dim <= 0 || expert_in_dim <= 0 || out_dim <= 0 ||
+ n_tokens <= 0 || n_experts <= 0 || n_expert_used <= 0 ||
+ n_expert_used > n_experts || n_experts == INT_MAX ||
+ n_tokens >= (1 << 22) || n_expert_used >= (1 << 10) ||
+ expert_in_dim % 256 != 0 || expert_mid_dim % 256 != 0) {
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+
+ const size_t nt = (size_t)n_tokens;
+ const size_t nu = (size_t)n_expert_used;
+ const size_t mid = (size_t)expert_mid_dim;
+ const size_t in = (size_t)expert_in_dim;
+ const size_t out = (size_t)out_dim;
+ if (nt > SIZE_MAX / nu) return DS4_MMQ_NOT_APPLICABLE;
+ const size_t assignments = nt * nu;
+ if (assignments > SIZE_MAX / mid ||
+ assignments * mid > SIZE_MAX / sizeof(float) ||
+ assignments > SIZE_MAX / out ||
+ assignments * out > SIZE_MAX / sizeof(float) ||
+ assignments > SIZE_MAX / in ||
+ assignments * in > SIZE_MAX / 512u ||
+ assignments * mid > SIZE_MAX / 512u) {
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+
+ /* Bound the raw per-expert strides used by both MMQs before any pool or
+ * stream operation. All dimensions enter as int, but their products do
+ * not necessarily fit int64_t. */
+ const int64_t iq2_k_blocks = expert_in_dim / 256;
+ const int64_t q2_k_blocks = expert_mid_dim / 256;
+ if ((int64_t)n_experts > INT64_MAX / expert_mid_dim ||
+ (int64_t)n_experts * expert_mid_dim > INT64_MAX / iq2_k_blocks ||
+ (int64_t)n_experts > INT64_MAX / out_dim ||
+ (int64_t)n_experts * out_dim > INT64_MAX / q2_k_blocks) {
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+
+ const int dev = ggml_cuda_get_device();
+ if (dev < 0 || dev >= GGML_CUDA_MAX_DEVICES) {
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ const int cc = ggml_cuda_info().devices[dev].cc;
+ if (!ds4_mmq_k_tile_supported(
+ "ds4_mmq_iq2_xxs_q2_K_moe_fused_raw", expert_in_dim, cc) ||
+ !get_ctx_for_device(dev) ||
+ ((size_t)n_tokens * 4u > ggml_cuda_info().devices[dev].smpbo &&
+ !ds4_mmid_large_enabled())) {
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+
+ const ds4_mmq_fused_down fused_down = {
+ W_down,
+ nullptr,
+ 0,
+ router_weights,
+ mid_f32,
+ down,
+ out_dim,
+ clamp,
+ false,
+ nullptr,
+ 0,
+ nullptr,
+ 0,
+ nullptr,
+ 0,
+ nullptr,
+ 0,
+ };
+ return ds4_mmq_moe_pair_impl(
+ "ds4_mmq_iq2_xxs_q2_K_moe_fused_raw",
+ W_gate, W_up, X, ids, gate, up,
+ expert_mid_dim, expert_in_dim, n_tokens, n_experts, n_expert_used,
+ stream,
+ nullptr, nullptr, 0,
+ /*sanitize_out=*/false, &fused_down);
+}
+
/* Aligned-artifact production fast path: gate/up accumulators stay in
* registers, weighted SwiGLU is quantized directly into down_q8_scratch by
* the fused D2R kernel, and only the pair-major down output is materialized.
@@ -2135,11 +3601,30 @@ extern "C" int ds4_mmq_iq2_xxs_q2_K_moe_fused_direct_soa(
!input_q8_scratch || input_q8_scratch_bytes == 0 ||
!down_q8_scratch || down_q8_scratch_bytes == 0 ||
!work_scratch || work_scratch_bytes == 0 || !down) {
- return -1;
- }
- const size_t down_bytes =
- (size_t)n_tokens * (size_t)n_expert_used *
- (size_t)out_dim * sizeof(float);
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ const size_t nt = (size_t)n_tokens;
+ const size_t nu = (size_t)n_expert_used;
+ const size_t od = (size_t)out_dim;
+ if (nt > SIZE_MAX / nu || nt * nu > SIZE_MAX / od ||
+ nt * nu * od > SIZE_MAX / sizeof(float)) {
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ const size_t assignments = nt * nu;
+ const size_t expert_in = (size_t)expert_in_dim;
+ const size_t expert_mid = (size_t)expert_mid_dim;
+ if (assignments > SIZE_MAX / expert_in ||
+ assignments > SIZE_MAX / expert_mid) {
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ /* The internal MMQ producer sizes multiply these logical element counts
+ * by block structs before dividing by their values-per-block. Keep ample
+ * headroom for that multiplication and its fixed tail allocation. */
+ if (assignments * expert_in > SIZE_MAX / 512u ||
+ assignments * expert_mid > SIZE_MAX / 512u) {
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ const size_t down_bytes = assignments * od * sizeof(float);
if (ds4_mmq_scratch_overlaps(
input_q8_scratch, input_q8_scratch_bytes,
down_q8_scratch, down_q8_scratch_bytes) ||
@@ -2155,12 +3640,20 @@ extern "C" int ds4_mmq_iq2_xxs_q2_K_moe_fused_direct_soa(
down_q8_scratch, down_q8_scratch_bytes, down, down_bytes) ||
ds4_mmq_scratch_overlaps(
work_scratch, work_scratch_bytes, down, down_bytes)) {
- return -1;
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ const int64_t iq2_k_blocks = expert_in_dim / 256;
+ const int64_t q2_k_blocks = expert_mid_dim / 256;
+ if ((int64_t)n_experts > INT64_MAX / expert_mid_dim ||
+ (int64_t)n_experts * expert_mid_dim > INT64_MAX / iq2_k_blocks ||
+ (int64_t)n_experts > INT64_MAX / (out_dim / 2) ||
+ (int64_t)n_experts * (out_dim / 2) > INT64_MAX / q2_k_blocks) {
+ return DS4_MMQ_NOT_APPLICABLE;
}
const int64_t iq2_blocks =
- (int64_t)n_experts * expert_mid_dim * (expert_in_dim / 256);
+ (int64_t)n_experts * expert_mid_dim * iq2_k_blocks;
const int64_t q2_pairs =
- (int64_t)n_experts * (out_dim / 2) * (expert_mid_dim / 256);
+ (int64_t)n_experts * (out_dim / 2) * q2_k_blocks;
const ds4_mmq_fused_down fused_down = {
W_down,
(const char *)W_down,
@@ -2180,13 +3673,17 @@ extern "C" int ds4_mmq_iq2_xxs_q2_K_moe_fused_direct_soa(
input_q8_ext,
input_q8_ext_bytes,
};
- return ds4_mmq_moe_pair_impl(
+ const int rc = ds4_mmq_moe_pair_impl(
"ds4_mmq_iq2_xxs_q2_K_moe_fused_direct_soa",
W_gate, W_up, X, ids, nullptr, nullptr,
expert_mid_dim, expert_in_dim, n_tokens, n_experts, n_expert_used,
stream,
(const char *)W_gate, (const char *)W_up, iq2_blocks,
/*sanitize_out=*/false, &fused_down);
+ if (rc == -1 || (rc <= -91 && rc >= -97)) {
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ return rc;
}
extern "C" int ds4_mmq_q4_K_moe_pair(
@@ -2291,11 +3788,10 @@ int ds4_mmq_moe_vec_impl(
const int64_t ne10_padded = GGML_PAD((int64_t)K, MATRIX_ROW_PADDING);
const size_t nbytes_q8_1 = (size_t)n_tokens * ne10_padded *
sizeof(block_q8_1) / QK8_1;
- // Step 7 task #29: experimental persistent Q8_1 scratch. Avoids
- // pool_alloc (cudaMallocAsync) graph nodes whose pointer baked at
- // capture time may not match the address resolved at replay. When
- // disabled (default) or when the persistent buffer is too small,
- // fall back to the pool path. See ds4_mmq_init for setup.
+ // Step 7 task #29: experimental persistent Q8_1 scratch. It avoids
+ // captured pool alloc/free nodes as a performance experiment. When
+ // disabled (default) or too small, the valid same-stream graph-memory
+ // pool path remains the fallback. See ds4_mmq_init for setup.
ggml_cuda_pool_alloc src1_q8_1_pool;
char *src1_q8_1_ptr = nullptr;
if (g_q81_scratch_enabled && g_q81_scratch_ptr &&
@@ -3047,6 +4543,162 @@ int ds4_mmq_moe_pair_vec_impl(
return 0;
}
+/* Diagnostic counters are host-dispatch counters. CUDA graph replays do not
+ * re-enter this wrapper, so they are deliberately not presented as kernel
+ * execution counts. They are still a fail-closed coverage signal: a GB10
+ * model run must observe at least one candidate and one use before this path
+ * can be promoted from opt-in to default. */
+static uint64_t g_q4_k1024_persistent_candidates;
+static uint64_t g_q4_k1024_persistent_uses;
+static uint64_t g_q4_k1024_persistent_fallbacks;
+static uint64_t g_q4_k1024_persistent_require_failures;
+static uint64_t g_q4_k1024_persistent_oracle_calls;
+static uint64_t g_q4_k1024_persistent_oracle_mismatches;
+static uint64_t g_q4_k1024_persistent_oracle_skips;
+static int g_q4_k1024_persistent_report_registered;
+static int g_q4_k1024_persistent_oracle_mismatch_reported;
+
+static bool q4_k1024_env_flag(const char *name) {
+ const char *value = getenv(name);
+ return value && value[0] && strcmp(value, "0") != 0;
+}
+
+static void q4_k1024_persistent_report(void) {
+ fprintf(stderr,
+ "ds4: CUDA Q4 K1024 persistent: "
+ "candidates=%llu uses=%llu fallbacks=%llu "
+ "require_failures=%llu oracle_calls=%llu "
+ "oracle_mismatches=%llu oracle_skips=%llu "
+ "(host dispatches; graph replays excluded, canonical oracle output retained)\n",
+ (unsigned long long)g_q4_k1024_persistent_candidates,
+ (unsigned long long)g_q4_k1024_persistent_uses,
+ (unsigned long long)g_q4_k1024_persistent_fallbacks,
+ (unsigned long long)g_q4_k1024_persistent_require_failures,
+ (unsigned long long)g_q4_k1024_persistent_oracle_calls,
+ (unsigned long long)g_q4_k1024_persistent_oracle_mismatches,
+ (unsigned long long)g_q4_k1024_persistent_oracle_skips);
+}
+
+static void q4_k1024_persistent_maybe_register_report(void) {
+ if (!g_q4_k1024_persistent_report_registered &&
+ (q4_k1024_env_flag("DS4_CUDA_Q4_K1024_PERSISTENT_STATS") ||
+ q4_k1024_env_flag("DS4_CUDA_Q4_K1024_PERSISTENT_ORACLE"))) {
+ g_q4_k1024_persistent_report_registered = 1;
+ (void)atexit(q4_k1024_persistent_report);
+ }
+}
+
+__global__ static void q4_K_k1024_bitwise_compare_kernel(
+ uint32_t *mismatch,
+ const float *candidate,
+ const float *reference,
+ uint64_t count) {
+ const uint64_t i = (uint64_t)blockIdx.x * blockDim.x + threadIdx.x;
+ if (i < count &&
+ __float_as_uint(candidate[i]) != __float_as_uint(reference[i])) {
+ atomicExch(mismatch, 1u);
+ }
+}
+
+/* GB10 AProjQ4 Q-b decode specialization (M=32768, N=1, K=1024).
+ *
+ * The canonical MMVQ small-K launch uses four warps to evaluate four rows:
+ * warp 0 owns Q4_K superblocks 0/1, warp 1 owns 2/3, and warps 2/3
+ * contribute +0.0f. Its reduction first adds the three peer-warp partials
+ * lane by lane, then applies warp_reduce_sum's XOR tree. Two independent
+ * four-warp groups below preserve that assignment and arithmetic order while
+ * persistent CTAs walk eight-row tiles at a grid stride. The immutable
+ * canonical Q8_1 activation is staged once per CTA; no Q8_K re-quantization
+ * or Q4_K weight repack is involved.
+ *
+ * Keep this kernel paired with the exact M/N/K admission in
+ * ds4_mmq_dense_vec_impl. Generalizing the row-warp mapping would change
+ * floating-point association relative to MMVQ. */
+static __global__ __launch_bounds__(256, 4) void
+q4_K_dense_vec_k1024_persistent_kernel(
+ const block_q4_K * __restrict__ W,
+ const block_q8_1 * __restrict__ x8,
+ float * __restrict__ out,
+ int M) {
+ constexpr int k_q4_blocks = 4; /* 1024 / QK_K */
+ constexpr int k_q8_blocks = 32; /* 1024 / QK8_1 */
+ constexpr int k_rows_per_group = 4; /* canonical MMVQ small-K tile */
+ constexpr int k_groups = 2;
+
+ /* block_q8_1 is 36 bytes. A uint32_t backing array both copies it
+ * efficiently and preserves the alignment required by vec_dot's int
+ * loads from qs. */
+ __shared__ __align__(16) uint32_t x8_words[
+ (k_q8_blocks * sizeof(block_q8_1)) / sizeof(uint32_t)];
+ __shared__ float partial[k_groups][3][k_rows_per_group][32];
+
+ const uint32_t *x8_src = (const uint32_t *)x8;
+ for (uint32_t i = threadIdx.x;
+ i < (uint32_t)(sizeof(x8_words) / sizeof(x8_words[0]));
+ i += blockDim.x) {
+ x8_words[i] = x8_src[i];
+ }
+ __syncthreads();
+
+ const block_q8_1 *x8_shared = (const block_q8_1 *)x8_words;
+ const uint32_t lane = threadIdx.x & 31u;
+ const uint32_t warp = threadIdx.x >> 5u;
+ const uint32_t group = warp >> 2u;
+ const uint32_t warp_in_group = warp & 3u;
+ const uint32_t group_tid = warp_in_group * 32u + lane;
+ const uint64_t row_tiles = ((uint64_t)(uint32_t)M + 7u) / 8u;
+
+ /* tile, row_tiles, and gridDim.x are block-uniform, and this loop has no
+ * divergent exit. Every thread therefore reaches both barriers below on
+ * every iteration; unrolling is unrelated to their correctness. */
+ for (uint64_t tile = blockIdx.x; tile < row_tiles; tile += gridDim.x) {
+ const uint32_t row0 = (uint32_t)(tile * 8u) +
+ group * k_rows_per_group;
+ float tmp[k_rows_per_group] = {0.0f};
+
+ /* This is the canonical N=1, K=1024 MMVQ small-K loop verbatim:
+ * qi/vdr = 16 and blocks_per_iter = 8 for Q4_K. */
+ const int kqs = VDR_Q4_K_Q8_1_MMVQ * (int)(group_tid % 16u);
+ for (int kbx = (int)(group_tid / 16u);
+ kbx < k_q4_blocks;
+ kbx += 8) {
+ const int kby = kbx * (QK_K / QK8_1);
+#pragma unroll
+ for (int i = 0; i < k_rows_per_group; ++i) {
+ tmp[i] += vec_dot_q4_K_q8_1(
+ W, &x8_shared[kby],
+ (int)((uint64_t)(row0 + (uint32_t)i) * k_q4_blocks) + kbx,
+ kqs);
+ }
+ }
+
+ if (warp_in_group > 0u) {
+#pragma unroll
+ for (int i = 0; i < k_rows_per_group; ++i) {
+ partial[group][warp_in_group - 1u][i][lane] = tmp[i];
+ }
+ }
+ __syncthreads();
+
+ if (warp_in_group == 0u) {
+#pragma unroll
+ for (int i = 0; i < k_rows_per_group; ++i) {
+#pragma unroll
+ for (int peer = 0; peer < 3; ++peer) {
+ tmp[i] += partial[group][peer][i][lane];
+ }
+ tmp[i] = warp_reduce_sum<32>(tmp[i]);
+ }
+ if (lane < k_rows_per_group) {
+ out[row0 + lane] = tmp[lane];
+ }
+ }
+ /* Both groups must finish consuming partial before the next
+ * grid-stride tile reuses it. */
+ __syncthreads();
+ }
+}
+
template
int ds4_mmq_dense_vec_impl(
const char * tag,
@@ -3056,6 +4708,7 @@ int ds4_mmq_dense_vec_impl(
int M,
int N,
int K,
+ int q4_weight_device_resident,
cudaStream_t stream) {
if (!W || !X_f32 || !out_f32) {
@@ -3083,21 +4736,302 @@ int ds4_mmq_dense_vec_impl(
return -1;
}
- // Route the pool's cudaMallocAsync through the caller-supplied stream
- // for Step 8 / CUDA Graph compatibility. See ds4_mmq_moe_vec_impl.
+ /* Resolve the exact-shape admission before allocating pool storage,
+ * quantizing X, clearing output, or launching any kernel. REQUIRE and
+ * the oracle are coverage gates: an ineligible candidate must therefore
+ * fail without leaving work queued on the caller's stream. */
+ bool q4_k1024_exact = false;
+ bool q4_k1024_eligible = false;
+ bool q4_k1024_oracle = false;
+ unsigned q4_k1024_grid = 0u;
+ if constexpr (type == GGML_TYPE_Q4_K) {
+ q4_k1024_persistent_maybe_register_report();
+ q4_k1024_exact = M == 32768 && N == 1 && K == 1024;
+ q4_k1024_oracle = q4_k1024_exact &&
+ q4_k1024_env_flag("DS4_CUDA_Q4_K1024_PERSISTENT_ORACLE");
+ const bool enable =
+ q4_k1024_env_flag("DS4_CUDA_ENABLE_Q4_K1024_PERSISTENT");
+ const bool disable =
+ q4_k1024_env_flag("DS4_CUDA_NO_Q4_K1024_PERSISTENT") ||
+ q4_k1024_env_flag("DS4_CUDA_NO_Q4_GB10_FAST");
+ if (q4_k1024_exact) {
+ g_q4_k1024_persistent_candidates++;
+ }
+ if (q4_k1024_exact && gb10_optimizations_enabled() &&
+ (enable || q4_k1024_oracle) && !disable &&
+ q4_weight_device_resident > 0 &&
+ (((uintptr_t)W & 15u) == 0u)) {
+ const uint64_t row_tiles = ((uint64_t)(uint32_t)M + 7u) / 8u;
+ const int nsm = ggml_cuda_info().devices[dev].nsm;
+ const uint64_t resident_blocks =
+ nsm > 0 ? (uint64_t)(uint32_t)nsm * 4u : 0u;
+ const uint64_t grid64 = row_tiles < resident_blocks
+ ? row_tiles : resident_blocks;
+ if (grid64 > 0u && grid64 <= UINT32_MAX) {
+ q4_k1024_grid = (unsigned)grid64;
+ q4_k1024_eligible = true;
+ }
+ }
+ if (q4_k1024_exact && !q4_k1024_eligible) {
+ g_q4_k1024_persistent_fallbacks++;
+ const bool require =
+ q4_k1024_env_flag(
+ "DS4_CUDA_REQUIRE_Q4_K1024_PERSISTENT");
+ if (require || q4_k1024_oracle) {
+ g_q4_k1024_persistent_require_failures++;
+ if (q4_k1024_oracle) {
+ g_q4_k1024_persistent_oracle_skips++;
+ }
+ fprintf(stderr,
+ "%s: required Q4_K K1024 persistent path unavailable "
+ "before enqueue\n",
+ tag);
+ return -4;
+ }
+ }
+ if (q4_k1024_eligible && q4_k1024_oracle) {
+ cudaStreamCaptureStatus capture = cudaStreamCaptureStatusNone;
+ const cudaError_t capture_err =
+ cudaStreamIsCapturing(stream, &capture);
+ if (capture_err != cudaSuccess ||
+ capture != cudaStreamCaptureStatusNone) {
+ (void)cudaGetLastError();
+ g_q4_k1024_persistent_fallbacks++;
+ g_q4_k1024_persistent_require_failures++;
+ g_q4_k1024_persistent_oracle_skips++;
+ fprintf(stderr,
+ "%s: Q4_K K1024 persistent oracle refuses CUDA "
+ "graph capture before enqueue; run the oracle with "
+ "DS4_CUDA_DECODE_GRAPHS=0\n",
+ tag);
+ return -5;
+ }
+ }
+ }
+
+ // Route the pool's cudaMallocAsync through the caller-supplied stream
+ // for Step 8 / CUDA Graph compatibility. See ds4_mmq_moe_vec_impl.
+ ds4_pool_set_stream(stream);
+
+ /* Oracle-only storage. Graph capture was rejected above, so the pool
+ * allocations and the host readback below cannot become graph nodes.
+ * The persistent candidate writes here; canonical MMVQ always owns the
+ * caller-visible output. */
+ ggml_cuda_pool_alloc q4_k1024_candidate;
+ ggml_cuda_pool_alloc q4_k1024_mismatch;
+ if (q4_k1024_eligible && q4_k1024_oracle) {
+ q4_k1024_candidate.alloc(ctx->pool(), (size_t)M);
+ q4_k1024_mismatch.alloc(ctx->pool(), 1u);
+ }
+
+ // Dense: no MoE, ids=null. Layout [K, N, 1, 1] for src1.
+ const int64_t ne10_padded = GGML_PAD((int64_t)K, MATRIX_ROW_PADDING);
+ const size_t nbytes_q8_1 = (size_t)N * ne10_padded *
+ sizeof(block_q8_1) / QK8_1;
+ ggml_cuda_pool_alloc src1_q8_1;
+ char *x8 = nullptr;
+ if constexpr (type == GGML_TYPE_Q4_K) {
+ if (gb10_optimizations_enabled() &&
+ getenv("DS4_CUDA_NO_Q4_GB10_FAST") == nullptr &&
+ getenv("DS4_CUDA_NO_Q4_DENSE_SCRATCH") == nullptr) {
+ x8 = (char *)ds4_mmq_aligned_q81_scratch(dev, nbytes_q8_1);
+ }
+ }
+ if (!x8) {
+ src1_q8_1.alloc(ctx->pool(), nbytes_q8_1);
+ x8 = src1_q8_1.get();
+ }
+
+ // Dense src1 layout: K innermost, N next; ne11=N, ne12=1, ne13=1.
+ quantize_row_q8_1_cuda(
+ X_f32, /*ids=*/nullptr, (void *)x8,
+ type, /*ne00=*/K,
+ /*s11=*/(int64_t)K, /*s12=*/(int64_t)K * N, /*s13=*/(int64_t)K * N,
+ /*ne0=*/ne10_padded, /*ne1=*/N, /*ne2=*/1, /*ne3=*/1,
+ stream);
+
+ cudaError_t err = cudaGetLastError();
+ if (err != cudaSuccess) {
+ fprintf(stderr, "%s: quantize_row_q8_1_cuda failed: %s\n",
+ tag, cudaGetErrorString(err));
+ return -2;
+ }
+
+ // Dense (no ids): per upstream dispatch (mmvq.cu:1121-1127),
+ // ncols_dst = ne1 = N
+ // nchannels_y = ne12 = 1
+ // nchannels_dst = ne2 = 1
+ // stride_col_y = s11 = ne10_padded / QK8_1
+ // stride_channel_y = s12 = N * (ne10_padded / QK8_1)
+ const int64_t blck = ggml_blck_size(type);
+ const int64_t s01_row = (int64_t)K / blck;
+ const int64_t s11_y = ne10_padded / QK8_1;
+ const int64_t s12_y = (int64_t)N * s11_y;
+ const int64_t s1_dst = (int64_t)M;
+
+ ggml_cuda_mm_fusion_args_device fusion = {};
+
+ (void)cudaMemsetAsync(out_f32, 0, (size_t)M * (size_t)N * sizeof(float), stream);
+
+ bool q4_k1024_persistent = false;
+ if constexpr (type == GGML_TYPE_Q4_K) {
+ if (q4_k1024_eligible) {
+ float *candidate_out = q4_k1024_oracle
+ ? q4_k1024_candidate.get() : out_f32;
+ q4_K_dense_vec_k1024_persistent_kernel<<<
+ q4_k1024_grid, 256, 0, stream>>>(
+ (const block_q4_K *)W,
+ (const block_q8_1 *)x8,
+ candidate_out, M);
+ g_q4_k1024_persistent_uses++;
+ q4_k1024_persistent = !q4_k1024_oracle;
+ }
+ }
+
+ if (!q4_k1024_persistent) {
+ mul_mat_vec_q_switch_type(
+ /*vx=*/W, /*type_x=*/type,
+ /*vy=*/(const void *)x8,
+ /*ids=*/nullptr, /*fusion=*/fusion,
+ /*dst=*/out_f32,
+ /*ncols_x=*/K, /*nrows_x=*/M, /*ncols_dst=*/N,
+ /*stride_row_x=*/(int)s01_row,
+ /*stride_col_y=*/(int)s11_y,
+ /*stride_col_dst=*/(int)s1_dst,
+ /*nchannels_x=*/1,
+ /*nchannels_y=*/1,
+ /*nchannels_dst=*/1,
+ /*stride_channel_x=*/0,
+ /*stride_channel_y=*/(int)s12_y,
+ /*stride_channel_dst=*/0,
+ /*nsamples_x=*/1, /*nsamples_dst=*/1,
+ /*stride_sample_x=*/0, /*stride_sample_y=*/0, /*stride_sample_dst=*/0,
+ /*ids_stride=*/0, stream);
+ }
+
+ err = cudaGetLastError();
+ if (err != cudaSuccess) {
+ fprintf(stderr, "%s: mul_mat_vec_q_switch_type (dense) launch failed: %s\n",
+ tag, cudaGetErrorString(err));
+ return -3;
+ }
+ const uint64_t out_count = (uint64_t)M * (uint64_t)N;
+ ds4_mmq_sanitize_f32(out_f32, out_count, stream);
+ if (q4_k1024_oracle) {
+ ds4_mmq_sanitize_f32(q4_k1024_candidate.get(), out_count, stream);
+ if (cudaGetLastError() != cudaSuccess) {
+ fprintf(stderr, "%s: Q4_K K1024 oracle sanitize failed\n", tag);
+ g_q4_k1024_persistent_oracle_skips++;
+ return -6;
+ }
+ cudaError_t oracle_err = cudaMemsetAsync(
+ q4_k1024_mismatch.get(), 0, sizeof(uint32_t), stream);
+ if (oracle_err == cudaSuccess) {
+ q4_K_k1024_bitwise_compare_kernel<<<
+ (unsigned)((out_count + 255u) / 256u), 256, 0, stream>>>(
+ q4_k1024_mismatch.get(), q4_k1024_candidate.get(),
+ out_f32, out_count);
+ oracle_err = cudaGetLastError();
+ }
+ uint32_t mismatch_host = 0u;
+ if (oracle_err == cudaSuccess) {
+ oracle_err = cudaMemcpyAsync(
+ &mismatch_host, q4_k1024_mismatch.get(), sizeof(uint32_t),
+ cudaMemcpyDeviceToHost, stream);
+ }
+ if (oracle_err == cudaSuccess) {
+ oracle_err = cudaStreamSynchronize(stream);
+ }
+ if (oracle_err != cudaSuccess) {
+ fprintf(stderr,
+ "%s: Q4_K K1024 persistent oracle failed: %s\n",
+ tag, cudaGetErrorString(oracle_err));
+ (void)cudaGetLastError();
+ g_q4_k1024_persistent_oracle_skips++;
+ return -6;
+ }
+ g_q4_k1024_persistent_oracle_calls++;
+ if (mismatch_host != 0u) {
+ g_q4_k1024_persistent_oracle_mismatches++;
+ if (!g_q4_k1024_persistent_oracle_mismatch_reported) {
+ g_q4_k1024_persistent_oracle_mismatch_reported = 1;
+ fprintf(stderr,
+ "%s: Q4_K K1024 persistent oracle found a bitwise "
+ "mismatch; retained canonical MMVQ output\n",
+ tag);
+ }
+ }
+ }
+ return 0;
+}
+
+template
+int ds4_mmq_dense_pair_vec_impl(
+ const char * tag,
+ const void * W0,
+ const void * W1,
+ const float * X_f32,
+ float * out0_f32,
+ float * out1_f32,
+ int M0,
+ int M1,
+ int N,
+ int K,
+ cudaStream_t stream) {
+
+ if (!W0 || !W1 || !X_f32 || !out0_f32 || !out1_f32) {
+ fprintf(stderr, "%s: null pointer\n", tag);
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ if (M0 <= 0 || M1 <= 0 || N <= 0 || K <= 0) {
+ fprintf(stderr, "%s: bad shape M0=%d M1=%d N=%d K=%d\n",
+ tag, M0, M1, N, K);
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ if (K % 256 != 0) {
+ fprintf(stderr, "%s: K=%d must be a multiple of 256\n", tag, K);
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ if (N > MMVQ_MAX_BATCH_SIZE) {
+ fprintf(stderr, "%s: N=%d exceeds MMVQ_MAX_BATCH_SIZE=%d\n",
+ tag, N, MMVQ_MAX_BATCH_SIZE);
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+
+ const int dev = ggml_cuda_get_device();
+ ggml_backend_cuda_context * ctx = get_ctx_for_device(dev);
+ if (!ctx) {
+ fprintf(stderr, "%s: failed to get cuda context for device %d\n",
+ tag, dev);
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+
ds4_pool_set_stream(stream);
- // Dense: no MoE, ids=null. Layout [K, N, 1, 1] for src1.
+ /* Match ds4_mmq_dense_vec_impl's activation layout and quantizer exactly,
+ * but retain the Q8_1 row for both projections. */
const int64_t ne10_padded = GGML_PAD((int64_t)K, MATRIX_ROW_PADDING);
- const size_t nbytes_q8_1 = (size_t)N * ne10_padded *
- sizeof(block_q8_1) / QK8_1;
- ggml_cuda_pool_alloc src1_q8_1(ctx->pool(), nbytes_q8_1);
+ const size_t nbytes_q8_1 = (size_t)N * ne10_padded *
+ sizeof(block_q8_1) / QK8_1;
+ ggml_cuda_pool_alloc src1_q8_1;
+ char *x8 = nullptr;
+ if constexpr (type == GGML_TYPE_Q4_K) {
+ if (gb10_optimizations_enabled() &&
+ getenv("DS4_CUDA_NO_Q4_GB10_FAST") == nullptr &&
+ getenv("DS4_CUDA_NO_Q4_DENSE_SCRATCH") == nullptr) {
+ x8 = (char *)ds4_mmq_aligned_q81_scratch(dev, nbytes_q8_1);
+ }
+ }
+ if (!x8) {
+ src1_q8_1.alloc(ctx->pool(), nbytes_q8_1);
+ x8 = src1_q8_1.get();
+ }
- // Dense src1 layout: K innermost, N next; ne11=N, ne12=1, ne13=1.
quantize_row_q8_1_cuda(
- X_f32, /*ids=*/nullptr, (void *)src1_q8_1.get(),
+ X_f32, /*ids=*/nullptr, (void *)x8,
type, /*ne00=*/K,
- /*s11=*/(int64_t)K, /*s12=*/(int64_t)K * N, /*s13=*/(int64_t)K * N,
+ /*s11=*/(int64_t)K, /*s12=*/(int64_t)K * N,
+ /*s13=*/(int64_t)K * N,
/*ne0=*/ne10_padded, /*ne1=*/N, /*ne2=*/1, /*ne3=*/1,
stream);
@@ -3108,48 +5042,207 @@ int ds4_mmq_dense_vec_impl(
return -2;
}
- // Dense (no ids): per upstream dispatch (mmvq.cu:1121-1127),
- // ncols_dst = ne1 = N
- // nchannels_y = ne12 = 1
- // nchannels_dst = ne2 = 1
- // stride_col_y = s11 = ne10_padded / QK8_1
- // stride_channel_y = s12 = N * (ne10_padded / QK8_1)
- const int64_t blck = ggml_blck_size(type);
- const int64_t s01_row = (int64_t)K / blck;
- const int64_t s11_y = ne10_padded / QK8_1;
- const int64_t s12_y = (int64_t)N * s11_y;
- const int64_t s1_dst = (int64_t)M;
-
+ const int64_t blck = ggml_blck_size(type);
+ const int64_t s01_row = (int64_t)K / blck;
+ const int64_t s11_y = ne10_padded / QK8_1;
+ const int64_t s12_y = (int64_t)N * s11_y;
ggml_cuda_mm_fusion_args_device fusion = {};
- (void)cudaMemsetAsync(out_f32, 0, (size_t)M * (size_t)N * sizeof(float), stream);
+ /* Keep each leg's memset, canonical MMVQ dispatch, error check, and
+ * sanitizer in the same order as two dense_vec calls. Only the activation
+ * quantization/allocation above is shared. */
+ cudaMemsetAsync(out0_f32, 0,
+ (size_t)M0 * (size_t)N * sizeof(float), stream);
+ mul_mat_vec_q_switch_type(
+ /*vx=*/W0, /*type_x=*/type,
+ /*vy=*/(const void *)x8,
+ /*ids=*/nullptr, /*fusion=*/fusion,
+ /*dst=*/out0_f32,
+ /*ncols_x=*/K, /*nrows_x=*/M0, /*ncols_dst=*/N,
+ /*stride_row_x=*/(int)s01_row,
+ /*stride_col_y=*/(int)s11_y,
+ /*stride_col_dst=*/M0,
+ /*nchannels_x=*/1, /*nchannels_y=*/1, /*nchannels_dst=*/1,
+ /*stride_channel_x=*/0,
+ /*stride_channel_y=*/(int)s12_y,
+ /*stride_channel_dst=*/0,
+ /*nsamples_x=*/1, /*nsamples_dst=*/1,
+ /*stride_sample_x=*/0, /*stride_sample_y=*/0,
+ /*stride_sample_dst=*/0,
+ /*ids_stride=*/0, stream);
+ err = cudaGetLastError();
+ if (err != cudaSuccess) {
+ fprintf(stderr, "%s: first dense MMVQ launch failed: %s\n",
+ tag, cudaGetErrorString(err));
+ return -3;
+ }
+ ds4_mmq_sanitize_f32(out0_f32, (uint64_t)M0 * (uint64_t)N, stream);
+ cudaMemsetAsync(out1_f32, 0,
+ (size_t)M1 * (size_t)N * sizeof(float), stream);
mul_mat_vec_q_switch_type(
- /*vx=*/W, /*type_x=*/type,
- /*vy=*/(const void *)src1_q8_1.get(),
+ /*vx=*/W1, /*type_x=*/type,
+ /*vy=*/(const void *)x8,
/*ids=*/nullptr, /*fusion=*/fusion,
- /*dst=*/out_f32,
- /*ncols_x=*/K, /*nrows_x=*/M, /*ncols_dst=*/N,
+ /*dst=*/out1_f32,
+ /*ncols_x=*/K, /*nrows_x=*/M1, /*ncols_dst=*/N,
/*stride_row_x=*/(int)s01_row,
/*stride_col_y=*/(int)s11_y,
- /*stride_col_dst=*/(int)s1_dst,
- /*nchannels_x=*/1,
- /*nchannels_y=*/1,
- /*nchannels_dst=*/1,
+ /*stride_col_dst=*/M1,
+ /*nchannels_x=*/1, /*nchannels_y=*/1, /*nchannels_dst=*/1,
/*stride_channel_x=*/0,
/*stride_channel_y=*/(int)s12_y,
/*stride_channel_dst=*/0,
/*nsamples_x=*/1, /*nsamples_dst=*/1,
- /*stride_sample_x=*/0, /*stride_sample_y=*/0, /*stride_sample_dst=*/0,
+ /*stride_sample_x=*/0, /*stride_sample_y=*/0,
+ /*stride_sample_dst=*/0,
/*ids_stride=*/0, stream);
+ err = cudaGetLastError();
+ if (err != cudaSuccess) {
+ fprintf(stderr, "%s: second dense MMVQ launch failed: %s\n",
+ tag, cudaGetErrorString(err));
+ return -4;
+ }
+ ds4_mmq_sanitize_f32(out1_f32, (uint64_t)M1 * (uint64_t)N, stream);
+ return 0;
+}
+
+__global__ static void ds4_mmq_group_ids_i32_kernel(
+ int32_t *ids, int n, int n_groups) {
+ const int i = (int)(blockIdx.x * blockDim.x + threadIdx.x);
+ if (i < n) ids[i] = i % n_groups;
+}
+
+/* Grouped AProjQ4 attention-A projection. Flatten (token, group) into the
+ * MMVQ channel dimension (never the column dimension): ncols_dst stays one,
+ * so every pair uses exactly the same one-row Q4_K MMVQ specialization, K
+ * partition, peer-warp fold, and reduction tree as the canonical nested
+ * token/group loop. The repeated ids select W[group], while channel_y and
+ * channel_dst retain the token-major flat index. Only activation
+ * quantization and launch setup are shared. */
+static int ds4_mmq_q4_K_grouped_batch_vec_impl(
+ const void *W,
+ const float *X,
+ float *out,
+ int M,
+ int K,
+ int n_tokens,
+ int n_groups,
+ cudaStream_t stream) {
+ const char *tag = n_tokens == 1
+ ? "ds4_mmq_q4_K_grouped_vec"
+ : "ds4_mmq_q4_K_grouped_batch_vec";
+ if (!W || !X || !out) {
+ fprintf(stderr, "%s: null pointer\n", tag);
+ return -1;
+ }
+ if (!gb10_optimizations_enabled() ||
+ getenv("DS4_CUDA_NO_Q4_GB10_FAST") != nullptr ||
+ getenv("DS4_CUDA_NO_Q4_GROUPED_ATTN_A") != nullptr ||
+ M <= 0 || K <= 0 || n_tokens <= 0 || n_tokens > 8 ||
+ n_groups <= 0 || n_groups > 16 ||
+ K % 256 != 0) {
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ if (n_tokens > 1) {
+ const char *enable =
+ getenv("DS4_CUDA_ENABLE_Q4_GROUPED_ATTN_A_BATCH");
+ if (!enable || !enable[0] || strcmp(enable, "0") == 0 ||
+ getenv("DS4_CUDA_NO_Q4_GROUPED_ATTN_A_BATCH") != nullptr) {
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ }
+
+ const int flat_channels = n_tokens * n_groups; /* <= 8 * 16 */
+
+ const int64_t row_blocks = (int64_t)K / ggml_blck_size(GGML_TYPE_Q4_K);
+ const int64_t weight_channel_stride = (int64_t)M * row_blocks;
+ if (row_blocks <= 0 || row_blocks > INT_MAX ||
+ weight_channel_stride > INT_MAX) {
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+
+ const int64_t ne10_padded = GGML_PAD((int64_t)K, MATRIX_ROW_PADDING);
+ const size_t q8_row_bytes = (size_t)ne10_padded *
+ sizeof(block_q8_1) / QK8_1;
+ if ((size_t)flat_channels > SIZE_MAX / q8_row_bytes) {
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+ const size_t nbytes_q8_1 = (size_t)flat_channels * q8_row_bytes;
+ if (nbytes_q8_1 > SIZE_MAX - 15u) return DS4_MMQ_NOT_APPLICABLE;
+ const size_t ids_offset = (nbytes_q8_1 + 15u) & ~(size_t)15u;
+ const size_t ids_bytes = (size_t)flat_channels * sizeof(int32_t);
+ if (ids_offset > SIZE_MAX - ids_bytes) {
+ return DS4_MMQ_NOT_APPLICABLE;
+ }
+
+ const int dev = ggml_cuda_get_device();
+ char *x8 = (char *)ds4_mmq_aligned_q81_scratch(
+ dev, ids_offset + ids_bytes);
+ if (!x8) return DS4_MMQ_NOT_APPLICABLE;
+ int32_t *ids = (int32_t *)(x8 + ids_offset);
+ ds4_mmq_group_ids_i32_kernel<<<
+ (unsigned)(flat_channels + 31) / 32u, 32, 0, stream>>>(
+ ids, flat_channels, n_groups);
+ cudaError_t err = cudaGetLastError();
+ if (err != cudaSuccess) {
+ fprintf(stderr, "%s: group-id launch failed: %s\n",
+ tag, cudaGetErrorString(err));
+ return -2;
+ }
+ quantize_row_q8_1_cuda(
+ X, /*ids=*/nullptr, (void *)x8,
+ GGML_TYPE_Q4_K, /*ne00=*/K,
+ /*s11=*/(int64_t)K,
+ /*s12=*/(int64_t)K * flat_channels,
+ /*s13=*/(int64_t)K * flat_channels,
+ /*ne0=*/ne10_padded, /*ne1=*/flat_channels, /*ne2=*/1, /*ne3=*/1,
+ stream);
err = cudaGetLastError();
if (err != cudaSuccess) {
- fprintf(stderr, "%s: mul_mat_vec_q_switch_type (dense) launch failed: %s\n",
+ fprintf(stderr, "%s: quantize_row_q8_1_cuda failed: %s\n",
tag, cudaGetErrorString(err));
return -3;
}
- ds4_mmq_sanitize_f32(out_f32, (uint64_t)M * (uint64_t)N, stream);
+
+ const int64_t y_channel_stride = ne10_padded / QK8_1;
+ ggml_cuda_mm_fusion_args_device fusion = {};
+ err = cudaMemsetAsync(
+ out, 0, (size_t)flat_channels * (size_t)M * sizeof(float), stream);
+ if (err != cudaSuccess) {
+ fprintf(stderr, "%s: output clear failed: %s\n",
+ tag, cudaGetErrorString(err));
+ return -4;
+ }
+ mul_mat_vec_q_switch_type(
+ /*vx=*/W, /*type_x=*/GGML_TYPE_Q4_K,
+ /*vy=*/(const void *)x8,
+ /*ids=*/ids, /*fusion=*/fusion,
+ /*dst=*/out,
+ /*ncols_x=*/K, /*nrows_x=*/M, /*ncols_dst=*/1,
+ /*stride_row_x=*/(int)row_blocks,
+ /*stride_col_y=*/(int)y_channel_stride,
+ /*stride_col_dst=*/M,
+ /*nchannels_x=*/n_groups,
+ /*nchannels_y=*/flat_channels,
+ /*nchannels_dst=*/flat_channels,
+ /*stride_channel_x=*/(int)weight_channel_stride,
+ /*stride_channel_y=*/(int)y_channel_stride,
+ /*stride_channel_dst=*/M,
+ /*nsamples_x=*/1, /*nsamples_dst=*/1,
+ /*stride_sample_x=*/0, /*stride_sample_y=*/0,
+ /*stride_sample_dst=*/0,
+ /*ids_stride=*/1, stream);
+ err = cudaGetLastError();
+ if (err != cudaSuccess) {
+ fprintf(stderr, "%s: grouped MMVQ launch failed: %s\n",
+ tag, cudaGetErrorString(err));
+ return -5;
+ }
+ ds4_mmq_sanitize_f32(
+ out, (uint64_t)(uint32_t)flat_channels * (uint64_t)(uint32_t)M,
+ stream);
return 0;
}
@@ -3679,7 +5772,9 @@ int ds4_mmq_moe_gate_up_mid_vec_impl(
ggml_cuda_pool_alloc src1_q8_1_pool;
// M2-Inc2a: the fused HC stage may have emitted this activation's q8_1
// codes already (ffn_norm) -- take them and skip the quantize prelude.
- char *src1_q8_1_ptr = ds4_mmq_folded_q81(X_f32, K, n_tokens, ne10_padded);
+ char *src1_q8_1_ptr = ds4_mmq_folded_q81(
+ X_f32, K, n_tokens, ne10_padded, stream);
+ const bool folded_hit = src1_q8_1_ptr != nullptr;
cudaError_t err;
if (!src1_q8_1_ptr) {
if (g_q81_scratch_enabled && g_q81_scratch_ptr && g_q81_scratch_bytes >= nbytes_q8_1) {
@@ -3711,6 +5806,106 @@ int ds4_mmq_moe_gate_up_mid_vec_impl(
const dim3 block_nums((M + 63) / 64, n_tokens * n_expert_used);
const dim3 block_dims(256);
+ if (folded_hit && ds4_mmq_q8_fold_oracle_enabled()) {
+ const size_t q8_bytes =
+ (size_t)ne10_padded * sizeof(block_q8_1) / QK8_1;
+ const uint64_t mid_count =
+ (uint64_t)M * (uint64_t)n_tokens * (uint64_t)n_expert_used;
+ const size_t mid_bytes = (size_t)mid_count * sizeof(float);
+ block_q8_1 *fresh = nullptr;
+ float *reference = nullptr;
+ uint32_t *mismatch_device = nullptr;
+ const bool allocated =
+ cudaMalloc((void **)&fresh, q8_bytes) == cudaSuccess &&
+ cudaMalloc((void **)&reference, mid_bytes) == cudaSuccess &&
+ cudaMalloc((void **)&mismatch_device, sizeof(uint32_t)) == cudaSuccess &&
+ fresh && reference && mismatch_device;
+ if (!allocated) {
+ (void)cudaGetLastError();
+ cudaError_t cleanup_err = cudaSuccess;
+ cleanup_err = ds4_mmq_q8_fold_oracle_free(
+ fresh, "raw-moe-fresh", cleanup_err);
+ cleanup_err = ds4_mmq_q8_fold_oracle_free(
+ reference, "raw-moe-reference", cleanup_err);
+ cleanup_err = ds4_mmq_q8_fold_oracle_free(
+ mismatch_device, "raw-moe-mismatch", cleanup_err);
+ if (cleanup_err != cudaSuccess) (void)cudaGetLastError();
+ g_q8_fold_oracle_skips++;
+ } else {
+ cudaError_t oracle_err = cudaMemsetAsync(
+ mismatch_device, 0, sizeof(uint32_t), stream);
+ if (oracle_err == cudaSuccess) {
+ quantize_row_q8_1_cuda(
+ X_f32, /*ids=*/nullptr, fresh, type,
+ /*ne00=*/K, /*s11=*/K, /*s12=*/K, /*s13=*/K,
+ /*ne0=*/ne10_padded, /*ne1=*/1, /*ne2=*/1, /*ne3=*/1,
+ stream);
+ oracle_err = cudaGetLastError();
+ }
+ if (oracle_err == cudaSuccess) {
+ ds4_mmq_moe_gate_up_mid_q8_1_qwarp32_kernel<<<
+ block_nums, block_dims, 0, stream>>>(
+ W_gate, W_up,
+ (const block_q8_1 *)src1_q8_1_ptr,
+ ids, weights, mid_f32,
+ (uint32_t)K, (uint32_t)M,
+ (uint32_t)n_tokens, (uint32_t)n_experts,
+ stride_row_x, stride_col_y, stride_channel_x, clamp);
+ oracle_err = cudaGetLastError();
+ }
+ if (oracle_err == cudaSuccess) {
+ ds4_mmq_moe_gate_up_mid_q8_1_qwarp32_kernel<<<
+ block_nums, block_dims, 0, stream>>>(
+ W_gate, W_up, fresh, ids, weights, reference,
+ (uint32_t)K, (uint32_t)M,
+ (uint32_t)n_tokens, (uint32_t)n_experts,
+ stride_row_x, stride_col_y, stride_channel_x, clamp);
+ oracle_err = cudaGetLastError();
+ }
+ if (oracle_err == cudaSuccess) {
+ q8_fold_output_compare_kernel<<<
+ (unsigned)((mid_count + 255u) / 256u), 256, 0, stream>>>(
+ mismatch_device, mid_f32, reference, mid_count);
+ oracle_err = cudaGetLastError();
+ }
+ if (oracle_err == cudaSuccess) {
+ oracle_err = cudaMemcpyAsync(
+ mid_f32, reference, mid_bytes,
+ cudaMemcpyDeviceToDevice, stream);
+ }
+ uint32_t mismatch_host = 0u;
+ if (oracle_err == cudaSuccess) {
+ oracle_err = cudaMemcpyAsync(
+ &mismatch_host, mismatch_device, sizeof(mismatch_host),
+ cudaMemcpyDeviceToHost, stream);
+ }
+ if (oracle_err == cudaSuccess) {
+ oracle_err = cudaStreamSynchronize(stream);
+ }
+ oracle_err = ds4_mmq_q8_fold_oracle_free(
+ fresh, "raw-moe-fresh", oracle_err);
+ oracle_err = ds4_mmq_q8_fold_oracle_free(
+ reference, "raw-moe-reference", oracle_err);
+ oracle_err = ds4_mmq_q8_fold_oracle_free(
+ mismatch_device, "raw-moe-mismatch", oracle_err);
+ if (oracle_err != cudaSuccess) {
+ (void)cudaGetLastError();
+ g_q8_fold_oracle_skips++;
+ fprintf(stderr, "%s: fold consumer oracle failed\n", tag);
+ return -3;
+ }
+ g_q8_fold_oracle_output_calls++;
+ g_q8_fold_oracle_raw_moe_calls++;
+ if (mismatch_host != 0u) {
+ g_q8_fold_oracle_output_mismatches++;
+ fprintf(stderr,
+ "ds4: CUDA Q8_1 fold oracle found a raw MoE "
+ "consumer output mismatch; retained canonical "
+ "output\n");
+ }
+ return 0;
+ }
+ }
ds4_mmq_moe_gate_up_mid_q8_1_qwarp32_kernel<<>>(
W_gate, W_up, (const block_q8_1 *)src1_q8_1_ptr, ids, weights, mid_f32,
(uint32_t)K, (uint32_t)M, (uint32_t)n_tokens, (uint32_t)n_experts,
@@ -3799,7 +5994,7 @@ static int ds4_mmq_q4_K_dense_pair_vec_impl(
const size_t qbytes =
(size_t)padded * sizeof(block_q8_1) / QK8_1;
ggml_cuda_pool_alloc q8_pool;
- char *x8 = ds4_mmq_folded_q81(X, K, 1, padded);
+ char *x8 = ds4_mmq_folded_q81(X, K, 1, padded, stream);
if (!x8) {
if (void *scratch = ds4_mmq_aligned_q81_scratch(dev, qbytes)) {
x8 = (char *)scratch;
@@ -3836,6 +6031,27 @@ static int ds4_mmq_q4_K_dense_pair_vec_impl(
} // anonymous namespace
+extern "C" void ds4_mmq_q4_K_k1024_persistent_counters(
+ uint64_t *candidates,
+ uint64_t *uses,
+ uint64_t *fallbacks,
+ uint64_t *require_failures,
+ uint64_t *oracle_calls,
+ uint64_t *oracle_mismatches,
+ uint64_t *oracle_skips) {
+ if (candidates) *candidates = g_q4_k1024_persistent_candidates;
+ if (uses) *uses = g_q4_k1024_persistent_uses;
+ if (fallbacks) *fallbacks = g_q4_k1024_persistent_fallbacks;
+ if (require_failures) {
+ *require_failures = g_q4_k1024_persistent_require_failures;
+ }
+ if (oracle_calls) *oracle_calls = g_q4_k1024_persistent_oracle_calls;
+ if (oracle_mismatches) {
+ *oracle_mismatches = g_q4_k1024_persistent_oracle_mismatches;
+ }
+ if (oracle_skips) *oracle_skips = g_q4_k1024_persistent_oracle_skips;
+}
+
extern "C" int ds4_mmq_q8_0_moe_vec(
const void * W, const float * X, const int32_t * ids, float * out,
int M, int K, int n_tokens, int n_experts, int n_expert_used,
@@ -3932,6 +6148,20 @@ extern "C" int ds4_mmq_iq2_xxs_aligned_derepack(
return 0;
}
+extern "C" void ds4_mmq_set_gb10_optimizations(int enabled) {
+ {
+ // Serialize the transition with any persistent Q8_1 host lease. The
+ // atomic also covers GB10 admission reads outside this arena lock.
+ std::lock_guard lock(g_q81_state_mutex);
+ g_gb10_optimizations.store(enabled != 0, std::memory_order_relaxed);
+ }
+ if (!enabled) {
+ // Backend teardown/reinit already funnels through this setter. Keep
+ // MMQ's owned arena lifecycle local to this translation unit.
+ (void)ds4_mmq_q81_persistent_cleanup();
+ }
+}
+
// ---------------------------------------------------------------------------
// Aligned-SoA Q8_0 dense decode matvec (megakernel program M1-Inc3).
//
@@ -3984,6 +6214,96 @@ __global__ void q8_0_aligned_dense_vec_kernel(
if (lane == 0) out[row] = acc;
}
+/* K=1024 decode specialization. Eight persistent row warps per CTA hoist the
+ * 32 Q8_1 activation blocks into registers and walk output rows at a grid
+ * stride. Each lane still owns the same single block term and the warp tree is
+ * unchanged, so output bits match q8_0_aligned_dense_vec_kernel. */
+__global__ __launch_bounds__(256, 6) void q8_0_aligned_dense_vec_k1024_persistent_kernel(
+ float *out,
+ const int4 *qs,
+ const __half *dq,
+ const block_q8_1 *x8,
+ int M)
+{
+ const int lane = threadIdx.x & 31;
+ const int warp = threadIdx.x >> 5;
+ const int *u = (const int *)x8[lane].qs;
+ const int u0 = u[0];
+ const int u1 = u[1];
+ const int u2 = u[2];
+ const int u3 = u[3];
+ const int u4 = u[4];
+ const int u5 = u[5];
+ const int u6 = u[6];
+ const int u7 = u[7];
+ const float dx = __low2float(x8[lane].ds);
+ const int64_t row0 = (int64_t)blockIdx.x * 8 + warp;
+ const int64_t row_stride = (int64_t)gridDim.x * 8;
+
+ for (int64_t row = row0; row < (int64_t)M; row += row_stride) {
+ const long long block = (long long)row * 32 + lane;
+ const int4 w0 = qs[block * 2 + 0];
+ const int4 w1 = qs[block * 2 + 1];
+ int s0 = ggml_cuda_dp4a(w0.x, u0, 0);
+ s0 = ggml_cuda_dp4a(w0.y, u1, s0);
+ int s1 = ggml_cuda_dp4a(w0.z, u2, 0);
+ s1 = ggml_cuda_dp4a(w0.w, u3, s1);
+ int s2 = ggml_cuda_dp4a(w1.x, u4, 0);
+ s2 = ggml_cuda_dp4a(w1.y, u5, s2);
+ int s3 = ggml_cuda_dp4a(w1.z, u6, 0);
+ s3 = ggml_cuda_dp4a(w1.w, u7, s3);
+ const int sumi = (s0 + s1) + (s2 + s3);
+ float acc = 0.0f;
+ acc += __half2float(dq[block]) * dx * (float)sumi;
+#pragma unroll
+ for (int off = 16; off > 0; off >>= 1)
+ acc += __shfl_down_sync(0xffffffffu, acc, off);
+ if (lane == 0) out[row] = acc;
+ }
+}
+
+/* Persistent-CTA form for the K=4096 vocabulary projection. It preserves
+ * the original lane/block assignment, per-lane term order, and warp tree;
+ * grouping eight row warps removes the one-warp CTA occupancy ceiling. */
+__global__ __launch_bounds__(256, 6) void q8_0_aligned_dense_vec_persistent_kernel(
+ float *out,
+ const int4 *qs,
+ const __half *dq,
+ const block_q8_1 *x8,
+ int M,
+ int nb)
+{
+ const int lane = threadIdx.x & 31;
+ const int warp = threadIdx.x >> 5;
+ const int64_t row0 = (int64_t)blockIdx.x * 8 + warp;
+ const int64_t row_stride = (int64_t)gridDim.x * 8;
+ for (int64_t row = row0; row < (int64_t)M; row += row_stride) {
+ const long long rbase = (long long)row * nb;
+ float acc = 0.0f;
+ for (int b0 = 0; b0 < nb; b0 += 32) {
+ const int b = b0 + lane;
+ const int4 w0 = qs[(rbase + b) * 2 + 0];
+ const int4 w1 = qs[(rbase + b) * 2 + 1];
+ const int *u = (const int *)x8[b].qs;
+ int sumi = 0;
+ sumi = ggml_cuda_dp4a(w0.x, u[0], sumi);
+ sumi = ggml_cuda_dp4a(w0.y, u[1], sumi);
+ sumi = ggml_cuda_dp4a(w0.z, u[2], sumi);
+ sumi = ggml_cuda_dp4a(w0.w, u[3], sumi);
+ sumi = ggml_cuda_dp4a(w1.x, u[4], sumi);
+ sumi = ggml_cuda_dp4a(w1.y, u[5], sumi);
+ sumi = ggml_cuda_dp4a(w1.z, u[6], sumi);
+ sumi = ggml_cuda_dp4a(w1.w, u[7], sumi);
+ acc += __half2float(dq[rbase + b]) *
+ __low2float(x8[b].ds) * (float)sumi;
+ }
+#pragma unroll
+ for (int off = 16; off > 0; off >>= 1)
+ acc += __shfl_down_sync(0xffffffffu, acc, off);
+ if (lane == 0) out[row] = acc;
+ }
+}
+
// Verify-width variant (v0.4 dense chase, proto_q8_aligned_nc): same aligned
// weight stream read ONCE per row, NC output columns accumulated per lane
// against col-strided q8_1 activations (which L1/L2-broadcast across rows).
@@ -4038,6 +6358,170 @@ __global__ void q8_0_aligned_dense_vec_nc_kernel(
}
}
+static int ds4_q8_aligned_warps_per_block(int cc);
+
+static cudaError_t q8_0_aligned_dense_vec_launch(
+ float *out, const int4 *qs, const __half *dq,
+ const block_q8_1 *x8, int M, int N, int K,
+ cudaStream_t stream) {
+ switch (N) {
+ case 1:
+ if (gb10_optimizations_enabled() &&
+ getenv("DS4_CUDA_NO_Q8_ALIGNED_PERSISTENT") == NULL &&
+ (K == 1024 || K == 4096) && M >= 32768) {
+ const uint64_t row_blocks = ((uint64_t)(unsigned)M + 7u) / 8u;
+ const unsigned persistent_blocks =
+ row_blocks < 288u ? (unsigned)row_blocks : 288u;
+ if (K == 1024) {
+ q8_0_aligned_dense_vec_k1024_persistent_kernel<<<
+ persistent_blocks, 256, 0, stream>>>(
+ out, qs, dq, x8, M);
+ } else {
+ q8_0_aligned_dense_vec_persistent_kernel<<<
+ persistent_blocks, 256, 0, stream>>>(
+ out, qs, dq, x8, M, K / 32);
+ }
+ } else {
+ switch (ds4_q8_aligned_warps_per_block(
+ ggml_cuda_info().devices[ggml_cuda_get_device()].cc)) {
+ case 16:
+ q8_0_aligned_dense_vec_kernel<16>
+ <<<((unsigned)M + 15u) / 16u, 512, 0, stream>>>(
+ out, qs, dq, x8, M, K / 32);
+ break;
+ case 8:
+ q8_0_aligned_dense_vec_kernel<8>
+ <<<((unsigned)M + 7u) / 8u, 256, 0, stream>>>(
+ out, qs, dq, x8, M, K / 32);
+ break;
+ case 4:
+ q8_0_aligned_dense_vec_kernel<4>
+ <<<((unsigned)M + 3u) / 4u, 128, 0, stream>>>(
+ out, qs, dq, x8, M, K / 32);
+ break;
+ case 2:
+ q8_0_aligned_dense_vec_kernel<2>
+ <<<((unsigned)M + 1u) / 2u, 64, 0, stream>>>(
+ out, qs, dq, x8, M, K / 32);
+ break;
+ default:
+ q8_0_aligned_dense_vec_kernel<1>
+ <<<(unsigned)M, 32, 0, stream>>>(
+ out, qs, dq, x8, M, K / 32);
+ break;
+ }
+ }
+ break;
+ case 2: q8_0_aligned_dense_vec_nc_kernel<2><<<(unsigned)M, 32, 0, stream>>>(out, qs, dq, x8, M, K / 32); break;
+ case 3: q8_0_aligned_dense_vec_nc_kernel<3><<<(unsigned)M, 32, 0, stream>>>(out, qs, dq, x8, M, K / 32); break;
+ case 4: q8_0_aligned_dense_vec_nc_kernel<4><<<(unsigned)M, 32, 0, stream>>>(out, qs, dq, x8, M, K / 32); break;
+ case 5: q8_0_aligned_dense_vec_nc_kernel<5><<<(unsigned)M, 32, 0, stream>>>(out, qs, dq, x8, M, K / 32); break;
+ case 6: q8_0_aligned_dense_vec_nc_kernel<6><<<(unsigned)M, 32, 0, stream>>>(out, qs, dq, x8, M, K / 32); break;
+ case 7: q8_0_aligned_dense_vec_nc_kernel<7><<<(unsigned)M, 32, 0, stream>>>(out, qs, dq, x8, M, K / 32); break;
+ case 8: q8_0_aligned_dense_vec_nc_kernel<8><<<(unsigned)M, 32, 0, stream>>>(out, qs, dq, x8, M, K / 32); break;
+ default: return cudaErrorInvalidValue;
+ }
+ return cudaGetLastError();
+}
+
+/* Full consumer oracle for the folded single-column Q8_0 aligned entry.
+ * It regenerates canonical Q8_1, runs the exact same consumer twice, compares
+ * output bits, and always leaves the freshly quantized reference output in
+ * the caller buffer. Return 1 when handled, 0 when diagnostics could not be
+ * set up before enqueue, and -1 after a CUDA failure. */
+static int q8_fold_q8_aligned_output_oracle(
+ const float *X_f32, const block_q8_1 *folded,
+ float *out, const int4 *qs, const __half *dq,
+ int M, int K, cudaStream_t stream) {
+ if (!ds4_mmq_q8_fold_oracle_enabled() || !folded || M <= 0 || K <= 0) {
+ return 0;
+ }
+ cudaStreamCaptureStatus capture = cudaStreamCaptureStatusNone;
+ if (cudaStreamIsCapturing(stream, &capture) != cudaSuccess ||
+ capture != cudaStreamCaptureStatusNone) {
+ (void)cudaGetLastError();
+ g_q8_fold_oracle_skips++;
+ return 0;
+ }
+ const size_t q8_bytes = (size_t)K * sizeof(block_q8_1) / QK8_1;
+ const size_t out_bytes = (size_t)M * sizeof(float);
+ block_q8_1 *fresh = nullptr;
+ float *reference = nullptr;
+ uint32_t *mismatch_device = nullptr;
+ if (cudaMalloc((void **)&fresh, q8_bytes) != cudaSuccess ||
+ cudaMalloc((void **)&reference, out_bytes) != cudaSuccess ||
+ cudaMalloc((void **)&mismatch_device, sizeof(uint32_t)) != cudaSuccess ||
+ !fresh || !reference || !mismatch_device) {
+ (void)cudaGetLastError();
+ cudaError_t cleanup_err = cudaSuccess;
+ cleanup_err = ds4_mmq_q8_fold_oracle_free(
+ fresh, "aligned-q8-fresh", cleanup_err);
+ cleanup_err = ds4_mmq_q8_fold_oracle_free(
+ reference, "aligned-q8-reference", cleanup_err);
+ cleanup_err = ds4_mmq_q8_fold_oracle_free(
+ mismatch_device, "aligned-q8-mismatch", cleanup_err);
+ if (cleanup_err != cudaSuccess) (void)cudaGetLastError();
+ g_q8_fold_oracle_skips++;
+ return 0;
+ }
+
+ cudaError_t err = cudaMemsetAsync(
+ mismatch_device, 0, sizeof(uint32_t), stream);
+ if (err == cudaSuccess) {
+ quantize_row_q8_1_cuda(
+ X_f32, /*ids=*/nullptr, fresh, GGML_TYPE_Q8_0,
+ /*ne00=*/K, /*s11=*/K, /*s12=*/K, /*s13=*/K,
+ /*ne0=*/K, /*ne1=*/1, /*ne2=*/1, /*ne3=*/1, stream);
+ err = cudaGetLastError();
+ }
+ if (err == cudaSuccess) {
+ err = q8_0_aligned_dense_vec_launch(
+ out, qs, dq, folded, M, 1, K, stream);
+ }
+ if (err == cudaSuccess) {
+ err = q8_0_aligned_dense_vec_launch(
+ reference, qs, dq, fresh, M, 1, K, stream);
+ }
+ if (err == cudaSuccess) {
+ q8_fold_output_compare_kernel<<<
+ (unsigned)(((uint64_t)M + 255u) / 256u), 256, 0, stream>>>(
+ mismatch_device, out, reference, (uint64_t)M);
+ err = cudaGetLastError();
+ }
+ if (err == cudaSuccess) {
+ err = cudaMemcpyAsync(out, reference, out_bytes,
+ cudaMemcpyDeviceToDevice, stream);
+ }
+ uint32_t mismatch_host = 0u;
+ if (err == cudaSuccess) {
+ err = cudaMemcpyAsync(&mismatch_host, mismatch_device,
+ sizeof(mismatch_host),
+ cudaMemcpyDeviceToHost, stream);
+ }
+ if (err == cudaSuccess) err = cudaStreamSynchronize(stream);
+
+ err = ds4_mmq_q8_fold_oracle_free(
+ fresh, "aligned-q8-fresh", err);
+ err = ds4_mmq_q8_fold_oracle_free(
+ reference, "aligned-q8-reference", err);
+ err = ds4_mmq_q8_fold_oracle_free(
+ mismatch_device, "aligned-q8-mismatch", err);
+ if (err != cudaSuccess) {
+ (void)cudaGetLastError();
+ g_q8_fold_oracle_skips++;
+ return -1;
+ }
+ g_q8_fold_oracle_output_calls++;
+ g_q8_fold_oracle_aligned_q8_calls++;
+ if (mismatch_host != 0u) {
+ g_q8_fold_oracle_output_mismatches++;
+ fprintf(stderr,
+ "ds4: CUDA Q8_1 fold oracle found a Q8 aligned consumer "
+ "output mismatch; retained canonical output\n");
+ }
+ return 1;
+}
+
extern "C" uint64_t ds4_mmq_q8_0_aligned_bytes(int M, int K) {
if (M <= 0 || K <= 0 || K % 1024 != 0) return 0;
const uint64_t nblk = (uint64_t)M * (uint64_t)(K / 32);
@@ -4122,7 +6606,7 @@ extern "C" int ds4_mmq_q8_0_aligned_dense_vec_pair(
const size_t qbytes =
(size_t)padded * sizeof(block_q8_1) / QK8_1;
ggml_cuda_pool_alloc q8_pool;
- char *x8 = ds4_mmq_folded_q81(X_f32, K, 1, padded);
+ char *x8 = ds4_mmq_folded_q81(X_f32, K, 1, padded, stream);
if (!x8) {
if (g_q81_scratch_enabled && g_q81_scratch_ptr &&
g_q81_scratch_bytes >= qbytes) {
@@ -4202,26 +6686,37 @@ extern "C" int ds4_mmq_q8_0_aligned_dense_vec(
// M2-Inc2a: producer-emitted q8_1 codes (qr_norm from the qkv-rms
// kernel) -- take them and skip the quantize prelude. Single-column
// producers only; verify widths always quantize.
- char *x8 = N == 1 ? ds4_mmq_folded_q81(X_f32, K, 1, ne10_padded) : NULL;
+ char *x8 = N == 1
+ ? ds4_mmq_folded_q81(X_f32, K, 1, ne10_padded, stream)
+ : NULL;
+ const bool folded_hit = x8 != NULL;
cudaError_t err;
if (!x8) {
- if (g_q81_scratch_enabled && g_q81_scratch_ptr && g_q81_scratch_bytes >= nbytes_q8_1) {
- x8 = (char *)g_q81_scratch_ptr;
- } else {
- q8_pool.alloc(ctx->pool(), nbytes_q8_1);
- x8 = q8_pool.get();
- }
- quantize_row_q8_1_cuda(
- X_f32, /*ids=*/nullptr, (void *)x8,
- GGML_TYPE_Q8_0, /*ne00=*/K,
- /*s11=*/(int64_t)K, /*s12=*/(int64_t)K * N, /*s13=*/(int64_t)K * N,
- /*ne0=*/ne10_padded, /*ne1=*/N, /*ne2=*/1, /*ne3=*/1,
- stream);
- err = cudaGetLastError();
- if (err != cudaSuccess) {
- fprintf(stderr, "%s: quantize_row_q8_1_cuda failed: %s\n", tag, cudaGetErrorString(err));
- return -2;
- }
+ if (getenv("DS4_CUDA_NO_Q8_ALIGNED_DENSE_SCRATCH") == NULL) {
+ x8 = (char *)ds4_mmq_aligned_q81_scratch(dev, nbytes_q8_1);
+ }
+ if (!x8 && g_q81_scratch_enabled && g_q81_scratch_ptr &&
+ g_q81_scratch_bytes >= nbytes_q8_1) {
+ x8 = (char *)g_q81_scratch_ptr;
+ }
+ if (!x8) {
+ q8_pool.alloc(ctx->pool(), nbytes_q8_1);
+ x8 = q8_pool.get();
+ }
+ quantize_row_q8_1_cuda(
+ X_f32, /*ids=*/nullptr, (void *)x8,
+ GGML_TYPE_Q8_0, /*ne00=*/K,
+ /*s11=*/(int64_t)K, /*s12=*/(int64_t)K * N,
+ /*s13=*/(int64_t)K * N,
+ /*ne0=*/ne10_padded, /*ne1=*/N, /*ne2=*/1, /*ne3=*/1,
+ stream);
+ err = cudaGetLastError();
+ if (err != cudaSuccess) {
+ fprintf(stderr,
+ "%s: quantize_row_q8_1_cuda failed: %s\n",
+ tag, cudaGetErrorString(err));
+ return -2;
+ }
}
const uint64_t nblk = (uint64_t)M * (uint64_t)(K / 32);
@@ -4229,46 +6724,17 @@ extern "C" int ds4_mmq_q8_0_aligned_dense_vec(
const int4 *qsp = (const int4 *)((const char *)W_aligned + dq_bytes);
const __half *dqp = (const __half *)W_aligned;
const block_q8_1 *x8p = (const block_q8_1 *)x8;
- switch (N) {
- case 1:
- switch (ds4_q8_aligned_warps_per_block(
- ggml_cuda_info().devices[dev].cc)) {
- case 16:
- q8_0_aligned_dense_vec_kernel<16>
- <<<((unsigned)M + 15u) / 16u, 512, 0, stream>>>(
- out_f32, qsp, dqp, x8p, M, K / 32);
- break;
- case 8:
- q8_0_aligned_dense_vec_kernel<8>
- <<<((unsigned)M + 7u) / 8u, 256, 0, stream>>>(
- out_f32, qsp, dqp, x8p, M, K / 32);
- break;
- case 4:
- q8_0_aligned_dense_vec_kernel<4>
- <<<((unsigned)M + 3u) / 4u, 128, 0, stream>>>(
- out_f32, qsp, dqp, x8p, M, K / 32);
- break;
- case 2:
- q8_0_aligned_dense_vec_kernel<2>
- <<<((unsigned)M + 1u) / 2u, 64, 0, stream>>>(
- out_f32, qsp, dqp, x8p, M, K / 32);
- break;
- default:
- q8_0_aligned_dense_vec_kernel<1>
- <<<(unsigned)M, 32, 0, stream>>>(
- out_f32, qsp, dqp, x8p, M, K / 32);
- break;
+ if (folded_hit && N == 1 && ds4_mmq_q8_fold_oracle_enabled()) {
+ const int oracle_rc = q8_fold_q8_aligned_output_oracle(
+ X_f32, x8p, out_f32, qsp, dqp, M, K, stream);
+ if (oracle_rc > 0) return 0;
+ if (oracle_rc < 0) {
+ fprintf(stderr, "%s: fold consumer oracle failed\n", tag);
+ return -3;
}
- break;
- case 2: q8_0_aligned_dense_vec_nc_kernel<2><<<(unsigned)M, 32, 0, stream>>>(out_f32, qsp, dqp, x8p, M, K / 32); break;
- case 3: q8_0_aligned_dense_vec_nc_kernel<3><<<(unsigned)M, 32, 0, stream>>>(out_f32, qsp, dqp, x8p, M, K / 32); break;
- case 4: q8_0_aligned_dense_vec_nc_kernel<4><<<(unsigned)M, 32, 0, stream>>>(out_f32, qsp, dqp, x8p, M, K / 32); break;
- case 5: q8_0_aligned_dense_vec_nc_kernel<5><<<(unsigned)M, 32, 0, stream>>>(out_f32, qsp, dqp, x8p, M, K / 32); break;
- case 6: q8_0_aligned_dense_vec_nc_kernel<6><<<(unsigned)M, 32, 0, stream>>>(out_f32, qsp, dqp, x8p, M, K / 32); break;
- case 7: q8_0_aligned_dense_vec_nc_kernel<7><<<(unsigned)M, 32, 0, stream>>>(out_f32, qsp, dqp, x8p, M, K / 32); break;
- case 8: q8_0_aligned_dense_vec_nc_kernel<8><<<(unsigned)M, 32, 0, stream>>>(out_f32, qsp, dqp, x8p, M, K / 32); break;
}
- err = cudaGetLastError();
+ err = q8_0_aligned_dense_vec_launch(
+ out_f32, qsp, dqp, x8p, M, N, K, stream);
if (err != cudaSuccess) {
fprintf(stderr, "%s: kernel launch failed: %s\n", tag, cudaGetErrorString(err));
return -3;
@@ -4579,7 +7045,9 @@ extern "C" uint64_t ds4_mmq_iq2_xxs_aligned_bytes(int M, int K, int n_experts) {
// pool otherwise) or nullptr on failure; *pool must outlive the launches.
static char *iq2_aligned_quantize_xn(
const char *tag, const float *X_f32, int K, int n_tokens,
- ggml_cuda_pool_alloc *pool, cudaStream_t stream) {
+ ggml_cuda_pool_alloc *pool, cudaStream_t stream,
+ bool *was_folded) {
+ if (was_folded) *was_folded = false;
const int dev = ggml_cuda_get_device();
ggml_backend_cuda_context * ctx = get_ctx_for_device(dev);
if (!ctx) {
@@ -4591,8 +7059,10 @@ static char *iq2_aligned_quantize_xn(
const size_t nbytes_q8_1 = (size_t)n_tokens * ne10_padded * sizeof(block_q8_1) / QK8_1;
// M2-Inc2a: producer-emitted q8_1 codes (ffn_norm from the fused HC
// stage) -- take them and skip the quantize prelude.
- char *folded = ds4_mmq_folded_q81(X_f32, K, n_tokens, ne10_padded);
+ char *folded = ds4_mmq_folded_q81(
+ X_f32, K, n_tokens, ne10_padded, stream);
if (folded) {
+ if (was_folded) *was_folded = true;
// C3-Inc4 fold twin selftest (DS4_Q8_FOLD_SELFTEST=,
// eager legs only -- syncs the stream): the taken sidecar must be
// byte-identical to the fresh quantize this prelude would have run.
@@ -4670,7 +7140,8 @@ extern "C" int ds4_mmq_iq2_xxs_aligned_moe_pair_vec(
return -1;
}
ggml_cuda_pool_alloc q8_pool;
- char *x8 = iq2_aligned_quantize_xn(tag, X_f32, K, n_tokens, &q8_pool, stream);
+ char *x8 = iq2_aligned_quantize_xn(
+ tag, X_f32, K, n_tokens, &q8_pool, stream, nullptr);
if (!x8) return -2;
const uint64_t nblk = (uint64_t)n_experts * (uint64_t)M * (uint64_t)(K / 256);
@@ -4707,7 +7178,9 @@ extern "C" int ds4_mmq_iq2_xxs_aligned_moe_gate_up_mid_vec(
return -1;
}
ggml_cuda_pool_alloc q8_pool;
- char *x8 = iq2_aligned_quantize_xn(tag, X_f32, K, n_tokens, &q8_pool, stream);
+ bool folded_hit = false;
+ char *x8 = iq2_aligned_quantize_xn(
+ tag, X_f32, K, n_tokens, &q8_pool, stream, &folded_hit);
if (!x8) return -2;
const uint64_t nblk = (uint64_t)n_experts * (uint64_t)M * (uint64_t)(K / 256);
@@ -4717,6 +7190,99 @@ extern "C" int ds4_mmq_iq2_xxs_aligned_moe_gate_up_mid_vec(
const __half *dq_g = (const __half *)W_gate_aligned;
const uint2 *qs_u = (const uint2 *)((const char *)W_up_aligned + dq_bytes);
const __half *dq_u = (const __half *)W_up_aligned;
+ if (folded_hit && n_tokens == 1 &&
+ ds4_mmq_q8_fold_oracle_enabled()) {
+ const size_t q8_bytes = (size_t)K * sizeof(block_q8_1) / QK8_1;
+ const uint64_t mid_count =
+ (uint64_t)M * (uint64_t)n_expert_used;
+ const size_t mid_bytes = (size_t)mid_count * sizeof(float);
+ block_q8_1 *fresh = nullptr;
+ float *reference = nullptr;
+ uint32_t *mismatch_device = nullptr;
+ const bool allocated =
+ cudaMalloc((void **)&fresh, q8_bytes) == cudaSuccess &&
+ cudaMalloc((void **)&reference, mid_bytes) == cudaSuccess &&
+ cudaMalloc((void **)&mismatch_device, sizeof(uint32_t)) == cudaSuccess &&
+ fresh && reference && mismatch_device;
+ if (!allocated) {
+ (void)cudaGetLastError();
+ cudaError_t cleanup_err = cudaSuccess;
+ cleanup_err = ds4_mmq_q8_fold_oracle_free(
+ fresh, "aligned-iq2-fresh", cleanup_err);
+ cleanup_err = ds4_mmq_q8_fold_oracle_free(
+ reference, "aligned-iq2-reference", cleanup_err);
+ cleanup_err = ds4_mmq_q8_fold_oracle_free(
+ mismatch_device, "aligned-iq2-mismatch", cleanup_err);
+ if (cleanup_err != cudaSuccess) (void)cudaGetLastError();
+ g_q8_fold_oracle_skips++;
+ } else {
+ cudaError_t oracle_err = cudaMemsetAsync(
+ mismatch_device, 0, sizeof(uint32_t), stream);
+ if (oracle_err == cudaSuccess) {
+ quantize_row_q8_1_cuda(
+ X_f32, /*ids=*/nullptr, fresh, GGML_TYPE_IQ2_XXS,
+ /*ne00=*/K, /*s11=*/K, /*s12=*/K, /*s13=*/K,
+ /*ne0=*/K, /*ne1=*/1, /*ne2=*/1, /*ne3=*/1, stream);
+ oracle_err = cudaGetLastError();
+ }
+ if (oracle_err == cudaSuccess) {
+ iq2_xxs_aligned_moe_gate_up_mid_kernel<<>>(
+ mid_f32, qs_g, dq_g, qs_u, dq_u,
+ (const block_q8_1 *)x8, ids, weights,
+ M, K / 256, K / 32, n_expert_used, clamp);
+ oracle_err = cudaGetLastError();
+ }
+ if (oracle_err == cudaSuccess) {
+ iq2_xxs_aligned_moe_gate_up_mid_kernel<<>>(
+ reference, qs_g, dq_g, qs_u, dq_u, fresh,
+ ids, weights, M, K / 256, K / 32,
+ n_expert_used, clamp);
+ oracle_err = cudaGetLastError();
+ }
+ if (oracle_err == cudaSuccess) {
+ q8_fold_output_compare_kernel<<<
+ (unsigned)((mid_count + 255u) / 256u), 256, 0, stream>>>(
+ mismatch_device, mid_f32, reference, mid_count);
+ oracle_err = cudaGetLastError();
+ }
+ if (oracle_err == cudaSuccess) {
+ oracle_err = cudaMemcpyAsync(
+ mid_f32, reference, mid_bytes,
+ cudaMemcpyDeviceToDevice, stream);
+ }
+ uint32_t mismatch_host = 0u;
+ if (oracle_err == cudaSuccess) {
+ oracle_err = cudaMemcpyAsync(
+ &mismatch_host, mismatch_device, sizeof(mismatch_host),
+ cudaMemcpyDeviceToHost, stream);
+ }
+ if (oracle_err == cudaSuccess) {
+ oracle_err = cudaStreamSynchronize(stream);
+ }
+ oracle_err = ds4_mmq_q8_fold_oracle_free(
+ fresh, "aligned-iq2-fresh", oracle_err);
+ oracle_err = ds4_mmq_q8_fold_oracle_free(
+ reference, "aligned-iq2-reference", oracle_err);
+ oracle_err = ds4_mmq_q8_fold_oracle_free(
+ mismatch_device, "aligned-iq2-mismatch", oracle_err);
+ if (oracle_err != cudaSuccess) {
+ (void)cudaGetLastError();
+ g_q8_fold_oracle_skips++;
+ fprintf(stderr, "%s: fold consumer oracle failed\n", tag);
+ return -3;
+ }
+ g_q8_fold_oracle_output_calls++;
+ g_q8_fold_oracle_aligned_iq2_calls++;
+ if (mismatch_host != 0u) {
+ g_q8_fold_oracle_output_mismatches++;
+ fprintf(stderr,
+ "ds4: CUDA Q8_1 fold oracle found an IQ2 MoE "
+ "consumer output mismatch; retained canonical "
+ "output\n");
+ }
+ return 0;
+ }
+ }
/* v0.4 V6: verify widths dedup expert overlap (see the dedup kernel's
* header comment). n_tokens==1 has no cross-token overlap and keeps
* the per-slot kernel; widths beyond the verify envelope likewise.
@@ -4925,14 +7491,80 @@ extern "C" int ds4_mmq_q8_0_dense_vec(
const void * W, const float * X, float * out,
int M, int N, int K, cudaStream_t stream) {
return ds4_mmq_dense_vec_impl(
- "ds4_mmq_q8_0_dense_vec", W, X, out, M, N, K, stream);
+ "ds4_mmq_q8_0_dense_vec", W, X, out, M, N, K,
+ /*q4_weight_device_resident=*/0, stream);
+}
+
+static int ds4_mmq_pointer_is_device_resident(
+ const void *ptr, int expected_device) {
+ if (!ptr || expected_device < 0) return 0;
+ cudaPointerAttributes attr = {};
+ const cudaError_t err = cudaPointerGetAttributes(&attr, ptr);
+ if (err != cudaSuccess) {
+ (void)cudaGetLastError();
+ return 0;
+ }
+#if defined(GGML_USE_HIP) && HIP_VERSION >= 60000000
+ return attr.type == cudaMemoryTypeDevice &&
+ attr.device == expected_device;
+#elif defined(GGML_USE_HIP)
+ return attr.memoryType == cudaMemoryTypeDevice &&
+ attr.device == expected_device;
+#elif CUDART_VERSION >= 10000
+ return attr.type == cudaMemoryTypeDevice &&
+ attr.device == expected_device;
+#else
+ return attr.memoryType == cudaMemoryTypeDevice &&
+ attr.device == expected_device;
+#endif
+}
+
+extern "C" int ds4_mmq_q4_K_dense_vec(
+ const void * W, const float * X, float * out,
+ int M, int N, int K, cudaStream_t stream) {
+ int weight_device_resident = 0;
+ /* Keep pointer introspection out of generic Q4 MMVQ traffic. It is only
+ * needed when the exact-shape persistent candidate could be considered;
+ * the full runtime uses the explicit provenance API below instead. */
+ if (M == 32768 && N == 1 && K == 1024) {
+ weight_device_resident = ds4_mmq_pointer_is_device_resident(
+ W, ggml_cuda_get_device());
+ }
+ return ds4_mmq_dense_vec_impl(
+ "ds4_mmq_q4_K_dense_vec", W, X, out, M, N, K,
+ weight_device_resident, stream);
+}
+
+extern "C" int ds4_mmq_q4_K_dense_vec_with_weight_residency(
+ const void * W, const float * X, float * out,
+ int M, int N, int K, int weight_device_resident,
+ cudaStream_t stream) {
+ return ds4_mmq_dense_vec_impl(
+ "ds4_mmq_q4_K_dense_vec_with_weight_residency",
+ W, X, out, M, N, K, weight_device_resident > 0, stream);
+}
+
+extern "C" int ds4_mmq_q4_K_grouped_vec(
+ const void *W, const float *X, float *out,
+ int M, int K, int n_groups, cudaStream_t stream) {
+ return ds4_mmq_q4_K_grouped_batch_vec_impl(
+ W, X, out, M, K, 1, n_groups, stream);
+}
+
+extern "C" int ds4_mmq_q4_K_grouped_batch_vec(
+ const void *W, const float *X, float *out,
+ int M, int K, int n_tokens, int n_groups, cudaStream_t stream) {
+ return ds4_mmq_q4_K_grouped_batch_vec_impl(
+ W, X, out, M, K, n_tokens, n_groups, stream);
}
extern "C" int ds4_mmq_q4_K_dense_pair_vec(
- const void *W0, const void *W1, const float *X,
- float *out0, float *out1, int M, int K, cudaStream_t stream) {
- return ds4_mmq_q4_K_dense_pair_vec_impl(
- W0, W1, X, out0, out1, M, K, stream);
+ const void * W0, const void * W1, const float * X,
+ float * out0, float * out1,
+ int M0, int M1, int N, int K, cudaStream_t stream) {
+ return ds4_mmq_dense_pair_vec_impl(
+ "ds4_mmq_q4_K_dense_pair_vec", W0, W1, X, out0, out1,
+ M0, M1, N, K, stream);
}
// Explicit instantiations. One per quant type the public API exposes.
diff --git a/cuda/mmq/ds4_mmq.h b/cuda/mmq/ds4_mmq.h
index a77a1c66cb..425ce62ef7 100644
--- a/cuda/mmq/ds4_mmq.h
+++ b/cuda/mmq/ds4_mmq.h
@@ -34,6 +34,35 @@ extern "C" {
int ds4_mmq_init(int device);
void ds4_mmq_set_aligned_q81_scratch(void *ptr, size_t bytes);
+// Producer-fold registry bridge implemented by the full CUDA runtime.
+// A hit returns the canonical Q8_1 sidecar for this exact activation pointer
+// and stream. It is valid only for single-token unpadded rows; registry slots
+// are refreshed by each producer layer and consumed once. The standalone MMQ
+// library provides a weak, fail-closed miss so its tests do not need to link
+// ds4_cuda.cu; full ds4 overrides it with the stream-aware implementation.
+int ds4_cuda_q8_fold_take_q81(
+ const void *src,
+ uint64_t in_dim,
+ cudaStream_t stream,
+ const void **q81);
+
+// Opt-in grouped-MMQ Q8_1 arena controlled by
+// DS4_CUDA_MMQ_Q81_PERSISTENT. Unset and =0 keep the stream-pool path.
+// cleanup drains the owner device before freeing and is safe across reinit;
+// report/counters expose host-dispatch coverage (graph replays excluded).
+int ds4_mmq_q81_persistent_cleanup(void);
+int ds4_mmq_q81_persistent_preflight_for_test(int device, size_t required);
+void ds4_mmq_q81_persistent_report(void);
+void ds4_mmq_q81_persistent_counters(
+ uint64_t *candidates,
+ uint64_t *uses,
+ uint64_t *hits,
+ uint64_t *pool_fallbacks,
+ uint64_t *allocations,
+ uint64_t *resizes,
+ size_t *arena_bytes,
+ size_t *high_water);
+
// Query whether ds4_mmq is willing to handle a given matmul. Returns
// 1 if mmq is faster than dequant+cublas for this shape on this device,
// 0 otherwise (caller should fall back to its existing dequant+cublas path).
@@ -159,6 +188,122 @@ int ds4_mmq_q4_K_dense(
int K,
cudaStream_t stream);
+#if !defined(GGML_USE_HIP)
+// CUDA benchmark/test boundary for separating activation quantization from
+// the Q4_K MMQ kernel. The scratch layout is canonical block_q8_1_mmq DS4
+// ([K/128][N]) plus a zeroed 128-column tail. These helpers never transfer
+// model weights and never synchronize the stream.
+size_t ds4_mmq_q4_K_q8_1_scratch_bytes(int N, int K);
+
+int ds4_mmq_q4_K_quantize_q8_1_for_test(
+ const float * X_f32,
+ void * q8_ds4,
+ size_t q8_bytes,
+ int N,
+ int K,
+ cudaStream_t stream);
+
+// Return non-zero only when the current device's canonical Q4_K MMQ picker
+// selects m128n128 for this activation-column count. Kernel A/B harnesses use
+// this to reject tail geometries whose Stream-K tile partition is different.
+int ds4_mmq_q4_K_dense_preq_reference_m128n128_for_test(int N);
+
+// Enqueue-only A/B arms over a caller-owned, already-quantized activation.
+// The reference may disable stream-K for a complete-K control; the 16-warp
+// candidate helper follows the production canonical stream-K/fixup policy.
+// Passing caller-owned reference fixup storage keeps pool alloc/free nodes out
+// of CUDA-event kernel benchmarks; null/zero retains the production pool.
+// Zero is success; nonzero is rejection/failure.
+int ds4_mmq_q4_K_dense_preq_reference_for_test(
+ const void * W_q4_K,
+ const void * q8_ds4,
+ size_t q8_bytes,
+ float * out_f32,
+ int M,
+ int N,
+ int K,
+ int use_stream_k,
+ void * stream_k_fixup,
+ size_t stream_k_fixup_bytes,
+ cudaStream_t stream);
+
+int ds4_mmq_q4_K_dense_preq_16warp_for_test(
+ const void * W_q4_K,
+ const void * q8_ds4,
+ size_t q8_bytes,
+ float * out_f32,
+ int M,
+ int N,
+ int K,
+ cudaStream_t stream);
+
+// Byte-parity boundary for the fixed [N][8][4096] grouped attention-A Q8_1
+// producer. use_specialized=0 launches the canonical strided quantizer;
+// nonzero launches the K4096/G8x2 candidate. Both write the same canonical
+// group-major block_q8_1_mmq DS4 payload and never synchronize the stream.
+size_t ds4_mmq_q4_K_grouped_q8_1_scratch_bytes_for_test(int N);
+
+int ds4_mmq_q4_K_grouped_quantize_q8_1_for_test(
+ const float * X_f32,
+ void * q8_ds4,
+ size_t q8_bytes,
+ int N,
+ int use_specialized,
+ cudaStream_t stream);
+#endif
+
+// Two dense Q4_K MMQ projections that share one token-tiled Q8_1
+// activation buffer. This is the prefill sibling of
+// ds4_mmq_q4_K_dense_pair_vec: N is not limited to the MMVQ batch ceiling,
+// M0 and M1 may differ, and each leg preserves ds4_mmq_q4_K_dense's
+// reduction and output layout. The two output ranges must be disjoint.
+// On CUDA, the opt-in 16-warp experiment selects each leg independently
+// (down to M=512) when its output-tile grid retains at least 80% SM-wave
+// efficiency; below canonical's whole-tile cutoff it mirrors canonical
+// stream-K partitioning and fixup. REQUIRE rejects the pair before allocation
+// unless both legs can use the candidate.
+// Shape/capability rejection returns DS4_MMQ_NOT_APPLICABLE before enqueue;
+// negative values report an attempted-path launch failure.
+int ds4_mmq_q4_K_dense_pair(
+ const void * W0_q4_K,
+ const void * W1_q4_K,
+ const float * X_f32,
+ float * out0_f32,
+ float * out1_f32,
+ int M0,
+ int M1,
+ int N,
+ int K,
+ cudaStream_t stream);
+
+// Prefill attention output-A with W=[groups][M][K],
+// X=[N][groups][K], and out=[N][groups][M]. It quantizes the strided source
+// in one launch and writes each group directly to the final token-major
+// layout, while preserving the established per-group MMQ reduction tree.
+int ds4_mmq_q4_K_grouped_dense(
+ const void * W_q4_K,
+ const float * X_f32,
+ float * out_f32,
+ int M,
+ int N,
+ int K,
+ int n_groups,
+ cudaStream_t stream);
+
+// Opt-in sibling of ds4_mmq_q4_K_grouped_dense that submits all groups in one
+// grid, with group selected by grid.z. Stream-k coordinates and fixup storage
+// are isolated per grid.z slice, preserving the reduction tree and output bits
+// of the established one-launch-per-group implementation.
+int ds4_mmq_q4_K_grouped_dense_single_grid(
+ const void * W_q4_K,
+ const float * X_f32,
+ float * out_f32,
+ int M,
+ int N,
+ int K,
+ int n_groups,
+ cudaStream_t stream);
+
int ds4_mmq_mxfp4_dense(
const void * W_mxfp4,
const float * X_f32,
@@ -344,6 +489,42 @@ int ds4_mmq_iq2_xxs_q2_K_moe_fused_soa(
float clamp,
cudaStream_t stream);
+/* Optional fused entries return this before enqueueing work when their
+ * capability/shape/scratch preflight cannot engage. Callers may safely retry
+ * a materialized fallback only for this result; zero is success and negative
+ * values may follow partial enqueue. */
+#define DS4_MMQ_NOT_APPLICABLE 1
+
+/* Raw-layout twin of ds4_mmq_iq2_xxs_q2_K_moe_fused_soa. This is the
+ * grouped SSD entry: callers may pass a compact expert table together with
+ * ids remapped into [0, n_experts). Gate/up/down use canonical GGUF block
+ * layouts while the routing map, activation quantize, and expert bounds are
+ * built only once for the complete fused pipeline. As with router top-k,
+ * ids for one token must be unique.
+ *
+ * Capability/shape failures return DS4_MMQ_NOT_APPLICABLE before enqueue.
+ * Once work has been submitted, failures are negative and must not be
+ * retried on the same stream as a materialized fallback. */
+int ds4_mmq_iq2_xxs_q2_K_moe_fused_raw(
+ const void * W_gate_raw,
+ const void * W_up_raw,
+ const void * W_down_raw,
+ const float * X_f32,
+ const int32_t * ids,
+ const float * router_weights,
+ float * gate_f32,
+ float * up_f32,
+ float * mid_f32,
+ float * down_f32,
+ int expert_mid_dim,
+ int expert_in_dim,
+ int out_dim,
+ int n_tokens,
+ int n_experts,
+ int n_expert_used,
+ float clamp,
+ cudaStream_t stream);
+
/* Aligned-artifact production fast path: gate/up stay in registers, weighted
* SwiGLU is quantized directly into down_q8_scratch, and only the pair-major
* down output is materialized. Caller-owned scratch keeps this hot path free
@@ -578,6 +759,11 @@ int ds4_mmq_q2_K_aligned_derepack(
// return non-zero so the caller can fall back to ds4_mmq_q8_0_dense_vec.
uint64_t ds4_mmq_q8_0_aligned_bytes(int M, int K);
+// Enable decode shapes validated on integrated sm_121 (GB10). The CUDA
+// backend sets this after device discovery; other devices retain the generic
+// aligned kernel. DS4_CUDA_NO_Q8_ALIGNED_PERSISTENT is the runtime rollback.
+void ds4_mmq_set_gb10_optimizations(int enabled);
+
int ds4_mmq_q8_0_aligned_dense_vec(
const void * W_aligned,
const float * X_f32,
@@ -872,13 +1058,110 @@ int ds4_mmq_q8_0_dense_vec(
int K,
cudaStream_t stream);
+int ds4_mmq_q4_K_dense_vec(
+ const void * W_q4_K,
+ const float * X_f32,
+ float * out_f32,
+ int M,
+ int N,
+ int K,
+ cudaStream_t stream);
+
+// Full-runtime form of ds4_mmq_q4_K_dense_vec. The CUDA model resolver
+// supplies weight_device_resident from allocation/cache provenance so the
+// exact K1024 persistent candidate can reject mapped-host/HMM weights without
+// issuing cudaPointerGetAttributes on every decode dispatch. Only a positive
+// hint admits that candidate; zero/negative provenance remains fail-closed and
+// canonical MMVQ stays available. The legacy entry
+// above performs its own pointer-attribute query for standalone callers and
+// benchmarks that allocate W with cudaMalloc.
+int ds4_mmq_q4_K_dense_vec_with_weight_residency(
+ const void * W_q4_K,
+ const float * X_f32,
+ float * out_f32,
+ int M,
+ int N,
+ int K,
+ int weight_device_resident,
+ cudaStream_t stream);
+
+// Exact grouped one-row Q4_K MMVQ for AProjQ4 attention-A on a single GB10.
+// W is [n_groups][M][K], X is [n_groups][K], and out is
+// [n_groups][M]. Each group retains the canonical dense_vec reduction tree;
+// only Q8_1 quantization and launch setup are shared. Returns
+// DS4_MMQ_NOT_APPLICABLE before enqueue when its GB10/scratch/shape gates do
+// not hold.
+int ds4_mmq_q4_K_grouped_vec(
+ const void * W_q4_K,
+ const float * X_f32,
+ float * out_f32,
+ int M,
+ int K,
+ int n_groups,
+ cudaStream_t stream);
+
+// Token-aware form of the exact grouped Q4_K entry above. X and out are
+// token-major: [n_tokens][n_groups][K] and
+// [n_tokens][n_groups][M]. Internally (token, group) is flattened into the
+// MMVQ channel dimension while ncols_dst remains one. This is deliberate:
+// every pair therefore retains the canonical one-row Q8_1 quantization,
+// Q4_K K partition, peer-warp fold and reduction tree. The GB10 path accepts
+// at most eight tokens and is opt-in with
+// DS4_CUDA_ENABLE_Q4_GROUPED_ATTN_A_BATCH=1. Either
+// DS4_CUDA_NO_Q4_GROUPED_ATTN_A_BATCH=1 or the existing grouped/global kill
+// switches disables it. DS4_MMQ_NOT_APPLICABLE is returned before enqueue
+// whenever a gate or scratch-capacity check fails.
+// The graph-level diagnostic
+// DS4_CUDA_REQUIRE_Q4_GROUPED_ATTN_A_BATCH=1 turns such ineligibility into a
+// visible failure when this attention-output path is reached.
+int ds4_mmq_q4_K_grouped_batch_vec(
+ const void * W_q4_K,
+ const float * X_f32,
+ float * out_f32,
+ int M,
+ int K,
+ int n_tokens,
+ int n_groups,
+ cudaStream_t stream);
+
+// On a single GB10, the exact AProjQ4 Q-b shape (M=32768, N=1, K=1024)
+// can opt into a persistent-CTA form with
+// DS4_CUDA_ENABLE_Q4_K1024_PERSISTENT=1. The rollback switch
+// DS4_CUDA_NO_Q4_K1024_PERSISTENT=1 is authoritative when both are set.
+// DS4_CUDA_REQUIRE_Q4_K1024_PERSISTENT=1 makes an unavailable exact-shape
+// dispatch fail before any CUDA work is enqueued instead of silently running
+// canonical MMVQ. DS4_CUDA_Q4_K1024_PERSISTENT_ORACLE=1 forces a candidate,
+// compares it bit-for-bit with canonical MMVQ, and retains canonical output;
+// run it with DS4_CUDA_DECODE_GRAPHS=0. Set
+// DS4_CUDA_Q4_K1024_PERSISTENT_STATS=1 for the atexit counter summary.
+// DS4_CUDA_NO_Q4_GB10_FAST=1 is the umbrella rollback for this and the
+// GB10 Q4 activation scratch. The candidate additionally requires W to be in
+// CUDA device allocation/cache storage; mapped host and managed/HMM pointers
+// retain canonical MMVQ. Other shapes and devices retain canonical MMVQ.
+void ds4_mmq_q4_K_k1024_persistent_counters(
+ uint64_t *candidates,
+ uint64_t *uses,
+ uint64_t *fallbacks,
+ uint64_t *require_failures,
+ uint64_t *oracle_calls,
+ uint64_t *oracle_mismatches,
+ uint64_t *oracle_skips);
+
+// Two independent dense Q4_K projections that share the canonical Q8_1
+// activation quantization. Each output is dispatched through the same MMVQ
+// entry as ds4_mmq_q4_K_dense_vec, so its reduction and output bits are
+// unchanged; M0 and M1 may differ (the DS4 Q-A/KV decode shape does).
+// Shape/capability rejection returns DS4_MMQ_NOT_APPLICABLE before enqueue;
+// negative values report an attempted-path launch failure.
int ds4_mmq_q4_K_dense_pair_vec(
const void * W0_q4_K,
const void * W1_q4_K,
const float * X_f32,
float * out0_f32,
float * out1_f32,
- int M,
+ int M0,
+ int M1,
+ int N,
int K,
cudaStream_t stream);
diff --git a/cuda/mmq/ds4_mmq_q4_16warp.cu b/cuda/mmq/ds4_mmq_q4_16warp.cu
new file mode 100644
index 0000000000..f1b22b4239
--- /dev/null
+++ b/cuda/mmq/ds4_mmq_q4_16warp.cu
@@ -0,0 +1,685 @@
+// SPDX-License-Identifier: MIT
+// Dense Q4_K x canonical-MMQ-Q8_1, m128n128, 16-warp experiment.
+//
+// The canonical Turing/Ampere MMQ kernel assigns two 16-row MMA minitiles to
+// each of eight warps at N=128. That leaves 64 F32 accumulators per thread
+// and can spill on shallow-K, wide-M prefill projections. This kernel keeps
+// the canonical shared representation and arithmetic but splits each 128-row
+// tile over four N-warps for each 32-row band. Each warp therefore owns
+// 32 rows x 32 columns and carries 32 accumulators. Keeping both 16-row A
+// fragments in one warp also preserves the canonical reuse of each B load.
+//
+// Numerical contract:
+// * canonical Q4_K nibble/scales/min unpack;
+// * canonical Q8_1 DS4 (half scale + half sum) activation blocks;
+// * identical ascending sequence of eight K32 folds per Q4_K block;
+// * the two canonical F32 accumulation statements are kept verbatim;
+// * direct tiling and canonical Stream-K/fixup reduction trees are both
+// available; the caller chooses explicitly at the enqueue boundary.
+
+#include "ds4_mmq_q4_16warp.cuh"
+
+#include "common.cuh"
+#include "mmq.cuh"
+
+#include
+#include
+
+namespace {
+namespace q4w16 {
+
+constexpr int kMTile = 128;
+constexpr int kNTile = 128;
+constexpr int kRowGroups = 4;
+constexpr int kColWarps = 4;
+constexpr int kWarps = kRowGroups * kColWarps;
+constexpr int kThreads = 32 * kWarps;
+constexpr int kRowFrag = 2;
+constexpr int kNFrag = kNTile / 8;
+constexpr int kNFragPerWarp = kNFrag / kColWarps;
+constexpr int kMetadataWarps = kMTile / 16;
+constexpr int kWeightStride = MMQ_MMA_TILE_X_K_Q8_1;
+constexpr int kYStrideInts = sizeof(block_q8_1_mmq) / sizeof(int);
+constexpr int kYChunks16 = sizeof(block_q8_1_mmq) / 16;
+constexpr size_t kTileElements = (size_t)kMTile * (size_t)kNTile;
+
+constexpr size_t kWeightTileBytes =
+ (size_t)kMTile * (size_t)kWeightStride * sizeof(int);
+constexpr size_t kYTileBytes =
+ (size_t)kNTile * sizeof(block_q8_1_mmq);
+constexpr size_t kSharedBytes = kWeightTileBytes + kYTileBytes;
+constexpr int kYTileVectors = (int)(kYTileBytes / sizeof(int4));
+
+static_assert(kWarps == 16, "Q4 16-warp decomposition changed");
+static_assert(kThreads == 512, "Q4 16-warp CTA must have 512 threads");
+static_assert(kRowGroups * kRowFrag * 16 == kMTile,
+ "Q4 split-N row coverage changed");
+static_assert(kNFragPerWarp == 4, "Q4 split-N fragment count changed");
+static_assert(kWeightStride == 76, "canonical Q4_K MMA row stride changed");
+static_assert(kYStrideInts == 36, "canonical Q8_1 DS4 stride changed");
+static_assert(kYChunks16 == 9, "canonical Q8_1 DS4 block size changed");
+static_assert(kYTileBytes % sizeof(int4) == 0,
+ "Q8_1 tile must support vectorized copies");
+static_assert(MMQ_ITER_K % QK_K == 0 && MMQ_ITER_K / QK_K == 1,
+ "Stream-K scheduler must restore canonical K alignment");
+static_assert(kSharedBytes == 57344, "Q4 16-warp shared-memory model changed");
+static_assert(kSharedBytes <= 99ull * 1024ull,
+ "Q4 16-warp kernel exceeds the intended opt-in shared limit");
+
+__device__ __forceinline__ int lane_id() {
+ return (int)threadIdx.x;
+}
+
+__device__ __forceinline__ int warp_id() {
+ return (int)threadIdx.y;
+}
+
+__device__ __forceinline__ int linear_tid() {
+ return (warp_id() << 5) | lane_id();
+}
+
+template
+__device__ __forceinline__ void load_weight_tile(
+ const block_q4_K * __restrict__ W,
+ int * __restrict__ tile,
+ int cta_row0,
+ int M,
+ int blocks_per_row,
+ int kb) {
+ int *x_qs = tile;
+ half2 *x_dm = reinterpret_cast(x_qs + 2 * MMQ_TILE_NE_K);
+ const int lane = lane_id();
+ const int warp = warp_id();
+
+ // Canonical load_tiles_q4_K nibble expansion. With 16 warps each warp
+ // visits eight rows; all 128 rows are covered exactly once.
+#pragma unroll
+ for (int row = warp; row < kMTile; row += kWarps) {
+ const int global_row = need_check && cta_row0 + row >= M
+ ? M - 1 : cta_row0 + row;
+ const block_q4_K *b =
+ W + (uint64_t)global_row * (uint64_t)blocks_per_row + kb;
+ const int qs0 = get_int_b4(b->qs, lane);
+ x_qs[row * kWeightStride + 16 * (lane / 8) + lane % 8 + 0] =
+ (qs0 >> 0) & 0x0F0F0F0F;
+ x_qs[row * kWeightStride + 16 * (lane / 8) + lane % 8 + 8] =
+ (qs0 >> 4) & 0x0F0F0F0F;
+ }
+
+ // The canonical loader uses 16 rows/warp and two lanes/row for metadata.
+ // Only eight warps participate, so the extra split-N warps do not
+ // duplicate any metadata row.
+ if (warp < kMetadataWarps) {
+ const int row = warp * 16 + lane / 2;
+ const int ksc = lane & 1;
+ const int global_row = need_check && cta_row0 + row >= M
+ ? M - 1 : cta_row0 + row;
+ const block_q4_K *b =
+ W + (uint64_t)global_row * (uint64_t)blocks_per_row + kb;
+ const int *scales = reinterpret_cast(b->scales);
+ const int sc32 = unpack_scales_q45_K(scales, ksc + 0);
+ const int m32 = unpack_scales_q45_K(scales, ksc + 2);
+ const uint8_t *sc8 = reinterpret_cast(&sc32);
+ const uint8_t *m8 = reinterpret_cast(&m32);
+ const half2 dm = b->dm * make_half2(1.0f, -1.0f);
+#pragma unroll
+ for (int l = 0; l < (int)sizeof(int); ++l) {
+ x_dm[row * kWeightStride + (int)sizeof(int) * ksc + l] =
+ dm * make_half2(sc8[l], m8[l]);
+ }
+ }
+}
+
+__device__ __forceinline__ void load_y_tile(
+ const block_q8_1_mmq * __restrict__ q8,
+ block_q8_1_mmq * __restrict__ tile,
+ int N,
+ int col0,
+ int k128) {
+ const int tid = linear_tid();
+
+ // The production selector admits complete N128 tiles. Copy those as one
+ // contiguous vector range, matching canonical MMQ's flat cooperative
+ // load. The former column-major mapping made every warp issue 144-byte-
+ // strided global loads; flattening turns each warp's accesses into adjacent
+ // 16-byte vectors while preserving the shared representation byte-for-byte.
+ if (col0 <= N - kNTile) {
+ const int4 * __restrict__ src = reinterpret_cast(
+ q8 + (uint64_t)k128 * (uint64_t)N + (uint64_t)col0);
+ int4 * __restrict__ dst = reinterpret_cast(tile);
+#pragma unroll
+ for (int vector = tid; vector < kYTileVectors;
+ vector += kThreads) {
+ dst[vector] = src[vector];
+ }
+ return;
+ }
+
+ // Keep the guarded per-column copy for the N tail accepted by the direct
+ // oracle hook. Production never takes this path.
+ constexpr int threads_per_col = kThreads / kNTile;
+ static_assert(threads_per_col == 4,
+ "Q8_1 DS4 copy mapping changed");
+ const int col = tid & (kNTile - 1);
+#pragma unroll
+ for (int chunk = tid >> 7; chunk < kYChunks16;
+ chunk += threads_per_col) {
+ int4 value = make_int4(0, 0, 0, 0);
+ if (col0 + col < N) {
+ const char *src = reinterpret_cast(
+ q8 + (uint64_t)k128 * (uint64_t)N + (uint64_t)(col0 + col));
+ value = *reinterpret_cast(src + chunk * 16);
+ }
+ char *dst = reinterpret_cast(tile + col);
+ *reinterpret_cast(dst + chunk * 16) = value;
+ }
+}
+
+template
+__device__ __forceinline__ void fold_y_half(
+ float (&acc)[kNFragPerWarp][kRowFrag][TileC::ne],
+ const int * __restrict__ x_tile,
+ const block_q8_1_mmq * __restrict__ y_tile,
+ int x_group0) {
+ static_assert(TileC::ne == 4,
+ "expected m16n8 s32 accumulator fragment");
+ const half2 *x_dm = reinterpret_cast(
+ x_tile + 2 * MMQ_TILE_NE_K);
+ const int warp = warp_id();
+ const int row0 = (warp / kColWarps) * (kRowFrag * 16);
+ const int nf0 = (warp % kColWarps) * kNFragPerWarp;
+ const int c0 = TileC::get_j(0);
+ const int c1 = TileC::get_j(1);
+ const int r0 = TileC::get_i(0);
+ const int r1 = TileC::get_i(2);
+
+ // K32-phased A loads keep only the two fragments needed for this 32-row
+ // band live, instead of canonical MMQ's eight K32 phases at once. Each
+ // B fragment is reused by both A fragments exactly as in canonical MMQ.
+ // For every output element folds remain in canonical group order 0..7.
+#pragma unroll
+ for (int local_group = 0; local_group < 4; ++local_group) {
+ const int x_group = x_group0 + local_group;
+ TileA A[kRowFrag];
+ float2 dmA[kRowFrag][2];
+#pragma unroll
+ for (int nr = 0; nr < kRowFrag; ++nr) {
+ const int frag_row0 = row0 + nr * 16;
+ ggml_cuda_mma::load_ldmatrix(
+ A[nr],
+ x_tile + frag_row0 * kWeightStride + x_group * QI8_1,
+ kWeightStride);
+ dmA[nr][0] = __half22float2(
+ x_dm[(frag_row0 + r0) * kWeightStride + x_group]);
+ dmA[nr][1] = __half22float2(
+ x_dm[(frag_row0 + r1) * kWeightStride + x_group]);
+ }
+
+#pragma unroll
+ for (int nf = 0; nf < kNFragPerWarp; ++nf) {
+ const int col_base = (nf0 + nf) * 8;
+ TileB B;
+ const int *b_qs = reinterpret_cast(
+ &y_tile[col_base].qs[local_group * QK8_1]);
+ // Canonical NVIDIA MMQ deliberately uses load_generic for B.
+ ggml_cuda_mma::load_generic(B, b_qs, kYStrideInts);
+
+ const float2 dsB[2] = {
+ __half22float2(y_tile[col_base + c0].ds4[local_group]),
+ __half22float2(y_tile[col_base + c1].ds4[local_group]),
+ };
+
+ // These are the canonical vec_dot_q8_1_q8_1_mma accumulation
+ // statements. Do not fuse the min correction into the dot fold
+ // or change their order: parity depends on this reduction tree.
+#pragma unroll
+ for (int nr = 0; nr < kRowFrag; ++nr) {
+ TileC C;
+ ggml_cuda_mma::mma(C, A[nr], B);
+#pragma unroll
+ for (int l = 0; l < TileC::ne; ++l) {
+ acc[nf][nr][l] +=
+ dmA[nr][l / 2].x * dsB[l % 2].x * C.x[l];
+ acc[nf][nr][l] +=
+ dmA[nr][l / 2].y * dsB[l % 2].y;
+ }
+ }
+ }
+ }
+}
+
+template
+__device__ __forceinline__ void process_tile_range(
+ const block_q4_K * __restrict__ W,
+ const block_q8_1_mmq * __restrict__ q8,
+ float * __restrict__ out,
+ float * __restrict__ tmp_fixup,
+ int M,
+ int N,
+ int K,
+ int it,
+ int jt,
+ int kb_start,
+ int kb_stop,
+ int * __restrict__ x_tile,
+ block_q8_1_mmq * __restrict__ y_tile) {
+#if defined(TURING_MMA_AVAILABLE)
+ using tile_A = ggml_cuda_mma::tile<16, 8, int>;
+ using tile_B = ggml_cuda_mma::tile<8, 8, int>;
+ using tile_C = ggml_cuda_mma::tile<16, 8, int>;
+
+ const int cta_row0 = it * kMTile;
+ const int col0 = jt * kNTile;
+ const int blocks_per_row = K / QK_K;
+ float acc[kNFragPerWarp][kRowFrag][tile_C::ne] = {};
+
+ for (int kb = kb_start; kb < kb_stop; ++kb) {
+ load_weight_tile(
+ W, x_tile, cta_row0, M, blocks_per_row, kb);
+ load_y_tile(q8, y_tile, N, col0, 2 * kb + 0);
+ __syncthreads();
+
+ fold_y_half(acc, x_tile, y_tile, 0);
+ __syncthreads();
+
+ load_y_tile(q8, y_tile, N, col0, 2 * kb + 1);
+ __syncthreads();
+
+ fold_y_half(acc, x_tile, y_tile, 4);
+ // Protect both shared tiles before the following K256 iteration.
+ __syncthreads();
+ }
+
+ const int warp = warp_id();
+ const int out_row0 =
+ cta_row0 + (warp / kColWarps) * (kRowFrag * 16);
+ const int out_col0 =
+ col0 + (warp % kColWarps) * (kNFragPerWarp * 8);
+#pragma unroll
+ for (int nf = 0; nf < kNFragPerWarp; ++nf) {
+#pragma unroll
+ for (int nr = 0; nr < kRowFrag; ++nr) {
+#pragma unroll
+ for (int l = 0; l < tile_C::ne; ++l) {
+ const int row = out_row0 + nr * 16 + tile_C::get_i(l);
+ const int col = out_col0 + nf * 8 + tile_C::get_j(l);
+ if constexpr (to_fixup) {
+ // Canonical MMQ always materializes a complete 128x128
+ // final-partial tile in block-private storage. Tail rows
+ // and columns are masked only when the fixup publishes it.
+ tmp_fixup[(size_t)blockIdx.x * kTileElements +
+ (size_t)(col - col0) * kMTile +
+ (size_t)(row - cta_row0)] = acc[nf][nr][l];
+ } else if (row < M && col < N) {
+ float value = acc[nf][nr][l];
+ // A leading Stream-K partial is deliberately left
+ // unsanitized. Canonical fixup sanitizes only after the
+ // complete reduction tree has been reconstructed.
+ if (kb_start == 0 && kb_stop == blocks_per_row &&
+ !isfinite(value)) {
+ value = 0.0f;
+ }
+ out[(uint64_t)col * (uint64_t)M + (uint64_t)row] =
+ value;
+ }
+ }
+ }
+ }
+#else
+ GGML_UNUSED_VARS(W, q8, out, tmp_fixup, M, N, K, it, jt,
+ kb_start, kb_stop);
+ GGML_UNUSED_VARS(x_tile, y_tile);
+ NO_DEVICE_CODE;
+#endif
+}
+
+__global__ __launch_bounds__(kThreads, 1)
+void dense_q4_16warp_kernel(
+ const block_q4_K * __restrict__ W,
+ const block_q8_1_mmq * __restrict__ q8,
+ float * __restrict__ out,
+ int M,
+ int N,
+ int K) {
+#if defined(TURING_MMA_AVAILABLE)
+ extern __shared__ __align__(16) unsigned char dynamic_smem[];
+ int *x_tile = reinterpret_cast(dynamic_smem);
+ block_q8_1_mmq *y_tile = reinterpret_cast(
+ dynamic_smem + kWeightTileBytes);
+ const int it = (int)blockIdx.x;
+ const int jt = (int)blockIdx.y;
+ process_tile_range(
+ W, q8, out, nullptr, M, N, K, it, jt,
+ 0, K / QK_K, x_tile, y_tile);
+#else
+ GGML_UNUSED_VARS(W, q8, out, M, N, K);
+ NO_DEVICE_CODE;
+#endif
+}
+
+// The integer partition and flattened tile order intentionally mirror
+// mul_mat_q. One CTA may finish a leading split
+// tile, own zero or more complete tiles, and publish one trailing prefix for
+// canonical mul_mat_q_stream_k_fixup.
+template
+__global__ __launch_bounds__(kThreads, 1)
+void dense_q4_16warp_streamk_kernel(
+ const block_q4_K * __restrict__ W,
+ const block_q8_1_mmq * __restrict__ q8,
+ float * __restrict__ out,
+ float * __restrict__ tmp_fixup,
+ int M,
+ int N,
+ int K) {
+#if defined(TURING_MMA_AVAILABLE)
+ extern __shared__ __align__(16) unsigned char dynamic_smem[];
+ int *x_tile = reinterpret_cast(dynamic_smem);
+ block_q8_1_mmq *y_tile = reinterpret_cast(
+ dynamic_smem + kWeightTileBytes);
+
+ // Convert before adding the tile bias so syntactically valid INT_MAX
+ // dimensions cannot overflow signed arithmetic in device code.
+ const int nty = (int)(((unsigned)M + (unsigned)kMTile - 1u) /
+ (unsigned)kMTile);
+ const int ntx = (int)(((unsigned)N + (unsigned)kNTile - 1u) /
+ (unsigned)kNTile);
+ const int blocks_per_row = K / QK_K;
+ const int64_t total = (int64_t)nty * ntx * blocks_per_row;
+
+ int kbc = (int)((int64_t)blockIdx.x * total / gridDim.x);
+ const int kbc_stop =
+ (int)((int64_t)(blockIdx.x + 1) * total / gridDim.x);
+
+ int kb_start = kbc % blocks_per_row;
+ int kb_stop = min(blocks_per_row, kb_start + kbc_stop - kbc);
+ while (kbc < kbc_stop && kb_stop == blocks_per_row) {
+ const int tile = kbc / blocks_per_row;
+ const int jt = tile % ntx;
+ const int it = tile / ntx;
+ process_tile_range(
+ W, q8, out, tmp_fixup, M, N, K, it, jt,
+ kb_start, kb_stop, x_tile, y_tile);
+
+ kbc += blocks_per_row;
+ kbc -= kbc % blocks_per_row;
+ kb_start = 0;
+ kb_stop = min(blocks_per_row, kbc_stop - kbc);
+ }
+
+ if (kbc >= kbc_stop) {
+ return;
+ }
+
+ const int tile = kbc / blocks_per_row;
+ const int jt = tile % ntx;
+ const int it = tile / ntx;
+ process_tile_range(
+ W, q8, out, tmp_fixup, M, N, K, it, jt,
+ kb_start, kb_stop, x_tile, y_tile);
+#else
+ GGML_UNUSED_VARS(W, q8, out, tmp_fixup, M, N, K);
+ NO_DEVICE_CODE;
+#endif
+}
+
+struct streamk_schedule {
+ unsigned nty;
+ unsigned ntx;
+ unsigned ntiles;
+ unsigned grid_x;
+ bool fixup_needed;
+ size_t scratch_bytes;
+};
+
+static bool make_streamk_schedule(
+ int M, int N, int nsm, streamk_schedule *schedule) {
+ if (M <= 0 || N <= 0 || nsm <= 0 || schedule == nullptr) {
+ return false;
+ }
+
+ const uint64_t nty64 =
+ ((uint64_t)(unsigned)M + (uint64_t)kMTile - 1u) / kMTile;
+ const uint64_t ntx64 =
+ ((uint64_t)(unsigned)N + (uint64_t)kNTile - 1u) / kNTile;
+ if (nty64 == 0 || ntx64 == 0 || nty64 > UINT32_MAX ||
+ ntx64 > UINT32_MAX || nty64 > UINT32_MAX / ntx64) {
+ return false;
+ }
+
+ const uint64_t ntiles64 = nty64 * ntx64;
+ const uint64_t nsm64 = (uint64_t)(unsigned)nsm;
+ const uint64_t nwaves = (ntiles64 + nsm64 - 1u) / nsm64;
+ if (nwaves == 0 || nsm64 > UINT64_MAX / nwaves) {
+ return false;
+ }
+ const uint64_t wave_slots = nsm64 * nwaves;
+ const uint64_t efficiency = 100u * ntiles64 / wave_slots;
+ const uint64_t grid64 = efficiency >= 90u ? ntiles64 : nsm64;
+ if (grid64 == 0 || grid64 > UINT32_MAX) {
+ return false;
+ }
+
+ const bool fixup_needed = ntiles64 % grid64 != 0;
+ size_t bytes = 0;
+ if (fixup_needed) {
+ if (grid64 > SIZE_MAX / kTileElements / sizeof(float)) {
+ return false;
+ }
+ bytes = (size_t)grid64 * kTileElements * sizeof(float);
+ }
+
+ schedule->nty = (unsigned)nty64;
+ schedule->ntx = (unsigned)ntx64;
+ schedule->ntiles = (unsigned)ntiles64;
+ schedule->grid_x = (unsigned)grid64;
+ schedule->fixup_needed = fixup_needed;
+ schedule->scratch_bytes = bytes;
+ return true;
+}
+
+} // namespace q4w16
+} // anonymous namespace
+
+extern "C" int ds4_mmq_q4_K_dense_16warp_available(int cc) {
+ return GGML_CUDA_CC_IS_NVIDIA(cc) &&
+ ggml_cuda_highest_compiled_arch(cc) >= GGML_CUDA_CC_AMPERE;
+}
+
+extern "C" int ds4_mmq_q4_K_dense_16warp_supported(
+ int cc, int M, int N, int K) {
+ if (!ds4_mmq_q4_K_dense_16warp_available(cc)) {
+ return 0;
+ }
+ return M >= 1024 && (M % q4w16::kMTile) == 0 &&
+ N >= 512 && (N % q4w16::kNTile) == 0 &&
+ K >= 1024 && K <= 8192 && (K % QK_K) == 0;
+}
+
+extern "C" int ds4_mmq_q4_K_dense_16warp_prepare(void) {
+ using namespace q4w16;
+ int device = -1;
+ cudaError_t err = cudaGetDevice(&device);
+ if (err != cudaSuccess) {
+ return -1;
+ }
+ cudaDeviceProp prop;
+ err = cudaGetDeviceProperties(&prop, device);
+ if (err != cudaSuccess || prop.major < 8 ||
+ prop.maxThreadsPerBlock < kThreads) {
+ return -2;
+ }
+#if CUDART_VERSION >= 9000
+ if ((size_t)prop.sharedMemPerBlockOptin < kSharedBytes) {
+ return -2;
+ }
+#else
+ if ((size_t)prop.sharedMemPerBlock < kSharedBytes) {
+ return -2;
+ }
+#endif
+ err = cudaFuncSetAttribute(
+ dense_q4_16warp_kernel,
+ cudaFuncAttributeMaxDynamicSharedMemorySize,
+ (int)kSharedBytes);
+ if (err != cudaSuccess) {
+ return -3;
+ }
+ err = cudaFuncSetAttribute(
+ dense_q4_16warp_streamk_kernel,
+ cudaFuncAttributeMaxDynamicSharedMemorySize,
+ (int)kSharedBytes);
+ if (err != cudaSuccess) {
+ return -3;
+ }
+ err = cudaFuncSetAttribute(
+ dense_q4_16warp_streamk_kernel,
+ cudaFuncAttributeMaxDynamicSharedMemorySize,
+ (int)kSharedBytes);
+ return err == cudaSuccess ? 0 : -3;
+}
+
+extern "C" int ds4_mmq_q4_K_dense_16warp_enqueue(
+ const void *W,
+ const void *q8_ds4,
+ float *out,
+ int M,
+ int N,
+ int K,
+ cudaStream_t stream) {
+ using namespace q4w16;
+ if (!W || !q8_ds4 || !out || M <= 0 || N <= 0 || K <= 0 ||
+ (M % kMTile) != 0 || (K % QK_K) != 0) {
+ return -1;
+ }
+
+ // Convert before adding the tile bias: N is a positive signed int, but
+ // N + 127 would otherwise overflow for a (syntactically valid) INT_MAX
+ // direct-enqueue request.
+ const unsigned grid_y =
+ ((unsigned)N + (unsigned)kNTile - 1u) / (unsigned)kNTile;
+ // CUDA guarantees only 65535 blocks on y/z. Production shapes are far
+ // below this, but reject oversized raw-enqueue requests before launch.
+ if (grid_y > 65535u) {
+ return -1;
+ }
+ const dim3 grid((unsigned)M / (unsigned)kMTile, grid_y, 1);
+ const dim3 block(32, kWarps, 1);
+ dense_q4_16warp_kernel<<>>(
+ static_cast(W),
+ static_cast(q8_ds4),
+ out, M, N, K);
+ const cudaError_t err = cudaGetLastError();
+ return err == cudaSuccess ? 0 : -4;
+}
+
+extern "C" size_t ds4_mmq_q4_K_dense_16warp_streamk_scratch_bytes(
+ int M, int N, int nsm) {
+ q4w16::streamk_schedule schedule;
+ return q4w16::make_streamk_schedule(M, N, nsm, &schedule)
+ ? schedule.scratch_bytes : 0;
+}
+
+extern "C" int ds4_mmq_q4_K_dense_16warp_streamk_enqueue(
+ const void *W,
+ const void *q8_ds4,
+ float *out,
+ void *scratch,
+ size_t scratch_bytes,
+ int M,
+ int N,
+ int K,
+ int nsm,
+ cudaStream_t stream) {
+ using namespace q4w16;
+ if (!W || !q8_ds4 || !out || M <= 0 || N <= 0 || K <= 0 ||
+ nsm <= 0 || (K % QK_K) != 0) {
+ return -1;
+ }
+
+ streamk_schedule schedule;
+ if (!make_streamk_schedule(M, N, nsm, &schedule)) {
+ return -1;
+ }
+
+ const uint64_t blocks_per_row = (uint64_t)(unsigned)K / QK_K;
+ const uint64_t total = (uint64_t)schedule.ntiles * blocks_per_row;
+ // Match the canonical launcher's invariant: the device scheduler stores
+ // flattened K-block coordinates in signed int variables.
+ if (blocks_per_row == 0 || total >= (1ull << 30)) {
+ return -1;
+ }
+
+ // Canonical Stream-K degenerates to one complete-K CTA per output tile
+ // at high whole-tile efficiency. Preserve that policy while using the
+ // cheaper 2-D direct launch for the aligned production shapes: it avoids
+ // per-CTA flattened-index divisions and needs neither scratch nor fixup.
+ if (!schedule.fixup_needed && (M % kMTile) == 0) {
+ return ds4_mmq_q4_K_dense_16warp_enqueue(
+ W, q8_ds4, out, M, N, K, stream);
+ }
+
+ if (schedule.fixup_needed) {
+ if (!scratch || scratch_bytes < schedule.scratch_bytes ||
+ ((uintptr_t)scratch % alignof(float)) != 0) {
+ return -1;
+ }
+ const cudaError_t memset_err = cudaMemsetAsync(
+ scratch, 0, schedule.scratch_bytes, stream);
+ if (memset_err != cudaSuccess) {
+ return -2;
+ }
+ }
+
+ const dim3 grid(schedule.grid_x, 1, 1);
+ const dim3 block(32, kWarps, 1);
+ float *tmp_fixup = schedule.fixup_needed
+ ? static_cast(scratch) : nullptr;
+ if ((M % kMTile) == 0) {
+ dense_q4_16warp_streamk_kernel
+ <<>>(
+ static_cast(W),
+ static_cast(q8_ds4),
+ out, tmp_fixup, M, N, K);
+ } else {
+ dense_q4_16warp_streamk_kernel
+ <<>>(
+ static_cast(W),
+ static_cast(q8_ds4),
+ out, tmp_fixup, M, N, K);
+ }
+ cudaError_t err = cudaGetLastError();
+ if (err != cudaSuccess) {
+ return -4;
+ }
+
+ if (!schedule.fixup_needed) {
+ return 0;
+ }
+
+ const uint3 blocks_per_ne00_fd = init_fastdiv_values(blocks_per_row);
+ const uint3 one_fd = init_fastdiv_values(1);
+ const uint3 ntx_fd = init_fastdiv_values(schedule.ntx);
+ const dim3 fixup_grid(schedule.grid_x, kMTile / 32, 1);
+ const dim3 fixup_block(32, 4, 1);
+ if ((M % kMTile) == 0) {
+ constexpr bool need_check = false;
+ mul_mat_q_stream_k_fixup<
+ GGML_TYPE_Q4_K, kNTile, need_check, false>
+ <<>>(
+ /*ids_dst=*/nullptr, /*expert_bounds=*/nullptr, out,
+ tmp_fixup, blocks_per_ne00_fd, M, N, M,
+ one_fd, /*stride_channel_dst=*/0,
+ one_fd, /*stride_sample_dst=*/0, ntx_fd);
+ } else {
+ constexpr bool need_check = true;
+ mul_mat_q_stream_k_fixup<
+ GGML_TYPE_Q4_K, kNTile, need_check, false>
+ <<>>(
+ /*ids_dst=*/nullptr, /*expert_bounds=*/nullptr, out,
+ tmp_fixup, blocks_per_ne00_fd, M, N, M,
+ one_fd, /*stride_channel_dst=*/0,
+ one_fd, /*stride_sample_dst=*/0, ntx_fd);
+ }
+ err = cudaGetLastError();
+ return err == cudaSuccess ? 0 : -5;
+}
diff --git a/cuda/mmq/ds4_mmq_q4_16warp.cuh b/cuda/mmq/ds4_mmq_q4_16warp.cuh
new file mode 100644
index 0000000000..2434330a25
--- /dev/null
+++ b/cuda/mmq/ds4_mmq_q4_16warp.cuh
@@ -0,0 +1,94 @@
+// SPDX-License-Identifier: MIT
+// Internal CUDA Q4_K dense-prefill experiment. This header intentionally
+// exposes only the pre-quantized enqueue boundary; allocation and Q8_1
+// quantization stay owned by ds4_mmq.cu.
+
+#pragma once
+
+#if defined(GGML_USE_HIP)
+#include "vendors/hip.h"
+#else
+#include
+#endif
+
+#include
+
+#if !defined(GGML_USE_HIP)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// Returns non-zero when the requested CUDA compute capability can execute
+// the m128n128, 16-warp integer-MMA kernel.
+int ds4_mmq_q4_K_dense_16warp_available(int cc);
+
+// Conservative standalone production admission gate. Availability and shape
+// are both checked; it admits M>=1024 and only complete 128x128 output tiles.
+// The K envelope covers the production 8192-wide attention output projection.
+// The dispatcher separately enforces the m128n128 reference selector and its
+// candidate-grid efficiency gate. A false result must fall back. The pair
+// dispatcher has a separate per-leg M>=512 gate.
+int ds4_mmq_q4_K_dense_16warp_supported(int cc, int M, int N, int K);
+
+// Opt in the 56 KiB dynamic-shared-memory launch on the current device.
+// Call once during device initialization (and once again after switching to a
+// different device) before enqueue. The operation is idempotent.
+int ds4_mmq_q4_K_dense_16warp_prepare(void);
+
+// Enqueue-only dense Q4_K GEMM over an already resident canonical MMQ Q8_1
+// activation buffer.
+//
+// W raw row-major block_q4_K, [M][K/256]
+// q8_ds4 block_q8_1_mmq DS4 (half scale + half sum), [K/128][N]
+// out column-major float, [N][M]
+//
+// ds4_mmq_q4_K_dense_16warp_prepare must have succeeded on the current device.
+// The kernel owns the complete K reduction for every output tile: it never
+// uses stream-K and writes every valid output exactly once. No allocation,
+// memset, quantization, synchronization, or host/device copy is performed.
+// Returns 0 after a successful enqueue and a negative value otherwise.
+int ds4_mmq_q4_K_dense_16warp_enqueue(
+ const void * W,
+ const void * q8_ds4,
+ float * out,
+ int M,
+ int N,
+ int K,
+ cudaStream_t stream);
+
+// Return the caller-owned fixup storage required by the canonical Stream-K
+// partition for this dense MxN output shape and SM count. Zero means either
+// that no fixup is necessary (the selected grid owns complete tiles) or that
+// the arguments/size cannot be represented; enqueue repeats all validation.
+// The storage, when non-zero, is a byte buffer and need only remain valid until
+// the work already enqueued on `stream` has completed.
+size_t ds4_mmq_q4_K_dense_16warp_streamk_scratch_bytes(
+ int M,
+ int N,
+ int nsm);
+
+// Enqueue the same 16-warp arithmetic using canonical CUDA MMQ Stream-K
+// scheduling and its exact Q4_K fixup reduction tree. W, q8_ds4 and out use
+// the layouts documented above. `scratch` must provide at least the size
+// returned by ds4_mmq_q4_K_dense_16warp_streamk_scratch_bytes; it may be null
+// when that function returns zero. The routine performs only asynchronous
+// memset/kernel operations and does not allocate or synchronize.
+// ds4_mmq_q4_K_dense_16warp_prepare must have succeeded on the current device.
+int ds4_mmq_q4_K_dense_16warp_streamk_enqueue(
+ const void * W,
+ const void * q8_ds4,
+ float * out,
+ void * scratch,
+ size_t scratch_bytes,
+ int M,
+ int N,
+ int K,
+ int nsm,
+ cudaStream_t stream);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // !defined(GGML_USE_HIP)
diff --git a/cuda/mmq/mmq.cuh b/cuda/mmq/mmq.cuh
index 0f22964d61..ad78a951ea 100644
--- a/cuda/mmq/mmq.cuh
+++ b/cuda/mmq/mmq.cuh
@@ -3663,6 +3663,7 @@ static __device__ __forceinline__ void mul_mat_q_process_tile(
const int * __restrict__ ids_dst, float * __restrict__ dst, float * __restrict__ tmp_fixup,
const int stride_row_x, const int ncols_y, const int stride_col_dst,
const int tile_x_max_i, const int tile_y_max_j, const int kb0_start, const int kb0_stop,
+ const int blocks_per_ne00_total,
const char * __restrict__ x_soa, const int64_t soa_blocks) {
constexpr int warp_size = ggml_cuda_get_physical_warp_size();
@@ -3756,6 +3757,22 @@ static __device__ __forceinline__ void mul_mat_q_process_tile(
__syncthreads();
}
+ /* AProjQ4 dense prefill used to run a separate full-output sanitize
+ * kernel after every MMQ. Preserve that contract in the producer
+ * epilogue instead. A stream-K block may publish only the leading
+ * partial of a split tile; sanitizing that partial would change the
+ * eventual sum, so only a block that owns the complete K range may fold
+ * non-finite values here. Split tiles are handled after their final
+ * accumulation in mul_mat_q_stream_k_fixup below. */
+ if constexpr (type == GGML_TYPE_Q4_K && !fixup) {
+ if (kb0_start == 0 && kb0_stop == blocks_per_ne00_total) {
+#pragma unroll
+ for (int l = 0; l < mmq_x*mmq_y / (nwarps*warp_size); ++l) {
+ if (!isfinite(sum[l])) sum[l] = 0.0f;
+ }
+ }
+ }
+
if (fixup) {
write_back(sum, nullptr, tmp_fixup + blockIdx.x*(mmq_x*mmq_y), mmq_y, mmq_y, mmq_x);
} else {
@@ -3766,7 +3783,7 @@ static __device__ __forceinline__ void mul_mat_q_process_tile(
// The mul_mat_q kernel implements "stream-k" work partitioning as described in https://arxiv.org/abs/2301.03598
-template
+template
#if defined(GGML_USE_HIP)
#if defined(RDNA4) || defined(RDNA3) || defined(RDNA2) || defined(CDNA) || defined(GCN)
__launch_bounds__(ggml_cuda_get_physical_warp_size()*mmq_get_nwarps_device(), 2)
@@ -3800,6 +3817,22 @@ static __global__ void mul_mat_q(
const uint32_t nty = (nrows_x + mmq_y - 1) / mmq_y; // Number of tiles y
+ /* Dense grouped dispatch: grid.z is an outer channel selector while each
+ * z-slice keeps the exact grid.x / stream-k partition of the former
+ * one-launch-per-channel path. Offset the three channel bases here and
+ * let the ordinary tile code see a single logical channel. This preserves
+ * each output's K reduction tree while removing the host launch loop. */
+ const int grid_z_channel = grid_z_channels ? (int)blockIdx.z : 0;
+ const int grid_z_offset_x = grid_z_channels
+ ? grid_z_channel * stride_channel_x : 0;
+ if constexpr (grid_z_channels) {
+ y += (int64_t)grid_z_channel * stride_channel_y;
+ dst += (int64_t)grid_z_channel * stride_channel_dst;
+ if (tmp_fixup != nullptr) {
+ tmp_fixup += (int64_t)grid_z_channel * gridDim.x * mmq_x * mmq_y;
+ }
+ }
+
// Initialize the ids for writing back data with just the index.
// For regular matrix multiplications this is never changed.
// For MoE the correct indices are loaded from ids_dst.
@@ -3819,9 +3852,13 @@ static __global__ void mul_mat_q(
// On non-CDNA AMD or old CUDA the performance with stream-k was worse, use conventional tiling instead:
#if (defined(GGML_USE_HIP) && !defined(CDNA)) || __CUDA_ARCH__ < GGML_CUDA_CC_VOLTA
{
- const uint2 tmp2 = fast_div_modulo(blockIdx.z, nchannels_y);
- const int wt = tmp2.x;
- const int zt = tmp2.y;
+ int wt = 0;
+ int zt = 0;
+ if constexpr (!grid_z_channels) {
+ const uint2 tmp2 = fast_div_modulo(blockIdx.z, nchannels_y);
+ wt = tmp2.x;
+ zt = tmp2.y;
+ }
const int jt = blockIdx.y;
const int it = blockIdx.x;
@@ -3870,12 +3907,13 @@ static __global__ void mul_mat_q(
const int tile_x_max_i = nrows_x - it*mmq_y - 1;
const int tile_y_max_j = col_diff - jt*mmq_x - 1;
- const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + fastdiv(zt, channel_ratio)*stride_channel_x + it*mmq_y*stride_row_x;
+ const int offset_x = grid_z_offset_x + fastdiv(wt, sample_ratio)*stride_sample_x + fastdiv(zt, channel_ratio)*stride_channel_x + it*mmq_y*stride_row_x;
constexpr bool fixup = false;
mul_mat_q_process_tile
(x, offset_x, y + offset_y, ids_dst_shared, dst + offset_dst, tmp_fixup, stride_row_x, ncols_y, stride_col_dst,
- tile_x_max_i, tile_y_max_j, 0, blocks_per_ne00.z, x_soa, soa_blocks);
+ tile_x_max_i, tile_y_max_j, 0, blocks_per_ne00.z,
+ blocks_per_ne00.z, x_soa, soa_blocks);
return;
}
#endif // (defined(GGML_USE_HIP) && !defined(CDNA4) && !defined(CDNA3)) || __CUDA_ARCH__ < GGML_CUDA_CC_VOLTA
@@ -3956,12 +3994,13 @@ static __global__ void mul_mat_q(
const int tile_x_max_i = nrows_x - it*mmq_y - 1;
const int tile_y_max_j = col_diff - jt*mmq_x - 1;
- const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + fastdiv(zt, channel_ratio)*stride_channel_x + it*mmq_y*stride_row_x;
+ const int offset_x = grid_z_offset_x + fastdiv(wt, sample_ratio)*stride_sample_x + fastdiv(zt, channel_ratio)*stride_channel_x + it*mmq_y*stride_row_x;
constexpr bool fixup = false; // All but (potentially) the last iterations write their data to dst rather than the fixup buffer.
mul_mat_q_process_tile
(x, offset_x, y + offset_y, ids_dst_shared, dst + offset_dst, tmp_fixup, stride_row_x, ncols_y, stride_col_dst,
- tile_x_max_i, tile_y_max_j, kb0_start, kb0_stop, x_soa, soa_blocks);
+ tile_x_max_i, tile_y_max_j, kb0_start, kb0_stop,
+ blocks_per_ne00.z, x_soa, soa_blocks);
kbc += blocks_per_ne00.z;
kbc -= fastmodulo(kbc, blocks_per_ne00);
@@ -4025,15 +4064,16 @@ static __global__ void mul_mat_q(
const int tile_x_max_i = nrows_x - it*mmq_y - 1;
const int tile_y_max_j = col_diff - jt*mmq_x - 1;
- const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + fastdiv(zt, channel_ratio)*stride_channel_x + it*mmq_y*stride_row_x;
+ const int offset_x = grid_z_offset_x + fastdiv(wt, sample_ratio)*stride_sample_x + fastdiv(zt, channel_ratio)*stride_channel_x + it*mmq_y*stride_row_x;
constexpr bool fixup = true; // Last index writes its data to fixup buffer to avoid data races with other blocks.
mul_mat_q_process_tile
(x, offset_x, y + offset_y, ids_dst_shared, dst + offset_dst, tmp_fixup, stride_row_x, ncols_y, stride_col_dst,
- tile_x_max_i, tile_y_max_j, kb0_start, kb0_stop, x_soa, soa_blocks);
+ tile_x_max_i, tile_y_max_j, kb0_start, kb0_stop,
+ blocks_per_ne00.z, x_soa, soa_blocks);
}
-template
+template
__launch_bounds__(ggml_cuda_get_physical_warp_size()*mmq_get_nwarps_device()/2, 1)
static __global__ void mul_mat_q_stream_k_fixup(
const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
@@ -4048,6 +4088,11 @@ static __global__ void mul_mat_q_stream_k_fixup(
constexpr int nwarps = mmq_get_nwarps_device()/2;
constexpr int warp_size = ggml_cuda_get_physical_warp_size();
+ if constexpr (grid_z_channels) {
+ dst += (int64_t)blockIdx.z * stride_channel_dst;
+ tmp_last_tile += (int64_t)blockIdx.z * gridDim.x * mmq_x * mmq_y;
+ }
+
float sum[mmq_x / nwarps] = {0.0f};
const int i = blockIdx.y*warp_size + threadIdx.x;
@@ -4136,7 +4181,12 @@ static __global__ void mul_mat_q_stream_k_fixup(
return;
}
- dst[j*stride_col_dst + i] += sum[j0/nwarps];
+ const int dst_idx = j*stride_col_dst + i;
+ float value = dst[dst_idx] + sum[j0/nwarps];
+ if constexpr (type == GGML_TYPE_Q4_K) {
+ if (!isfinite(value)) value = 0.0f;
+ }
+ dst[dst_idx] = value;
}
return;
}
@@ -4172,7 +4222,12 @@ static __global__ void mul_mat_q_stream_k_fixup(
return;
}
- dst[ids_dst_shared[j]*stride_col_dst + i] += sum[j0/nwarps];
+ const int dst_idx = ids_dst_shared[j]*stride_col_dst + i;
+ float value = dst[dst_idx] + sum[j0/nwarps];
+ if constexpr (type == GGML_TYPE_Q4_K) {
+ if (!isfinite(value)) value = 0.0f;
+ }
+ dst[dst_idx] = value;
}
}
@@ -4187,6 +4242,10 @@ struct mmq_args {
// ignored; soa_blocks = pair count (Q2_K) or block count (IQ2_XXS).
// Trailing fields so existing aggregate initializers value-init them.
const char * x_soa; int64_t soa_blocks;
+ // Optional caller-owned Stream-K fixup tile storage. Production callers
+ // normally leave this null and use the CUDA pool; kernel-only A/B harnesses
+ // provide it so cudaMallocAsync/cudaFreeAsync are outside their events.
+ float * stream_k_fixup; size_t stream_k_fixup_elements;
};
template
@@ -4199,7 +4258,7 @@ static size_t mmq_get_nbytes_shared(const int mmq_x, const int mmq_y, const int
return nbs_ids + nbs_x + GGML_PAD(nbs_y, nwarps*warp_size*sizeof(int));
}
-template
+template
static void launch_mul_mat_q(ggml_backend_cuda_context & ctx, const mmq_args & args, cudaStream_t stream) {
const int id = ggml_cuda_get_device();
const int cc = ggml_cuda_info().devices[id].cc;
@@ -4212,30 +4271,38 @@ static void launch_mul_mat_q(ggml_backend_cuda_context & ctx, const mmq_args & a
const int nbytes_shared = mmq_get_nbytes_shared(mmq_x, mmq_y, cc, warp_size, nwarps);
- CUDA_SET_SHARED_MEMORY_LIMIT((mul_mat_q), nbytes_shared);
- CUDA_SET_SHARED_MEMORY_LIMIT((mul_mat_q), nbytes_shared);
+ CUDA_SET_SHARED_MEMORY_LIMIT((mul_mat_q), nbytes_shared);
+ CUDA_SET_SHARED_MEMORY_LIMIT((mul_mat_q), nbytes_shared);
const int nty = (args.nrows_x + mmq_y - 1) / mmq_y;
const int ntx = (args.ncols_max + mmq_x - 1) / mmq_x;
- const int ntzw = args.nchannels_y * args.nsamples_y;
- const dim3 block_nums_xy_tiling(nty, ntx, ntzw);
+ const int ntzw = grid_z_channels ? 1 : args.nchannels_y * args.nsamples_y;
+ const int grid_z = grid_z_channels ? args.nchannels_y : ntzw;
+ const dim3 block_nums_xy_tiling(nty, ntx, grid_z);
GGML_ASSERT(args.nchannels_y % args.nchannels_x == 0);
GGML_ASSERT(args.nsamples_y % args.nsamples_x == 0);
- const int channel_ratio = args.nchannels_y / args.nchannels_x;
- const int sample_ratio = args.nsamples_y / args.nsamples_x;
+ if constexpr (grid_z_channels) {
+ GGML_ASSERT(args.ids_dst == nullptr && args.expert_bounds == nullptr);
+ GGML_ASSERT(args.nchannels_x == args.nchannels_y);
+ GGML_ASSERT(args.nsamples_x == 1 && args.nsamples_y == 1);
+ }
+ const int channel_ratio = grid_z_channels ? 1 : args.nchannels_y / args.nchannels_x;
+ const int sample_ratio = grid_z_channels ? 1 : args.nsamples_y / args.nsamples_x;
+ const int logical_nchannels_y = grid_z_channels ? 1 : args.nchannels_y;
+ const int logical_nsamples_y = grid_z_channels ? 1 : args.nsamples_y;
const uint3 blocks_per_ne00_fd = init_fastdiv_values(args.ncols_x / ggml_cuda_type_traits::qk);
const uint3 ntx_fd = init_fastdiv_values(ntx);
- const uint3 nchannels_y_fd = init_fastdiv_values(args.nchannels_y);
- const uint3 nsamples_y_fd = init_fastdiv_values(args.nsamples_y);
+ const uint3 nchannels_y_fd = init_fastdiv_values(logical_nchannels_y);
+ const uint3 nsamples_y_fd = init_fastdiv_values(logical_nsamples_y);
const uint3 channel_ratio_fd = init_fastdiv_values(channel_ratio);
const uint3 sample_ratio_fd = init_fastdiv_values(sample_ratio);
if (!args.use_stream_k) {
if (args.nrows_x % mmq_y == 0) {
constexpr bool need_check = false;
- mul_mat_q<<>>
+ mul_mat_q<<>>
(args.x, args.y, args.ids_dst, args.expert_bounds, args.dst, nullptr,
blocks_per_ne00_fd, args.nrows_x, args.ncols_dst, args.stride_row_x, args.ncols_y, args.nrows_dst,
channel_ratio_fd, nchannels_y_fd, args.stride_channel_x, args.stride_channel_y, args.stride_channel_dst,
@@ -4243,7 +4310,7 @@ static void launch_mul_mat_q(ggml_backend_cuda_context & ctx, const mmq_args & a
ntx_fd, args.x_soa, args.soa_blocks);
} else {
constexpr bool need_check = true;
- mul_mat_q<<>>
+ mul_mat_q<<>>
(args.x, args.y, args.ids_dst, args.expert_bounds, args.dst, nullptr,
blocks_per_ne00_fd, args.nrows_x, args.ncols_dst, args.stride_row_x, args.ncols_y, args.nrows_dst,
channel_ratio_fd, nchannels_y_fd, args.stride_channel_x, args.stride_channel_y, args.stride_channel_dst,
@@ -4258,7 +4325,8 @@ static void launch_mul_mat_q(ggml_backend_cuda_context & ctx, const mmq_args & a
const int ntiles_dst = ntx * nty * ntzw;
const int tiles_nwaves = (ntiles_dst + nsm - 1) / nsm;
const int tiles_efficiency_percent = 100 * ntiles_dst / (nsm*tiles_nwaves);
- const dim3 block_nums_stream_k(GGML_CUDA_CC_IS_NVIDIA(cc) && tiles_efficiency_percent >= 90 ? ntiles_dst : nsm, 1, 1);
+ const unsigned stream_k_grid_x = GGML_CUDA_CC_IS_NVIDIA(cc) && tiles_efficiency_percent >= 90 ? ntiles_dst : nsm;
+ const dim3 block_nums_stream_k(stream_k_grid_x, 1, grid_z_channels ? args.nchannels_y : 1);
GGML_ASSERT(ntiles_dst * blocks_per_ne00_fd.z < (1 << 30)); // Assert that variable kbc will not overflow.
@@ -4266,20 +4334,28 @@ static void launch_mul_mat_q(ggml_backend_cuda_context & ctx, const mmq_args & a
ggml_cuda_pool & pool = ctx.pool(id);
ggml_cuda_pool_alloc tmp_fixup(pool);
+ float * tmp_fixup_ptr = nullptr;
if (fixup_needed) {
- tmp_fixup.alloc(block_nums_stream_k.x * mmq_x*mmq_y);
- CUDA_CHECK(cudaMemsetAsync(tmp_fixup.ptr, 0,
- (size_t)block_nums_stream_k.x * (size_t)mmq_x * (size_t)mmq_y * sizeof(float),
- stream));
+ const size_t fixup_elements =
+ (size_t)block_nums_stream_k.x *
+ (size_t)block_nums_stream_k.z * mmq_x * mmq_y;
+ if (args.stream_k_fixup != nullptr) {
+ GGML_ASSERT(args.stream_k_fixup_elements >= fixup_elements);
+ tmp_fixup_ptr = args.stream_k_fixup;
+ } else {
+ tmp_fixup_ptr = tmp_fixup.alloc(fixup_elements);
+ }
+ CUDA_CHECK(cudaMemsetAsync(
+ tmp_fixup_ptr, 0, fixup_elements * sizeof(float), stream));
}
- const dim3 block_nums_fixup(block_nums_stream_k.x, mmq_y/warp_size, 1);
+ const dim3 block_nums_fixup(block_nums_stream_k.x, mmq_y/warp_size, block_nums_stream_k.z);
const dim3 block_dims_fixup(block_dims.x, block_dims.y/2, block_dims.z);
if (args.nrows_x % mmq_y == 0) {
constexpr bool need_check = false;
- mul_mat_q<<>>
- (args.x, args.y, args.ids_dst, args.expert_bounds, args.dst, tmp_fixup.ptr,
+ mul_mat_q<<>>
+ (args.x, args.y, args.ids_dst, args.expert_bounds, args.dst, tmp_fixup_ptr,
blocks_per_ne00_fd, args.nrows_x, args.ncols_dst, args.stride_row_x, args.ncols_y, args.nrows_dst,
channel_ratio_fd, nchannels_y_fd, args.stride_channel_x, args.stride_channel_y, args.stride_channel_dst,
sample_ratio_fd, nsamples_y_fd, args.stride_sample_x, args.stride_sample_y, args.stride_sample_dst,
@@ -4290,14 +4366,14 @@ static void launch_mul_mat_q(ggml_backend_cuda_context & ctx, const mmq_args & a
}
CUDA_CHECK(cudaGetLastError());
- mul_mat_q_stream_k_fixup<<>>
- (args.ids_dst, args.expert_bounds, args.dst, tmp_fixup.ptr, blocks_per_ne00_fd, args.nrows_x, args.ncols_dst,
+ mul_mat_q_stream_k_fixup<<>>
+ (args.ids_dst, args.expert_bounds, args.dst, tmp_fixup_ptr, blocks_per_ne00_fd, args.nrows_x, args.ncols_dst,
args.nrows_dst, nchannels_y_fd, args.stride_channel_dst, nsamples_y_fd, args.stride_sample_dst,
ntx_fd);
} else {
constexpr bool need_check = true;
- mul_mat_q<<>>
- (args.x, args.y, args.ids_dst, args.expert_bounds, args.dst, tmp_fixup.ptr,
+ mul_mat_q<<>>
+ (args.x, args.y, args.ids_dst, args.expert_bounds, args.dst, tmp_fixup_ptr,
blocks_per_ne00_fd, args.nrows_x, args.ncols_dst, args.stride_row_x, args.ncols_y, args.nrows_dst,
channel_ratio_fd, nchannels_y_fd, args.stride_channel_x, args.stride_channel_y, args.stride_channel_dst,
sample_ratio_fd, nsamples_y_fd, args.stride_sample_x, args.stride_sample_y, args.stride_sample_dst,
@@ -4308,15 +4384,15 @@ static void launch_mul_mat_q(ggml_backend_cuda_context & ctx, const mmq_args & a
}
CUDA_CHECK(cudaGetLastError());
- mul_mat_q_stream_k_fixup<<>>
- (args.ids_dst, args.expert_bounds, args.dst, tmp_fixup.ptr, blocks_per_ne00_fd, args.nrows_x, args.ncols_dst,
+ mul_mat_q_stream_k_fixup<<>>
+ (args.ids_dst, args.expert_bounds, args.dst, tmp_fixup_ptr, blocks_per_ne00_fd, args.nrows_x, args.ncols_dst,
args.nrows_dst, nchannels_y_fd, args.stride_channel_dst, nsamples_y_fd, args.stride_sample_dst,
ntx_fd);
}
}
-template
-void mul_mat_q_case(ggml_backend_cuda_context & ctx, const mmq_args & args, cudaStream_t stream) {
+template
+static void mul_mat_q_case_impl(ggml_backend_cuda_context & ctx, const mmq_args & args, cudaStream_t stream) {
const int id = ggml_cuda_get_device();
const int cc = ggml_cuda_info().devices[id].cc;
const size_t smpbo = ggml_cuda_info().devices[id].smpbo;
@@ -4346,52 +4422,52 @@ void mul_mat_q_case(ggml_backend_cuda_context & ctx, const mmq_args & args, cuda
switch (mmq_x_best) {
case 8:
- launch_mul_mat_q(ctx, args, stream);
+ launch_mul_mat_q(ctx, args, stream);
break;
case 16:
- launch_mul_mat_q(ctx, args, stream);
+ launch_mul_mat_q(ctx, args, stream);
break;
case 24:
- launch_mul_mat_q(ctx, args, stream);
+ launch_mul_mat_q(ctx, args, stream);
break;
case 32:
- launch_mul_mat_q(ctx, args, stream);
+ launch_mul_mat_q(ctx, args, stream);
break;
case 40:
- launch_mul_mat_q(ctx, args, stream);
+ launch_mul_mat_q(ctx, args, stream);
break;
case 48:
- launch_mul_mat_q(ctx, args, stream);
+ launch_mul_mat_q(ctx, args, stream);
break;
case 56:
- launch_mul_mat_q(ctx, args, stream);
+ launch_mul_mat_q(ctx, args, stream);
break;
case 64:
- launch_mul_mat_q(ctx, args, stream);
+ launch_mul_mat_q(ctx, args, stream);
break;
case 72:
- launch_mul_mat_q(ctx, args, stream);
+ launch_mul_mat_q(ctx, args, stream);
break;
case 80:
- launch_mul_mat_q(ctx, args, stream);
+ launch_mul_mat_q(ctx, args, stream);
break;
case 88:
- launch_mul_mat_q(ctx, args, stream);
+ launch_mul_mat_q(ctx, args, stream);
break;
case 96:
- launch_mul_mat_q(ctx, args, stream);
+ launch_mul_mat_q(ctx, args, stream);
break;
case 104:
- launch_mul_mat_q(ctx, args, stream);
+ launch_mul_mat_q(ctx, args, stream);
break;
case 112:
- launch_mul_mat_q(ctx, args, stream);
+ launch_mul_mat_q(ctx, args, stream);
break;
case 120:
- launch_mul_mat_q(ctx, args, stream);
+ launch_mul_mat_q(ctx, args, stream);
break;
case 128:
- launch_mul_mat_q(ctx, args, stream);
+ launch_mul_mat_q(ctx, args, stream);
break;
default:
fprintf(stderr, "mmq_x_best=%d\n", mmq_x_best);
@@ -4400,6 +4476,20 @@ void mul_mat_q_case(ggml_backend_cuda_context & ctx, const mmq_args & args, cuda
}
}
+template
+void mul_mat_q_case(ggml_backend_cuda_context & ctx, const mmq_args & args, cudaStream_t stream) {
+ mul_mat_q_case_impl(ctx, args, stream);
+}
+
+/* Dense-only grouped entry used by ds4's Q4 attention output-A path. Each
+ * grid.z slice is reduction-isolated, so the result remains bit-identical to
+ * invoking mul_mat_q_case once per channel on the same stream. */
+template
+void mul_mat_q_case_grouped_channels(
+ ggml_backend_cuda_context & ctx, const mmq_args & args, cudaStream_t stream) {
+ mul_mat_q_case_impl(ctx, args, stream);
+}
+
#define DECL_MMQ_CASE(type) \
template void mul_mat_q_case(ggml_backend_cuda_context & ctx, const mmq_args & args, cudaStream_t stream) \
diff --git a/cuda/mmq/quantize.cu b/cuda/mmq/quantize.cu
index 52f664719a..a8066c4845 100644
--- a/cuda/mmq/quantize.cu
+++ b/cuda/mmq/quantize.cu
@@ -366,6 +366,77 @@ static __global__ void quantize_mmq_q8_1(
}
}
+#if !defined(GGML_USE_HIP)
+// Q4 grouped attention-A has one hot, fixed source geometry:
+// [token][group=8][K=4096]. The generic MMQ quantizer launches four-warp
+// CTAs, each producing four 128-value block_q8_1_mmq records. This kernel
+// keeps the exact DS4 arithmetic and byte layout, but uses eight warps and
+// lets each warp produce two consecutive records. One CTA therefore covers
+// 2048 source values and the launch uses four times fewer CTAs, without the
+// 16-warp geometry that regressed on GB10.
+__launch_bounds__(8*WARP_SIZE)
+static __global__ void quantize_mmq_q8_1_q4_grouped_k4096_g8x2(
+ const float * __restrict__ x, void * __restrict__ vy, const int ne1) {
+ constexpr int k_groups = 8;
+ constexpr int k_values = 4096;
+ constexpr int k_q8_blocks = k_values / (4*QK8_1);
+ constexpr int k_warps = 8;
+ constexpr int k_blocks_per_warp = 2;
+ constexpr int k_blocks_per_cta = k_warps * k_blocks_per_warp;
+ static_assert(WARP_SIZE == 32, "CUDA Q8_1 quantizer requires 32-lane warps");
+ static_assert(k_q8_blocks == 32, "unexpected grouped Q8_1 block count");
+ static_assert(2*k_blocks_per_cta == k_q8_blocks,
+ "two CTAs must cover one grouped activation row");
+
+ const int token = (int)blockIdx.x;
+ const int group = (int)blockIdx.z;
+ const int warp = (int)threadIdx.x / WARP_SIZE;
+ const int lane = (int)threadIdx.x % WARP_SIZE;
+ const uint32_t input_base =
+ ((uint32_t)token * k_groups + (uint32_t)group) * k_values;
+ const float4 * __restrict__ x4 = (const float4 *)x;
+ block_q8_1_mmq * __restrict__ y = (block_q8_1_mmq *)vy;
+
+#pragma unroll
+ for (int j = 0; j < k_blocks_per_warp; ++j) {
+ const int q8_block =
+ (int)blockIdx.y * k_blocks_per_cta + j * k_warps + warp;
+ const uint32_t input = input_base +
+ (uint32_t)q8_block * (4*QK8_1) + (uint32_t)lane * 4u;
+ const float4 xi = x4[input / 4u];
+
+ float amax = fabsf(xi.x);
+ amax = fmaxf(amax, fabsf(xi.y));
+ amax = fmaxf(amax, fabsf(xi.z));
+ amax = fmaxf(amax, fabsf(xi.w));
+#pragma unroll
+ for (int offset = 4; offset > 0; offset >>= 1) {
+ amax = fmaxf(
+ amax, __shfl_xor_sync(0xFFFFFFFF, amax, offset, WARP_SIZE));
+ }
+
+ float sum = xi.x + xi.y + xi.z + xi.w;
+#pragma unroll
+ for (int offset = 4; offset > 0; offset >>= 1) {
+ sum += __shfl_xor_sync(0xFFFFFFFF, sum, offset, WARP_SIZE);
+ }
+
+ const float d_inv = 127.0f / amax;
+ char4 q;
+ q.x = roundf(xi.x*d_inv);
+ q.y = roundf(xi.y*d_inv);
+ q.z = roundf(xi.z*d_inv);
+ q.w = roundf(xi.w*d_inv);
+
+ const int ib = (group*k_q8_blocks + q8_block)*ne1 + token;
+ ((char4 *)y[ib].qs)[lane] = q;
+ if ((lane % 8) == 0) {
+ y[ib].ds4[lane / 8] = make_half2(1.0f / d_inv, sum);
+ }
+ }
+}
+#endif
+
void quantize_row_q8_1_cuda(
const float * x, const int32_t * ids, void * vy, const ggml_type type_src0,
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
@@ -412,6 +483,22 @@ void quantize_mmq_q8_1_cuda(
}
}
+#if !defined(GGML_USE_HIP)
+void quantize_mmq_q8_1_q4_grouped_k4096_g8x2_cuda(
+ const float * x, void * vy, int ne1, cudaStream_t stream) {
+ GGML_ASSERT(x);
+ GGML_ASSERT(vy);
+ GGML_ASSERT(ne1 > 0 && ne1 <= INT32_MAX / (8*4096));
+
+ constexpr int k_warps = 8;
+ constexpr int k_grid_y = 2;
+ const dim3 num_blocks(ne1, k_grid_y, 8);
+ const dim3 block_size(k_warps*WARP_SIZE, 1, 1);
+ quantize_mmq_q8_1_q4_grouped_k4096_g8x2<<<
+ num_blocks, block_size, 0, stream>>>(x, vy, ne1);
+}
+#endif
+
void quantize_mmq_fp4_cuda(
const float * x, const int32_t * ids, void * vy, const ggml_type type_src0,
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
diff --git a/cuda/mmq/quantize.cuh b/cuda/mmq/quantize.cuh
index 768a3ae6de..ecc1ca6dfe 100644
--- a/cuda/mmq/quantize.cuh
+++ b/cuda/mmq/quantize.cuh
@@ -26,6 +26,13 @@ void quantize_mmq_q8_1_cuda(
ggml_type type_src0, int64_t ne00, int64_t s01, int64_t s02, int64_t s03,
int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne3, cudaStream_t stream);
+#if !defined(GGML_USE_HIP)
+// Fixed-layout Q4 attention-A prefill producer. X is [N][8][4096] and the
+// output is canonical block_q8_1_mmq DS4, group-major [8][32][N].
+void quantize_mmq_q8_1_q4_grouped_k4096_g8x2_cuda(
+ const float * x, void * vy, int ne1, cudaStream_t stream);
+#endif
+
void quantize_mmq_fp4_cuda(const float * x,
const int32_t * ids,
void * vy,
diff --git a/cuda/mmq/test/d2r_stubs.cu b/cuda/mmq/test/d2r_stubs.cu
index e9249e7909..81fb1a9e3b 100644
--- a/cuda/mmq/test/d2r_stubs.cu
+++ b/cuda/mmq/test/d2r_stubs.cu
@@ -1,10 +1,12 @@
#include "ds4_mmq_d2r.cuh"
extern "C" int ds4_cuda_q8_fold_take_q81(
- const void *src, uint64_t in_dim, const void **q81) {
+ const void *src, uint64_t in_dim, cudaStream_t stream,
+ const void **q81) {
(void)src;
(void)in_dim;
- (void)q81;
+ (void)stream;
+ if (q81) *q81 = nullptr;
return 0;
}
diff --git a/cuda/mmq/test/proto_gemm_dense_q8_d2r.cu b/cuda/mmq/test/proto_gemm_dense_q8_d2r.cu
index 78496c5a13..8dc8d42758 100644
--- a/cuda/mmq/test/proto_gemm_dense_q8_d2r.cu
+++ b/cuda/mmq/test/proto_gemm_dense_q8_d2r.cu
@@ -42,13 +42,6 @@
#include "ds4_mmq.h"
#include "quantize.cuh"
-extern "C" int ds4_cuda_q8_fold_take_q81(const void *src, uint64_t in_dim, void *out) {
- (void)src;
- (void)in_dim;
- (void)out;
- return 0;
-}
-
#include
#include
diff --git a/cuda/mmq/test/test_mmq_parity.cu b/cuda/mmq/test/test_mmq_parity.cu
index 29edf8275c..cdf4aa341a 100644
--- a/cuda/mmq/test/test_mmq_parity.cu
+++ b/cuda/mmq/test/test_mmq_parity.cu
@@ -20,6 +20,7 @@
// -o test_mmq_parity
#include "ds4_mmq.h"
+#include "ds4_mmq_q4_16warp.cuh"
#include "iq2_host_tables.h"
// Pull in the block_* struct definitions. We use the CUDA decl/impl mode
@@ -48,18 +49,98 @@
#endif
#include
+#include
#include
#include
#include
#include
#include
#include
+#include
#include
namespace {
constexpr int QK_K_LOCAL = 256;
+class scoped_env_override {
+public:
+ explicit scoped_env_override(const char *name) : name_(name) {
+ const char *value = std::getenv(name_);
+ if (value) {
+ had_original_ = true;
+ original_value_ = value;
+ }
+ }
+
+ ~scoped_env_override() {
+ (void)restore();
+ }
+
+ bool set(const char *value) {
+ if (setenv(name_, value, 1) != 0) {
+ const int saved_errno = errno;
+ fprintf(stderr, "setenv(%s=%s) failed: %s\n",
+ name_, value, std::strerror(saved_errno));
+ return false;
+ }
+ active_ = true;
+ return true;
+ }
+
+ bool restore() {
+ if (!active_) return true;
+ const int rc = had_original_
+ ? setenv(name_, original_value_.c_str(), 1)
+ : unsetenv(name_);
+ if (rc != 0) {
+ const int saved_errno = errno;
+ fprintf(stderr, "restoring %s failed: %s\n",
+ name_, std::strerror(saved_errno));
+ return false;
+ }
+ active_ = false;
+ return true;
+ }
+
+ scoped_env_override(const scoped_env_override &) = delete;
+ scoped_env_override &operator=(const scoped_env_override &) = delete;
+
+private:
+ const char *name_;
+ std::string original_value_;
+ bool had_original_ = false;
+ bool active_ = false;
+};
+
+cudaError_t enqueue_scratch_guard_copy(
+ const void *storage, size_t payload_bytes, size_t guard_bytes,
+ uint8_t *host_guards, cudaStream_t stream) {
+ if (!storage || !host_guards || guard_bytes == 0) {
+ // cudaError_t is an integer-compatible type in both the CUDA runtime and
+ // the host-only syntax-check stub; avoid depending on a stubbed enum.
+ return static_cast(1);
+ }
+ const auto *bytes = static_cast(storage);
+ cudaError_t err = cudaMemcpyAsync(
+ host_guards, bytes, guard_bytes, cudaMemcpyDeviceToHost, stream);
+ if (err == cudaSuccess) {
+ err = cudaMemcpyAsync(
+ host_guards + guard_bytes, bytes + guard_bytes + payload_bytes,
+ guard_bytes, cudaMemcpyDeviceToHost, stream);
+ }
+ return err;
+}
+
+size_t scratch_guard_mismatches(
+ const std::vector &guards, uint8_t expected) {
+ size_t bad = 0;
+ for (uint8_t value : guards) {
+ if (value != expected) bad++;
+ }
+ return bad;
+}
+
// --------------------------------------------------------------------------
// Half-precision conversion (standalone, no CUDA host fp16 needed).
// --------------------------------------------------------------------------
@@ -504,6 +585,1176 @@ bool run_q4_K(int M, int N, int K, uint32_t seed, float abs_scale = 0.20f) {
return ok;
}
+// Resident-kernel oracle for the opt-in m128n128/16-warp Q4_K prefill
+// candidate. The raw canonical/candidate arms consume the same caller-owned
+// DS4 Q8_1 activation. The canonical arm uses the production stream-K policy,
+// including fixup when selected. The production API can be checked as a third,
+// independently guarded output without folding its quantizer into the raw
+// kernel comparison.
+bool run_q4_K_dense_16warp_parity(
+ int M, int N, int K, int nsm, uint32_t seed,
+ bool check_public_dense, bool check_rejection) {
+ fprintf(stderr,
+ "=== Q4_K/DENSE_16WARP M=%d N=%d K=%d seed=%u%s ===\n",
+ M, N, K, seed, check_public_dense ? " production" : "");
+
+ if (M <= 0 || N <= 0 || K <= 0 || nsm <= 0 ||
+ K % QK_K_LOCAL != 0 ||
+ (size_t)M > SIZE_MAX / (size_t)N / sizeof(float)) {
+ fprintf(stderr, "invalid 16-warp parity shape\n\n");
+ return false;
+ }
+
+ std::mt19937 rng(seed);
+ std::normal_distribution nd(0.0f, 1.0f);
+ const int blocks_per_row = K / QK_K_LOCAL;
+ std::vector W((size_t)M * blocks_per_row);
+ for (auto &blk : W) generate_random_block_q4_K(&blk, rng);
+ std::vector X((size_t)N * K);
+ for (float &v : X) v = nd(rng);
+
+ const size_t q8_bytes = ds4_mmq_q4_K_q8_1_scratch_bytes(N, K);
+ if (q8_bytes == 0) {
+ fprintf(stderr, "Q4_K 16-warp scratch-size query rejected shape\n\n");
+ return false;
+ }
+
+ constexpr size_t guard_floats = 64;
+ constexpr uint8_t ref_guard_byte = 0xa5;
+ constexpr uint8_t prod_guard_byte = 0xc3;
+ constexpr uint8_t got_guard_byte = 0x5a;
+ constexpr uint8_t reject_byte = 0x3c;
+ constexpr uint8_t scratch_guard_byte = 0x7d;
+ const size_t output_count = (size_t)M * N;
+ const size_t output_bytes = output_count * sizeof(float);
+ const size_t guard_bytes = guard_floats * sizeof(float);
+ const size_t guarded_bytes = output_bytes + 2u * guard_bytes;
+ const size_t scratch_bytes =
+ ds4_mmq_q4_K_dense_16warp_streamk_scratch_bytes(M, N, nsm);
+ if (scratch_bytes > SIZE_MAX - 2u * guard_bytes) {
+ fprintf(stderr, "Q4_K 16-warp scratch guard size overflow\n\n");
+ return false;
+ }
+ const size_t scratch_guarded_bytes = scratch_bytes + 2u * guard_bytes;
+
+ cudaStream_t stream = nullptr;
+ void *dW = nullptr;
+ float *dX = nullptr;
+ void *dQ8 = nullptr;
+ float *dRefStorage = nullptr;
+ float *dProdStorage = nullptr;
+ float *dGotStorage = nullptr;
+ void *dScratchStorage = nullptr;
+ const bool allocated = cudaStreamCreate(&stream) == cudaSuccess &&
+ cudaMalloc(&dW, W.size() * sizeof(block_q4_K)) == cudaSuccess &&
+ cudaMalloc(&dX, X.size() * sizeof(float)) == cudaSuccess &&
+ cudaMalloc(&dQ8, q8_bytes) == cudaSuccess &&
+ cudaMalloc(&dRefStorage, guarded_bytes) == cudaSuccess &&
+ (!check_public_dense ||
+ cudaMalloc(&dProdStorage, guarded_bytes) == cudaSuccess) &&
+ cudaMalloc(&dGotStorage, guarded_bytes) == cudaSuccess &&
+ cudaMalloc(&dScratchStorage, scratch_guarded_bytes) == cudaSuccess;
+ const auto cleanup = [&]() {
+ if (dScratchStorage) cudaFree(dScratchStorage);
+ if (dGotStorage) cudaFree(dGotStorage);
+ if (dProdStorage) cudaFree(dProdStorage);
+ if (dRefStorage) cudaFree(dRefStorage);
+ if (dQ8) cudaFree(dQ8);
+ if (dX) cudaFree(dX);
+ if (dW) cudaFree(dW);
+ if (stream) cudaStreamDestroy(stream);
+ };
+ if (!allocated) {
+ fprintf(stderr, "Q4_K 16-warp parity allocation failed: %s\n\n",
+ cudaGetErrorString(cudaGetLastError()));
+ cleanup();
+ return false;
+ }
+
+ float *const dRef = dRefStorage + guard_floats;
+ float *const dProd = check_public_dense
+ ? dProdStorage + guard_floats : nullptr;
+ float *const dGot = dGotStorage + guard_floats;
+ void *const dScratch =
+ static_cast(dScratchStorage) + guard_bytes;
+ cudaError_t enqueue_err = cudaMemcpyAsync(
+ dW, W.data(), W.size() * sizeof(block_q4_K),
+ cudaMemcpyHostToDevice, stream);
+ if (enqueue_err == cudaSuccess) {
+ enqueue_err = cudaMemcpyAsync(
+ dX, X.data(), X.size() * sizeof(float),
+ cudaMemcpyHostToDevice, stream);
+ }
+ if (enqueue_err == cudaSuccess) {
+ enqueue_err = cudaMemsetAsync(
+ dRefStorage, ref_guard_byte, guarded_bytes, stream);
+ }
+ if (enqueue_err == cudaSuccess && check_public_dense) {
+ enqueue_err = cudaMemsetAsync(
+ dProdStorage, prod_guard_byte, guarded_bytes, stream);
+ }
+ if (enqueue_err == cudaSuccess) {
+ enqueue_err = cudaMemsetAsync(
+ dGotStorage, got_guard_byte, guarded_bytes, stream);
+ }
+ if (enqueue_err == cudaSuccess) {
+ enqueue_err = cudaMemsetAsync(
+ dScratchStorage, scratch_guard_byte, scratch_guarded_bytes,
+ stream);
+ }
+
+ const int rc_quant = enqueue_err == cudaSuccess
+ ? ds4_mmq_q4_K_quantize_q8_1_for_test(
+ dX, dQ8, q8_bytes, N, K, stream)
+ : -100;
+ const int rc_ref = rc_quant == 0
+ ? ds4_mmq_q4_K_dense_preq_reference_for_test(
+ dW, dQ8, q8_bytes, dRef, M, N, K,
+ /*use_stream_k=*/1,
+ dScratch, scratch_bytes,
+ stream)
+ : -100;
+ std::vector ref_scratch_guards(2u * guard_bytes);
+ if (enqueue_err == cudaSuccess && rc_ref == 0) {
+ enqueue_err = enqueue_scratch_guard_copy(
+ dScratchStorage, scratch_bytes, guard_bytes,
+ ref_scratch_guards.data(), stream);
+ }
+ const int rc_prod = rc_ref != 0 || enqueue_err != cudaSuccess
+ ? -100 : check_public_dense
+ ? ds4_mmq_q4_K_dense(
+ dW, dX, dProd, M, N, K, stream)
+ : 0;
+ const int rc_got = rc_prod == 0
+ ? ds4_mmq_q4_K_dense_16warp_streamk_enqueue(
+ dW, dQ8, dGot, dScratch, scratch_bytes,
+ M, N, K, nsm, stream)
+ : -100;
+ std::vector got_scratch_guards(2u * guard_bytes);
+ if (enqueue_err == cudaSuccess && rc_got == 0) {
+ enqueue_err = enqueue_scratch_guard_copy(
+ dScratchStorage, scratch_bytes, guard_bytes,
+ got_scratch_guards.data(), stream);
+ }
+
+ std::vector ref_guarded(guarded_bytes);
+ std::vector prod_guarded(
+ check_public_dense ? guarded_bytes : 0u);
+ std::vector got_guarded(guarded_bytes);
+ if (rc_got == 0) {
+ enqueue_err = cudaMemcpyAsync(
+ ref_guarded.data(), dRefStorage, guarded_bytes,
+ cudaMemcpyDeviceToHost, stream);
+ }
+ if (enqueue_err == cudaSuccess && rc_got == 0 && check_public_dense) {
+ enqueue_err = cudaMemcpyAsync(
+ prod_guarded.data(), dProdStorage, guarded_bytes,
+ cudaMemcpyDeviceToHost, stream);
+ }
+ if (enqueue_err == cudaSuccess && rc_got == 0) {
+ enqueue_err = cudaMemcpyAsync(
+ got_guarded.data(), dGotStorage, guarded_bytes,
+ cudaMemcpyDeviceToHost, stream);
+ }
+ const cudaError_t sync_err = cudaStreamSynchronize(stream);
+
+ size_t ref_got_mismatches = 0;
+ size_t ref_prod_mismatches = 0;
+ size_t prod_got_mismatches = 0;
+ size_t nonfinite_ref = 0;
+ size_t nonfinite_prod = 0;
+ size_t nonfinite_got = 0;
+ uint32_t first_ref_bits = 0;
+ uint32_t first_got_bits = 0;
+ uint32_t first_prod_bits = 0;
+ size_t first_ref_got_bad = SIZE_MAX;
+ size_t first_ref_prod_bad = SIZE_MAX;
+ if (enqueue_err == cudaSuccess && sync_err == cudaSuccess && rc_got == 0) {
+ for (size_t i = 0; i < output_count; ++i) {
+ const uint8_t *const ref_bits_ptr =
+ ref_guarded.data() + guard_bytes + i * sizeof(float);
+ const uint8_t *const got_bits_ptr =
+ got_guarded.data() + guard_bytes + i * sizeof(float);
+ const uint8_t *const prod_bits_ptr = check_public_dense
+ ? prod_guarded.data() + guard_bytes + i * sizeof(float)
+ : nullptr;
+ float ref_value = 0.0f;
+ float prod_value = 0.0f;
+ float got_value = 0.0f;
+ std::memcpy(&ref_value, ref_bits_ptr, sizeof(ref_value));
+ std::memcpy(&got_value, got_bits_ptr, sizeof(got_value));
+ if (check_public_dense) {
+ std::memcpy(&prod_value, prod_bits_ptr, sizeof(prod_value));
+ }
+ if (!std::isfinite(ref_value)) nonfinite_ref++;
+ if (check_public_dense && !std::isfinite(prod_value)) {
+ nonfinite_prod++;
+ }
+ if (!std::isfinite(got_value)) nonfinite_got++;
+ if (std::memcmp(ref_bits_ptr, got_bits_ptr, sizeof(float)) != 0) {
+ if (first_ref_got_bad == SIZE_MAX) {
+ first_ref_got_bad = i;
+ std::memcpy(&first_ref_bits, ref_bits_ptr,
+ sizeof(first_ref_bits));
+ std::memcpy(&first_got_bits, got_bits_ptr,
+ sizeof(first_got_bits));
+ }
+ ref_got_mismatches++;
+ }
+ if (check_public_dense &&
+ std::memcmp(ref_bits_ptr, prod_bits_ptr, sizeof(float)) != 0) {
+ if (first_ref_prod_bad == SIZE_MAX) {
+ first_ref_prod_bad = i;
+ std::memcpy(&first_prod_bits, prod_bits_ptr,
+ sizeof(first_prod_bits));
+ }
+ ref_prod_mismatches++;
+ }
+ if (check_public_dense &&
+ std::memcmp(prod_bits_ptr, got_bits_ptr, sizeof(float)) != 0) {
+ prod_got_mismatches++;
+ }
+ }
+ }
+
+ const auto guard_mismatches = [=](
+ const std::vector &bytes, uint8_t expected) {
+ size_t bad = 0;
+ for (size_t i = 0; i < guard_bytes; ++i) {
+ if (bytes[i] != expected) bad++;
+ }
+ for (size_t i = guard_bytes + output_bytes; i < bytes.size(); ++i) {
+ if (bytes[i] != expected) bad++;
+ }
+ return bad;
+ };
+ const size_t ref_canary = guard_mismatches(ref_guarded, ref_guard_byte);
+ const size_t prod_canary = check_public_dense
+ ? guard_mismatches(prod_guarded, prod_guard_byte) : 0;
+ const size_t got_canary = guard_mismatches(got_guarded, got_guard_byte);
+ const size_t ref_scratch_canary =
+ scratch_guard_mismatches(ref_scratch_guards, scratch_guard_byte);
+ const size_t got_scratch_canary =
+ scratch_guard_mismatches(got_scratch_guards, scratch_guard_byte);
+
+ int rc_reject = DS4_MMQ_NOT_APPLICABLE;
+ size_t reject_writes = 0;
+ cudaError_t reject_sync = cudaSuccess;
+ if (check_rejection && enqueue_err == cudaSuccess &&
+ sync_err == cudaSuccess) {
+ cudaError_t reject_err = cudaMemsetAsync(
+ dGotStorage, reject_byte, guarded_bytes, stream);
+ rc_reject = reject_err == cudaSuccess
+ ? ds4_mmq_q4_K_dense_preq_16warp_for_test(
+ dW, dQ8, q8_bytes, dGot, M, /*N=*/511, K, stream)
+ : -100;
+ std::vector rejected(guarded_bytes);
+ if (reject_err == cudaSuccess) {
+ reject_err = cudaMemcpyAsync(
+ rejected.data(), dGotStorage, guarded_bytes,
+ cudaMemcpyDeviceToHost, stream);
+ }
+ reject_sync = cudaStreamSynchronize(stream);
+ if (reject_err == cudaSuccess && reject_sync == cudaSuccess) {
+ for (uint8_t byte : rejected) {
+ if (byte != reject_byte) reject_writes++;
+ }
+ } else {
+ reject_writes = SIZE_MAX;
+ }
+ }
+
+ const bool rejection_ok = !check_rejection ||
+ (rc_reject == DS4_MMQ_NOT_APPLICABLE &&
+ reject_sync == cudaSuccess && reject_writes == 0);
+ const bool production_ok = !check_public_dense ||
+ (ref_prod_mismatches == 0 && prod_got_mismatches == 0 &&
+ nonfinite_prod == 0 && prod_canary == 0);
+ const bool ok = rc_quant == 0 && rc_ref == 0 && rc_prod == 0 &&
+ rc_got == 0 && enqueue_err == cudaSuccess &&
+ sync_err == cudaSuccess && ref_got_mismatches == 0 &&
+ nonfinite_ref == 0 && nonfinite_got == 0 && ref_canary == 0 &&
+ got_canary == 0 && ref_scratch_canary == 0 &&
+ got_scratch_canary == 0 && production_ok && rejection_ok;
+ fprintf(stderr,
+ "quant/ref/production/16w=%d/%d/%d/%d enqueue=%s sync=%s "
+ "bits(ref-16w/ref-production/production-16w)=%zu/%zu/%zu "
+ "nonfinite=%zu/%zu/%zu canary=%zu/%zu/%zu "
+ "scratch_canary(ref/16w)=%zu/%zu reject=%d/%zu: %s\n",
+ rc_quant, rc_ref, rc_prod, rc_got,
+ cudaGetErrorString(enqueue_err), cudaGetErrorString(sync_err),
+ ref_got_mismatches, ref_prod_mismatches, prod_got_mismatches,
+ nonfinite_ref, nonfinite_prod, nonfinite_got,
+ ref_canary, prod_canary, got_canary,
+ ref_scratch_canary, got_scratch_canary,
+ rc_reject, reject_writes,
+ ok ? "PASS" : "FAIL");
+ if (first_ref_got_bad != SIZE_MAX) {
+ fprintf(stderr,
+ "first ref/16w mismatch at output[%zu]: "
+ "ref=0x%08x got=0x%08x\n",
+ first_ref_got_bad, first_ref_bits, first_got_bits);
+ }
+ if (first_ref_prod_bad != SIZE_MAX) {
+ uint32_t ref_bits = 0;
+ const uint8_t *const ptr = ref_guarded.data() + guard_bytes +
+ first_ref_prod_bad * sizeof(float);
+ std::memcpy(&ref_bits, ptr, sizeof(ref_bits));
+ fprintf(stderr,
+ "first ref/production mismatch at output[%zu]: "
+ "ref=0x%08x production=0x%08x\n",
+ first_ref_prod_bad, ref_bits, first_prod_bits);
+ }
+ fputc('\n', stderr);
+ cleanup();
+ return ok;
+}
+
+// Kernel-only Q-A/KV pair oracle. Quantize X exactly once, then compare two
+// canonical stream-K launches against two 16-warp stream-K launches over the
+// same immutable Q8_1 DS4 buffer and the real required production pair API.
+// Keeping every output independently guarded catches a bad M0/M1 stride or a
+// cross-leg overwrite as well as a numerical mismatch.
+bool run_q4_K_dense_pair_16warp_parity(
+ int M0, int M1, int N, int K, int nsm, uint32_t seed) {
+ fprintf(stderr,
+ "=== Q4_K/DENSE_PAIR_16WARP M0=%d M1=%d N=%d K=%d seed=%u ===\n",
+ M0, M1, N, K, seed);
+
+ if (M0 <= 0 || M1 <= 0 || N <= 0 || K <= 0 || nsm <= 0 ||
+ K % QK_K_LOCAL != 0 ||
+ (size_t)M0 > SIZE_MAX / (size_t)N / sizeof(float) ||
+ (size_t)M1 > SIZE_MAX / (size_t)N / sizeof(float)) {
+ fprintf(stderr, "invalid 16-warp pair parity shape\n\n");
+ return false;
+ }
+
+ std::mt19937 rng(seed);
+ std::normal_distribution nd(0.0f, 1.0f);
+ const int blocks_per_row = K / QK_K_LOCAL;
+ std::vector W0((size_t)M0 * blocks_per_row);
+ std::vector W1((size_t)M1 * blocks_per_row);
+ for (auto &blk : W0) generate_random_block_q4_K(&blk, rng);
+ for (auto &blk : W1) generate_random_block_q4_K(&blk, rng);
+ std::vector X((size_t)N * K);
+ for (float &v : X) v = nd(rng);
+
+ const size_t q8_bytes = ds4_mmq_q4_K_q8_1_scratch_bytes(N, K);
+ if (q8_bytes == 0) {
+ fprintf(stderr, "Q4_K 16-warp pair scratch-size query rejected shape\n\n");
+ return false;
+ }
+
+ constexpr size_t guard_floats = 64;
+ constexpr size_t guard_bytes = guard_floats * sizeof(float);
+ constexpr uint8_t ref0_guard_byte = 0xa5;
+ constexpr uint8_t ref1_guard_byte = 0xb6;
+ constexpr uint8_t got0_guard_byte = 0x5a;
+ constexpr uint8_t got1_guard_byte = 0x69;
+ constexpr uint8_t prod0_guard_byte = 0xc3;
+ constexpr uint8_t prod1_guard_byte = 0xd4;
+ constexpr uint8_t reject_guard_byte = 0x3c;
+ constexpr uint8_t scratch_guard_byte = 0x7d;
+ const size_t count0 = (size_t)M0 * N;
+ const size_t count1 = (size_t)M1 * N;
+ const size_t bytes0 = count0 * sizeof(float);
+ const size_t bytes1 = count1 * sizeof(float);
+ const size_t guarded0 = bytes0 + 2u * guard_bytes;
+ const size_t guarded1 = bytes1 + 2u * guard_bytes;
+ const size_t scratch0_bytes =
+ ds4_mmq_q4_K_dense_16warp_streamk_scratch_bytes(M0, N, nsm);
+ const size_t scratch1_bytes =
+ ds4_mmq_q4_K_dense_16warp_streamk_scratch_bytes(M1, N, nsm);
+ const size_t scratch_bytes =
+ scratch0_bytes > scratch1_bytes ? scratch0_bytes : scratch1_bytes;
+ if (scratch_bytes > SIZE_MAX - 2u * guard_bytes) {
+ fprintf(stderr, "Q4_K 16-warp pair scratch guard size overflow\n\n");
+ return false;
+ }
+ const size_t scratch_guarded_bytes = scratch_bytes + 2u * guard_bytes;
+
+ cudaStream_t stream = nullptr;
+ void *dW0 = nullptr;
+ void *dW1 = nullptr;
+ float *dX = nullptr;
+ void *dQ8 = nullptr;
+ float *dRef0Storage = nullptr;
+ float *dRef1Storage = nullptr;
+ float *dGot0Storage = nullptr;
+ float *dGot1Storage = nullptr;
+ float *dProd0Storage = nullptr;
+ float *dProd1Storage = nullptr;
+ void *dScratchStorage = nullptr;
+ const bool allocated = cudaStreamCreate(&stream) == cudaSuccess &&
+ cudaMalloc(&dW0, W0.size() * sizeof(block_q4_K)) == cudaSuccess &&
+ cudaMalloc(&dW1, W1.size() * sizeof(block_q4_K)) == cudaSuccess &&
+ cudaMalloc(&dX, X.size() * sizeof(float)) == cudaSuccess &&
+ cudaMalloc(&dQ8, q8_bytes) == cudaSuccess &&
+ cudaMalloc(&dRef0Storage, guarded0) == cudaSuccess &&
+ cudaMalloc(&dRef1Storage, guarded1) == cudaSuccess &&
+ cudaMalloc(&dGot0Storage, guarded0) == cudaSuccess &&
+ cudaMalloc(&dGot1Storage, guarded1) == cudaSuccess &&
+ cudaMalloc(&dProd0Storage, guarded0) == cudaSuccess &&
+ cudaMalloc(&dProd1Storage, guarded1) == cudaSuccess &&
+ cudaMalloc(&dScratchStorage, scratch_guarded_bytes) == cudaSuccess;
+ const auto cleanup = [&]() {
+ if (dScratchStorage) cudaFree(dScratchStorage);
+ if (dProd1Storage) cudaFree(dProd1Storage);
+ if (dProd0Storage) cudaFree(dProd0Storage);
+ if (dGot1Storage) cudaFree(dGot1Storage);
+ if (dGot0Storage) cudaFree(dGot0Storage);
+ if (dRef1Storage) cudaFree(dRef1Storage);
+ if (dRef0Storage) cudaFree(dRef0Storage);
+ if (dQ8) cudaFree(dQ8);
+ if (dX) cudaFree(dX);
+ if (dW1) cudaFree(dW1);
+ if (dW0) cudaFree(dW0);
+ if (stream) cudaStreamDestroy(stream);
+ };
+ if (!allocated) {
+ fprintf(stderr, "Q4_K 16-warp pair allocation failed: %s\n\n",
+ cudaGetErrorString(cudaGetLastError()));
+ cleanup();
+ return false;
+ }
+
+ float *const dRef0 = dRef0Storage + guard_floats;
+ float *const dRef1 = dRef1Storage + guard_floats;
+ float *const dGot0 = dGot0Storage + guard_floats;
+ float *const dGot1 = dGot1Storage + guard_floats;
+ float *const dProd0 = dProd0Storage + guard_floats;
+ float *const dProd1 = dProd1Storage + guard_floats;
+ void *const dScratch =
+ static_cast(dScratchStorage) + guard_bytes;
+ cudaError_t enqueue_err = cudaMemcpyAsync(
+ dW0, W0.data(), W0.size() * sizeof(block_q4_K),
+ cudaMemcpyHostToDevice, stream);
+ if (enqueue_err == cudaSuccess) {
+ enqueue_err = cudaMemcpyAsync(
+ dW1, W1.data(), W1.size() * sizeof(block_q4_K),
+ cudaMemcpyHostToDevice, stream);
+ }
+ if (enqueue_err == cudaSuccess) {
+ enqueue_err = cudaMemcpyAsync(
+ dX, X.data(), X.size() * sizeof(float),
+ cudaMemcpyHostToDevice, stream);
+ }
+ if (enqueue_err == cudaSuccess) {
+ enqueue_err = cudaMemsetAsync(
+ dRef0Storage, ref0_guard_byte, guarded0, stream);
+ }
+ if (enqueue_err == cudaSuccess) {
+ enqueue_err = cudaMemsetAsync(
+ dRef1Storage, ref1_guard_byte, guarded1, stream);
+ }
+ if (enqueue_err == cudaSuccess) {
+ enqueue_err = cudaMemsetAsync(
+ dGot0Storage, got0_guard_byte, guarded0, stream);
+ }
+ if (enqueue_err == cudaSuccess) {
+ enqueue_err = cudaMemsetAsync(
+ dGot1Storage, got1_guard_byte, guarded1, stream);
+ }
+ if (enqueue_err == cudaSuccess) {
+ enqueue_err = cudaMemsetAsync(
+ dProd0Storage, prod0_guard_byte, guarded0, stream);
+ }
+ if (enqueue_err == cudaSuccess) {
+ enqueue_err = cudaMemsetAsync(
+ dProd1Storage, prod1_guard_byte, guarded1, stream);
+ }
+ if (enqueue_err == cudaSuccess) {
+ enqueue_err = cudaMemsetAsync(
+ dScratchStorage, scratch_guard_byte, scratch_guarded_bytes,
+ stream);
+ }
+
+ const int rc_quant = enqueue_err == cudaSuccess
+ ? ds4_mmq_q4_K_quantize_q8_1_for_test(
+ dX, dQ8, q8_bytes, N, K, stream)
+ : -100;
+ const int rc_ref0 = rc_quant == 0
+ ? ds4_mmq_q4_K_dense_preq_reference_for_test(
+ dW0, dQ8, q8_bytes, dRef0, M0, N, K,
+ /*use_stream_k=*/1,
+ dScratch, scratch_bytes,
+ stream)
+ : -100;
+ const int rc_ref1 = rc_ref0 == 0
+ ? ds4_mmq_q4_K_dense_preq_reference_for_test(
+ dW1, dQ8, q8_bytes, dRef1, M1, N, K,
+ /*use_stream_k=*/1,
+ dScratch, scratch_bytes,
+ stream)
+ : -100;
+ std::vector ref_scratch_guards(2u * guard_bytes);
+ if (enqueue_err == cudaSuccess && rc_ref1 == 0) {
+ enqueue_err = enqueue_scratch_guard_copy(
+ dScratchStorage, scratch_bytes, guard_bytes,
+ ref_scratch_guards.data(), stream);
+ }
+ const int rc_got0 = rc_ref1 == 0 && enqueue_err == cudaSuccess
+ ? ds4_mmq_q4_K_dense_16warp_streamk_enqueue(
+ dW0, dQ8, dGot0, dScratch, scratch_bytes,
+ M0, N, K, nsm, stream)
+ : -100;
+ const int rc_got1 = rc_got0 == 0
+ ? ds4_mmq_q4_K_dense_16warp_streamk_enqueue(
+ dW1, dQ8, dGot1, dScratch, scratch_bytes,
+ M1, N, K, nsm, stream)
+ : -100;
+ std::vector got_scratch_guards(2u * guard_bytes);
+ if (enqueue_err == cudaSuccess && rc_got1 == 0) {
+ enqueue_err = enqueue_scratch_guard_copy(
+ dScratchStorage, scratch_bytes, guard_bytes,
+ got_scratch_guards.data(), stream);
+ }
+ const int rc_pair = rc_got1 == 0 && enqueue_err == cudaSuccess
+ ? ds4_mmq_q4_K_dense_pair(
+ dW0, dW1, dX, dProd0, dProd1, M0, M1, N, K, stream)
+ : -100;
+
+ std::vector ref0_guarded(guarded0);
+ std::vector ref1_guarded(guarded1);
+ std::vector got0_guarded(guarded0);
+ std::vector got1_guarded(guarded1);
+ std::vector prod0_guarded(guarded0);
+ std::vector prod1_guarded(guarded1);
+ if (rc_pair == 0) {
+ enqueue_err = cudaMemcpyAsync(
+ ref0_guarded.data(), dRef0Storage, guarded0,
+ cudaMemcpyDeviceToHost, stream);
+ }
+ if (enqueue_err == cudaSuccess && rc_pair == 0) {
+ enqueue_err = cudaMemcpyAsync(
+ ref1_guarded.data(), dRef1Storage, guarded1,
+ cudaMemcpyDeviceToHost, stream);
+ }
+ if (enqueue_err == cudaSuccess && rc_pair == 0) {
+ enqueue_err = cudaMemcpyAsync(
+ got0_guarded.data(), dGot0Storage, guarded0,
+ cudaMemcpyDeviceToHost, stream);
+ }
+ if (enqueue_err == cudaSuccess && rc_pair == 0) {
+ enqueue_err = cudaMemcpyAsync(
+ got1_guarded.data(), dGot1Storage, guarded1,
+ cudaMemcpyDeviceToHost, stream);
+ }
+ if (enqueue_err == cudaSuccess && rc_pair == 0) {
+ enqueue_err = cudaMemcpyAsync(
+ prod0_guarded.data(), dProd0Storage, guarded0,
+ cudaMemcpyDeviceToHost, stream);
+ }
+ if (enqueue_err == cudaSuccess && rc_pair == 0) {
+ enqueue_err = cudaMemcpyAsync(
+ prod1_guarded.data(), dProd1Storage, guarded1,
+ cudaMemcpyDeviceToHost, stream);
+ }
+ const cudaError_t sync_err = cudaStreamSynchronize(stream);
+
+ struct leg_result {
+ size_t mismatches = 0;
+ size_t nonfinite_ref = 0;
+ size_t nonfinite_got = 0;
+ size_t ref_canary = 0;
+ size_t got_canary = 0;
+ size_t first_bad = SIZE_MAX;
+ uint32_t first_ref_bits = 0;
+ uint32_t first_got_bits = 0;
+ };
+ const auto inspect_leg = [&](const std::vector &ref,
+ const std::vector &got,
+ size_t count, size_t output_bytes,
+ uint8_t expected_ref,
+ uint8_t expected_got) {
+ leg_result result;
+ if (enqueue_err != cudaSuccess || sync_err != cudaSuccess ||
+ rc_pair != 0) {
+ return result;
+ }
+ for (size_t i = 0; i < count; ++i) {
+ const uint8_t *const ref_ptr =
+ ref.data() + guard_bytes + i * sizeof(float);
+ const uint8_t *const got_ptr =
+ got.data() + guard_bytes + i * sizeof(float);
+ float ref_value = 0.0f;
+ float got_value = 0.0f;
+ std::memcpy(&ref_value, ref_ptr, sizeof(ref_value));
+ std::memcpy(&got_value, got_ptr, sizeof(got_value));
+ if (!std::isfinite(ref_value)) result.nonfinite_ref++;
+ if (!std::isfinite(got_value)) result.nonfinite_got++;
+ if (std::memcmp(ref_ptr, got_ptr, sizeof(float)) != 0) {
+ if (result.first_bad == SIZE_MAX) {
+ result.first_bad = i;
+ std::memcpy(&result.first_ref_bits, ref_ptr,
+ sizeof(result.first_ref_bits));
+ std::memcpy(&result.first_got_bits, got_ptr,
+ sizeof(result.first_got_bits));
+ }
+ result.mismatches++;
+ }
+ }
+ for (size_t i = 0; i < guard_bytes; ++i) {
+ if (ref[i] != expected_ref) result.ref_canary++;
+ if (got[i] != expected_got) result.got_canary++;
+ }
+ for (size_t i = guard_bytes + output_bytes; i < ref.size(); ++i) {
+ if (ref[i] != expected_ref) result.ref_canary++;
+ }
+ for (size_t i = guard_bytes + output_bytes; i < got.size(); ++i) {
+ if (got[i] != expected_got) result.got_canary++;
+ }
+ return result;
+ };
+
+ const leg_result leg0 = inspect_leg(
+ ref0_guarded, got0_guarded, count0, bytes0,
+ ref0_guard_byte, got0_guard_byte);
+ const leg_result leg1 = inspect_leg(
+ ref1_guarded, got1_guarded, count1, bytes1,
+ ref1_guard_byte, got1_guard_byte);
+ const leg_result prod0 = inspect_leg(
+ ref0_guarded, prod0_guarded, count0, bytes0,
+ ref0_guard_byte, prod0_guard_byte);
+ const leg_result prod1 = inspect_leg(
+ ref1_guarded, prod1_guarded, count1, bytes1,
+ ref1_guard_byte, prod1_guard_byte);
+ const size_t ref_scratch_canary =
+ scratch_guard_mismatches(ref_scratch_guards, scratch_guard_byte);
+ const size_t got_scratch_canary =
+ scratch_guard_mismatches(got_scratch_guards, scratch_guard_byte);
+
+ // REQUIRE must reject the whole pair before either leg can enqueue. A
+ // 384-row second leg is aligned but below the pair admission floor; poison
+ // both complete guarded ranges so even a partial first-leg launch is seen.
+ int rc_reject = -100;
+ size_t reject_writes = SIZE_MAX;
+ cudaError_t reject_sync = cudaSuccess;
+ if (enqueue_err == cudaSuccess && sync_err == cudaSuccess && rc_pair == 0) {
+ cudaError_t reject_err = cudaMemsetAsync(
+ dProd0Storage, reject_guard_byte, guarded0, stream);
+ if (reject_err == cudaSuccess) {
+ reject_err = cudaMemsetAsync(
+ dProd1Storage, reject_guard_byte, guarded1, stream);
+ }
+ rc_reject = reject_err == cudaSuccess
+ ? ds4_mmq_q4_K_dense_pair(
+ dW0, dW1, dX, dProd0, dProd1,
+ M0, /*M1=*/384, N, K, stream)
+ : -100;
+ std::vector rejected0(guarded0);
+ std::vector rejected1(guarded1);
+ if (reject_err == cudaSuccess) {
+ reject_err = cudaMemcpyAsync(
+ rejected0.data(), dProd0Storage, guarded0,
+ cudaMemcpyDeviceToHost, stream);
+ }
+ if (reject_err == cudaSuccess) {
+ reject_err = cudaMemcpyAsync(
+ rejected1.data(), dProd1Storage, guarded1,
+ cudaMemcpyDeviceToHost, stream);
+ }
+ reject_sync = cudaStreamSynchronize(stream);
+ if (reject_err == cudaSuccess && reject_sync == cudaSuccess) {
+ reject_writes = 0;
+ for (uint8_t byte : rejected0) {
+ if (byte != reject_guard_byte) reject_writes++;
+ }
+ for (uint8_t byte : rejected1) {
+ if (byte != reject_guard_byte) reject_writes++;
+ }
+ }
+ }
+ const bool rejection_ok =
+ rc_reject == DS4_MMQ_NOT_APPLICABLE &&
+ reject_sync == cudaSuccess && reject_writes == 0;
+ const bool ok = rc_quant == 0 && rc_ref0 == 0 && rc_ref1 == 0 &&
+ rc_got0 == 0 && rc_got1 == 0 && rc_pair == 0 &&
+ enqueue_err == cudaSuccess &&
+ sync_err == cudaSuccess && leg0.mismatches == 0 &&
+ leg1.mismatches == 0 && prod0.mismatches == 0 &&
+ prod1.mismatches == 0 && leg0.nonfinite_ref == 0 &&
+ leg0.nonfinite_got == 0 && leg1.nonfinite_ref == 0 &&
+ leg1.nonfinite_got == 0 && prod0.nonfinite_got == 0 &&
+ prod1.nonfinite_got == 0 && leg0.ref_canary == 0 &&
+ leg0.got_canary == 0 && leg1.ref_canary == 0 &&
+ leg1.got_canary == 0 && prod0.got_canary == 0 &&
+ prod1.got_canary == 0 && ref_scratch_canary == 0 &&
+ got_scratch_canary == 0 && rejection_ok;
+ fprintf(stderr,
+ "quant/ref0/ref1/16w0/16w1/pair=%d/%d/%d/%d/%d/%d "
+ "enqueue=%s sync=%s bits(raw/prod)=%zu/%zu,%zu/%zu "
+ "nonfinite(ref/raw/prod)=%zu/%zu/%zu,%zu/%zu/%zu "
+ "canary(ref/raw/prod)=%zu/%zu/%zu,%zu/%zu/%zu "
+ "scratch_canary(ref/16w)=%zu/%zu "
+ "reject=%d/%zu reject_sync=%s: %s\n",
+ rc_quant, rc_ref0, rc_ref1, rc_got0, rc_got1, rc_pair,
+ cudaGetErrorString(enqueue_err), cudaGetErrorString(sync_err),
+ leg0.mismatches, prod0.mismatches,
+ leg1.mismatches, prod1.mismatches,
+ leg0.nonfinite_ref, leg0.nonfinite_got, prod0.nonfinite_got,
+ leg1.nonfinite_ref, leg1.nonfinite_got, prod1.nonfinite_got,
+ leg0.ref_canary, leg0.got_canary, prod0.got_canary,
+ leg1.ref_canary, leg1.got_canary, prod1.got_canary,
+ ref_scratch_canary, got_scratch_canary,
+ rc_reject, reject_writes, cudaGetErrorString(reject_sync),
+ ok ? "PASS" : "FAIL");
+ if (leg0.first_bad != SIZE_MAX) {
+ fprintf(stderr,
+ "first pair leg0 mismatch at output[%zu]: "
+ "ref=0x%08x got=0x%08x\n",
+ leg0.first_bad, leg0.first_ref_bits, leg0.first_got_bits);
+ }
+ if (leg1.first_bad != SIZE_MAX) {
+ fprintf(stderr,
+ "first pair leg1 mismatch at output[%zu]: "
+ "ref=0x%08x got=0x%08x\n",
+ leg1.first_bad, leg1.first_ref_bits, leg1.first_got_bits);
+ }
+ if (prod0.first_bad != SIZE_MAX) {
+ fprintf(stderr,
+ "first pair production leg0 mismatch at output[%zu]: "
+ "ref=0x%08x got=0x%08x\n",
+ prod0.first_bad, prod0.first_ref_bits, prod0.first_got_bits);
+ }
+ if (prod1.first_bad != SIZE_MAX) {
+ fprintf(stderr,
+ "first pair production leg1 mismatch at output[%zu]: "
+ "ref=0x%08x got=0x%08x\n",
+ prod1.first_bad, prod1.first_ref_bits, prod1.first_got_bits);
+ }
+ fputc('\n', stderr);
+ cleanup();
+ return ok;
+}
+
+// Prefill dense-pair verifier. The candidate shares only the canonical
+// token-tiled Q8_1 activation; both weight legs still run the ordinary Q4_K
+// MMQ kernel, so their outputs must match two independent dense calls bitwise.
+bool run_q4_K_dense_pair_parity(
+ int M0, int M1, int N, int K, uint32_t seed) {
+ fprintf(stderr,
+ "=== Q4_K/DENSE_PAIR M0=%d M1=%d N=%d K=%d seed=%u ===\n",
+ M0, M1, N, K, seed);
+
+ std::mt19937 rng(seed);
+ std::normal_distribution nd(0.0f, 1.0f);
+ const int blocks_per_row = K / QK_K_LOCAL;
+ std::vector W0((size_t)M0 * blocks_per_row);
+ std::vector W1((size_t)M1 * blocks_per_row);
+ for (auto &blk : W0) generate_random_block_q4_K(&blk, rng);
+ for (auto &blk : W1) generate_random_block_q4_K(&blk, rng);
+ std::vector X((size_t)N * K);
+ for (auto &v : X) v = nd(rng);
+
+ cudaStream_t stream;
+ cudaStreamCreate(&stream);
+ void *dW0 = nullptr;
+ void *dW1 = nullptr;
+ float *dX = nullptr;
+ float *dRef0 = nullptr;
+ float *dRef1 = nullptr;
+ float *dGot0 = nullptr;
+ float *dGot1 = nullptr;
+ cudaMalloc(&dW0, W0.size() * sizeof(block_q4_K));
+ cudaMalloc(&dW1, W1.size() * sizeof(block_q4_K));
+ cudaMalloc(&dX, X.size() * sizeof(float));
+ cudaMalloc(&dRef0, (size_t)M0 * N * sizeof(float));
+ cudaMalloc(&dRef1, (size_t)M1 * N * sizeof(float));
+ cudaMalloc(&dGot0, (size_t)M0 * N * sizeof(float));
+ cudaMalloc(&dGot1, (size_t)M1 * N * sizeof(float));
+ cudaMemcpyAsync(dW0, W0.data(), W0.size() * sizeof(block_q4_K),
+ cudaMemcpyHostToDevice, stream);
+ cudaMemcpyAsync(dW1, W1.data(), W1.size() * sizeof(block_q4_K),
+ cudaMemcpyHostToDevice, stream);
+ cudaMemcpyAsync(dX, X.data(), X.size() * sizeof(float),
+ cudaMemcpyHostToDevice, stream);
+ cudaMemsetAsync(dRef0, 0xa5, (size_t)M0 * N * sizeof(float), stream);
+ cudaMemsetAsync(dRef1, 0xa5, (size_t)M1 * N * sizeof(float), stream);
+ cudaMemsetAsync(dGot0, 0x5a, (size_t)M0 * N * sizeof(float), stream);
+ cudaMemsetAsync(dGot1, 0x5a, (size_t)M1 * N * sizeof(float), stream);
+
+ const int rc0 = ds4_mmq_q4_K_dense(
+ dW0, dX, dRef0, M0, N, K, stream);
+ const int rc1 = ds4_mmq_q4_K_dense(
+ dW1, dX, dRef1, M1, N, K, stream);
+ const int rcp = ds4_mmq_q4_K_dense_pair(
+ dW0, dW1, dX, dGot0, dGot1, M0, M1, N, K, stream);
+
+ std::vector ref0((size_t)M0 * N);
+ std::vector ref1((size_t)M1 * N);
+ std::vector got0((size_t)M0 * N);
+ std::vector got1((size_t)M1 * N);
+ cudaMemcpyAsync(ref0.data(), dRef0, ref0.size() * sizeof(float),
+ cudaMemcpyDeviceToHost, stream);
+ cudaMemcpyAsync(ref1.data(), dRef1, ref1.size() * sizeof(float),
+ cudaMemcpyDeviceToHost, stream);
+ cudaMemcpyAsync(got0.data(), dGot0, got0.size() * sizeof(float),
+ cudaMemcpyDeviceToHost, stream);
+ cudaMemcpyAsync(got1.data(), dGot1, got1.size() * sizeof(float),
+ cudaMemcpyDeviceToHost, stream);
+ const cudaError_t sync_err = cudaStreamSynchronize(stream);
+
+ size_t bad0 = 0;
+ size_t bad1 = 0;
+ for (size_t i = 0; i < ref0.size(); i++) {
+ if (std::memcmp(&ref0[i], &got0[i], sizeof(float)) != 0) bad0++;
+ }
+ for (size_t i = 0; i < ref1.size(); i++) {
+ if (std::memcmp(&ref1[i], &got1[i], sizeof(float)) != 0) bad1++;
+ }
+
+ cudaFree(dW0);
+ cudaFree(dW1);
+ cudaFree(dX);
+ cudaFree(dRef0);
+ cudaFree(dRef1);
+ cudaFree(dGot0);
+ cudaFree(dGot1);
+ cudaStreamDestroy(stream);
+
+ const bool ok = rc0 == 0 && rc1 == 0 && rcp == 0 &&
+ sync_err == cudaSuccess && bad0 == 0 && bad1 == 0;
+ fprintf(stderr,
+ "pair rc=%d/%d/%d sync=%s mismatches=%zu/%zu: %s\n\n",
+ rc0, rc1, rcp, cudaGetErrorString(sync_err), bad0, bad1,
+ ok ? "PASS" : "FAIL");
+ return ok;
+}
+
+// Prefill attention output-A verifier. The grouped entry consumes
+// X=[N][G][K] and writes out=[N][G][M]. Build the reference with exactly G
+// ordinary dense calls, using D2D 2D copies to pack/unpack each group. This
+// keeps the quantizer and MMQ reduction tree identical while independently
+// checking the grouped entry's strided quantization and output pitch.
+bool run_q4_K_grouped_dense_parity(
+ int M, int N, int K, int n_groups, uint32_t seed,
+ bool inject_nonfinite = false) {
+ fprintf(stderr,
+ "=== Q4_K/GROUPED_DENSE M=%d N=%d K=%d groups=%d seed=%u%s ===\n",
+ M, N, K, n_groups, seed,
+ inject_nonfinite ? " nonfinite" : "");
+
+ std::mt19937 rng(seed);
+ std::normal_distribution nd(0.0f, 1.0f);
+ const int blocks_per_row = K / QK_K_LOCAL;
+ const size_t blocks_per_group = (size_t)M * blocks_per_row;
+ std::vector