Repository navigation
Allow using prompt files. - #59
Merged
Merged
Conversation
jesusmb1995
pushed a commit
to jesusmb1995/llama.cpp
that referenced
this pull request
Nov 25, 2025
QVAC-7519: Fix dynamic libs path with vcpkg install
jesusmb1995
pushed a commit
to jesusmb1995/llama.cpp
that referenced
this pull request
Nov 27, 2025
QVAC-7519: Fix dynamic libs path with vcpkg install
rururush
pushed a commit
to USTC-ADSL/llama.cpp
that referenced
this pull request
Mar 16, 2026
* Add power management utilities to NPU device context and update DCVS settings * Update DCVS settings in power_utils to use v3 API and enhance power management * wip * Enhance dequantization functions by adding load_dequant_table support and updating signatures for improved performance * use lut * wip * fix test failure * wip * Refactor load_qual_block_generic to improve block handling and optimize vector operations * Enhance load_dual_block_generic and load_qual_block_generic to accept a mask parameter for improved block handling * Refactor flash_attn_impl to optimize mask l2 prefetch * wip * wip * wip * wip * add log * link against shared libraries instead of static ones * fix swiglu * wip * refactor expf_fix to handle overflow for different data types * enhance is_glu_op_supported to validate shapes for multiple sources * wip * refactor logging macros to use hexagon namespace and improve formatting * fix printf format error * wip * refactor: update static_assert messages for block size validation and add HVX_VectorPred_x3 type alias * rename * feat: enhance fa with mask * wip * wip * refactor: replace instances of Q6_V_vzero() with kZeroV for consistency * wip * wip * wip * fix: improve address alignment check in HVX_Vector handling * refactor: streamline vector dot product implementations for improved readability * refactor: q4k add hvx intrinsic impl * refactor: enhance dequantize_row_q4_K for clarity and performance * refactor: optimize scale mask usage in dequantization functions for improved performance * refactor: optimize dequantize_row_q4_K for intrinsic usage and performance improvements * refactor: move GLU operation implementation into separated file * sync after swiglu * wip * wip * wip * feat: increase prc main thread stack size * fix: replace hardcoded stack size with NPU_THREAD_STACK_SIZE constant * wip * feat: add optimized vector operations for exponential and division with overflow handling * wip * feat: refactor exponential function to handle overflow and underflow with improved logic * wip * wip * feat: add vector loading and scaling functions for improved performance in block processing * wip * feat: optimize block loading by refactoring scale index handling for improved performance * use Q6_Vb_vlut32_VbVbR_nomatch instead * feat: enhance scale loading by adding static assertion and restructuring block handling * wip * feat: refactor vec_dot_product_mixed_impl for improved clarity and performance * wip * feat: simplify vector loading functions and improve alignment handling * wip * feat: enhance scale loading mask with quantization block size validation * wip * feat: implement make_scale_load_mask function and refactor vector handling in vec_ops * feat: enhance load_dual_block_generic to include scale indices for improved vector loading * revert q8 dequant * wip * feat: optimize dequantization functions by removing unnecessary masking and updating lookup methods * wip * wip * add qurt_mutex * Add DMA transfer class and integrate into thread pool * Enhance DMA transfer functionality by adding support for multiple descriptors and initiating transfers in parallel * fix dma crash * fix failed unit tests * wip * use alignas * Improve DMA transfer error handling and update descriptor completion check * Fix VTCM cache size calculation in element-wise operations * Add cache clean operations before DMA transfers in element-wise operations * reduce cache clean operations * Refactor DMA transfer functions to support 1D operations and rename for clarity * Enhance DMA transfer functionality by adding 2D submission support and improving descriptor initialization * Update read buffer method to support forced invalidation and remove unnecessary invalidation calls in element-wise operations * wip * Improve DMA transfer handling in mul_mat_gemv_impl by replacing memcpy with initiate_dma_row_transfer and adding wait_for_dma logic * fix 2d dma * feat: add DMA plane cache * rename * wip * use memcpy for debug * fix cache plane calc * refactor: remove debug logging from mul_mat_impl and optimize cache handling * rename * fix 2d dma type * refactor: enhance DMA transfer handling in mul_mat_gemv_impl and wait functions * refactor: optimize DMA transfer handling in mul_mat_gemv_impl and wait functions * wip * wip * move op impl into sub dir * add log * fix: correct pointer usage in mul_mat_gemv_impl for next plane access * fix: improve DMA transfer error handling in mul_mat_impl and mul_mat_gemv_impl * fix: fix crash by using the entire row bytes * wip * wip * fix: prevent parallelization for scalar src1 in is_mul_mat_supported * fix: add dimension checks for 2D DMA transfers and fallback to 1D if necessary * wip * fix: enable thread barrier for mul multiplication operations * feat: add synchronization checks for tensor operations and update related functions * wip * fix: remove invalidation flag from get_read_buffer calls in element-wise and matrix multiplication operations * Revert "fix: remove invalidation flag from get_read_buffer calls in element-wise and matrix multiplication operations" This reverts commit af3441e. * wip * wip * add comment * fix: improve DMA transfer handling in mul_mat_gemv_impl for quantized source tensors * add log * try fix mulmat gemv * wip * fix: enhance DMA transfer handling in mul_mat_gemv_impl for quantized source tensors * fix: optimize cache offset calculation and remove redundant swap in mul_mat_gemv_impl * fix: refactor DMA transfer handling in mul_mat_gemv_impl for improved clarity and maintainability * wip * wip * wip * fix: enhance mul_mat_impl for improved cache handling and clarity * fix: refactor tensor unflattening and DMA transfer initialization for improved clarity and type safety * fix: improve cache handling of quant * wip * fix: improve cache handling in mul_mat_impl and mul_mat_gemv_impl for better memory efficiency * rename * add load_hexa_block_generic * wip * extract dequant block into separated function * refactor: enhance dequantization functions with table parameter * fix load_dual_block_generic * refactor: rename dequantization functions for clarity and enhance block handling * refactor: simplify dequantization logic by consolidating block handling and removing unused parameters * wip * wip * feat: add make_qs_load_mask function and update load_dual_block_generic to use qs_indices * fix load_dual_block_generic * refactor: update load functions to use qs_indices for improved block loading * wip * fix: update loop indices and boundary checks to use size_t for better efficiency * wip * update make_scale_load_mask, to make it available for q8 * feat: add vec_dot_product_quant_impl for quantized dot product computation * refactoring: move come quant func to dedicated file * refactor: rename dequantization functions for clarity and consistency * wip * feat: enhance vec_dot_product_quant_impl with dual dequantization and improved assertions * add vec_dot_product_vqf32_q40_f32 * wip * wip * wip * wip * implement vec_mpy_qf32_qf32_qf32 function and update vec_dot_product_vqf32_q40_f32 to use it * wip * add src0_plane_write_cache_offset * wip * enhance mul_mat_f32 to handle NPU_DATA_TYPE_Q4_0 for quantized matrix multiplication * wip * wip * update test func * refactor mul_mat_gemv_quant_impl to use get_nb for row stride and remove unused test function in init_f16_f32_table * wip * Add support for 4-block dequantization in vec_quant and update dot product implementation * Refactor vec_dot_product_quant_impl to improve variable handling and enhance readability * Refactor vec_dot_product_quant_impl to replace template function with inline vector operations * use Q6_Vqf32_vmpy_VsfVsf instead of Q6_Vqf32_vmpy_Vqf32Vqf32 * Revert "use Q6_Vqf32_vmpy_VsfVsf instead of Q6_Vqf32_vmpy_Vqf32Vqf32" This reverts commit 5483916. * wip * improve log print in graph * Refactor batched_row_dot to accept additional arguments and remove batched_row_dot_with_table * Refactor synchronization functions to include previous operation and NE type parameters * Refactor synchronization checks in several operations * Update synchronization checks to include NPU_OP_COUNT in required conditions * Add performance tracking to buffer management functions * add memset * add log * fix: update backend device type from ACCEL to IGPU * fix comment * add get/set rows * feat: implement row operation support checks in is_rows_supported * feat: add support for I64 data type in rows operations * feat: implement set_rows functionality for I32 and I64 data types * wip * fix set_rows * feat: extend is_rows_supported to allow F32 data type in destination * wip * feat: rename set_rows function, add generic to its name * disable q4_k * move ops to separated file * rename: op_impl -> op_registry * refactor: update get_data_type struct to include output type for unary operations * refactor: simplify vec_trans_impl by removing parameterized overload and using variadic templates * add vec_trans_with_half_ret_impl * add NPU_OP_CPY * refactor: enhance is_unary_op_supported to handle non-continuous rows and add type support logging * refactor: update vec_trans_with_half_ret_impl to use processed_bytes for clarity and accuracy * wip * refactor: optimize dequantize_vec_q40_qf32_4blocks by improving shuffling logic and reducing redundancy * refactor: improve performance of vec_dot_product and dequantize functions by optimizing shuffling logic * wip * add dequantize_vec_q40_qf32_6blocks * feat: add load_dequant_vec_q40_qf32_6blocks function for 6-block dequantization * feat: enhance vec_dot_product_quant_impl with 6-element processing loop for improved performance * Revert "feat: enhance vec_dot_product_quant_impl with 6-element processing loop for improved performance" This reverts commit a5c8fa3. since there's a performance degradation * fix: correct load_hexa_block_generic return type and update dequantization logic * wip * wip * feat: add make_q40_qs_load_mask function and update vec_dot_product_vqf32_q40_f32 * fix dequant load * add debug log * wip * wip * fix shuffle index array * refactor: simplify load mask generation and improve index shuffling for q4 blocks * wip * wip * fix comment * wip * update ops.md * update ops.md by create_ops_docs.py # Conflicts: # docs/ops.md
InfernalDread
referenced
this pull request
in InfernalDread/llama.cpp
Apr 23, 2026
InfernalDread
referenced
this pull request
in InfernalDread/llama.cpp
Apr 23, 2026
…se-wht fix: inverse WHT in test-turbo-quant.c round-trip (#59)
InfernalDread
referenced
this pull request
in InfernalDread/llama.cpp
Apr 23, 2026
Seunghhon
pushed a commit
to Seunghhon/llama.cpp
that referenced
this pull request
Apr 26, 2026
Jcfunk
pushed a commit
to Jcfunk/llama.cpp
that referenced
this pull request
May 13, 2026
ckti
pushed a commit
to ckti/llama.cpp-consolidated
that referenced
this pull request
May 22, 2026
jimbothigpen
added a commit
to jimbothigpen/af-engn
that referenced
this pull request
May 29, 2026
The meta backend already handles quantized KV correctly: axis-0 split uses head-aligned granularity, view/permute propagation maps to axis-2 for flash_attn_ext, and turbo set_rows kernels handle quantized writes. Remove the defensive block and log the configuration instead. Ported from buun spiritbuun/buun-llama-cpp commit 0530f51 (ggml-org#59). Co-Authored-By: Claude Haiku 4.5 <[email protected]>
jimbothigpen
added a commit
to jimbothigpen/af-engn
that referenced
this pull request
May 29, 2026
The meta backend's tensor-split planner didn't know how to propagate split state through GGML_OP_TURBO_WHT, causing an abort on multi-GPU setups with turbo KV cache quantization. TURBO_WHT is an elementwise transform (128-element WHT groups along axis 0), so handle_generic with scalar_only=false is correct — same as GLU and other elementwise ops. Ported from buun spiritbuun/buun-llama-cpp commit 9b1ffc6 (ggml-org#59). Co-Authored-By: Claude Haiku 4.5 <[email protected]>
InfernalDread
referenced
this pull request
in InfernalDread/llama.cpp
Jun 11, 2026
Builds Mac Metal (arm64) and Windows CUDA (12.4) on tag push.
Creates GitHub release with prebuilt binaries.
vulkan: TQ4_1s support for model weights (#69)
* vulkan: add TQ4_1S weight compression support
Adds Vulkan shader support for TQ4_1S (4-bit WHT-rotated weight
compression with 16 Lloyd-Max centroids, 32-element blocks).
Shaders:
- dequant_tq4_1s.comp: standalone dequant with WHT inverse via
subgroupShuffleXor (32-thread workgroup, 5-stage butterfly)
- mul_mat_vec_tq4_1s.comp: specialized MUL_MAT_VEC with inline
activation pre-rotation (forward RHT on activation, centroid*scale
dequant without inverse RHT)
- copy_from_quant.comp: TQ4_1S dequant path with full WHT inverse
- copy_to_quant.comp: TQ4_1S SET_ROWS quantization path with forward
RHT, dual half-block RMS scales, 16-centroid quantization
- types.glsl: block_tq4_1s struct (d0, d1, qs[16])
- dequant_funcs.glsl: TQ4_1S centroid*scale dequant (no RHT)
Pipeline wiring (ggml-vulkan.cpp):
- MUL_MAT, SET_ROWS, CPY supports_op
- pipeline_dequant, pipeline_set_rows, pipeline_cpy_quant_f32
- Specialized MUL_MAT_VEC with forced subgroup workgroup size
Tests:
- test_set_rows_tq4_1s: SET_ROWS round-trip validation
* vulkan: add fused mul_mat_vec kernel for TQ4_1S
Adds a specialised MUL_MAT_VEC shader for TQ4_1S weights so the
per-decode-step matrix-vector product no longer has to dequant the
full weight tensor to f16 and then go through the generic matmul
path. The kernel pre-rotates the activation via a forward
Walsh-Hadamard Transform in shared memory and dot-products against
the raw centroid*scale stored weights, folding the inverse-WHT on
the weight side into the activation by the symmetry H = H^T.
Math:
w[k] = sign[k] * INV_SQRT32 * (H @ stored)[k]
sum_k w[k] * a[k] = INV_SQRT32 * sum_j stored[j] * (H @ (sign * a))[j]
Portability choices:
- Workgroup size is pinned to 32 threads regardless of the
DMMV_WG_SIZE bucket the rest of the mul_mat_vec family picks for
the current architecture. The butterfly operates on 32-element
blocks with one element per thread; that contract is fixed by the
quantization format, not by the GPU. Earlier revisions used
`gl_WorkGroupSize.x` as the stride unit, which silently skipped
half the work on Intel drivers that force the subgroup to 16
(tests passed via NMSE tolerance while real inference output was
garbage).
- Butterfly implementation is shared memory only. A subgroup-shuffle
variant (`subgroupShuffleXor`) was prototyped and measured on Intel
Arc A380 with Mesa Xe HPG: it ran ~60-85 %% slower than the
explicit shared-memory butterfly, because Mesa emulates subgroup
shuffles via LDS and ends up doing the same LDS traffic with extra
driver overhead. The shared-memory butterfly is correct on every
device regardless of subgroup-op support, is the fastest path on
every device we can actually measure, and leaves the
`pipeline_dequant_mul_mat_vec_f32_f32[w][TQ4_1S]` slot uniform
across all DMMV_WG_SIZE buckets.
- Reduction is the shared-memory tree reduction (no subgroupAdd), for
the same reason: on Intel Arc the subgroupAdd is also LDS-backed
and the hybrid reduction path was measurably slower. Future
vendor-specific heuristics can switch to the hybrid or pure-subgroup
reduction variants on NVIDIA / AMD RDNA if hardware subgroup ops
turn out to beat the LDS roundtrip there; the existing reduction
modes in `mul_mat_vec_base.glsl` already provide the necessary
variants.
- NUM_ROWS is 8 so the butterfly cost amortises across 8 output rows
per workgroup. Each thread holds one position of each of the 8
weight blocks and pairs them with the shared rotated activation.
- `mul_mm` and `flash_attn_cm2` shader generation is skipped for
TQ4_1S because it is a weight-only format that never reaches the
coopmat2 matmul or the KV cache flash-attention paths.
Tests:
- `test-backend-ops` MUL_MAT tolerance tightened from 2.0 to 0.01
NMSE so real defects can't hide behind a loose check.
- Added Gemma-4 E2B, Qwen, Phi and Llama dimensional coverage
(k in {1536, 2048, 2304, 3072, 4096}, m in {256, 1152, 1536,
2048, 5120, 6144}, n in {1..8, 16, 64, 256}). 148 MUL_MAT test
cases total.
Verification (Intel Arc A380, 6 GB VRAM, Vulkan ANV / Mesa Xe HPG,
`llama-bench -p 512 -n 128 -r 3` and `llama-perplexity -c 512
--chunks 20 wiki.test.raw`):
| Model | Config | Size | Reduction | PPL ╬Ф | pp512/Q8 | tg128/Q8 |
|---------------|---------|----------:|----------:|-------:|---------:|---------:|
| Qwen2.5-1.5B | I | 1570тЖТ1082 | -31.1% | +4.66% | 53.9% | 107.5% |
| Phi-3.5-mini | I | 3873тЖТ2839 | -26.7% | +5.36% | 57.6% | 52.8% |
| Llama-3.2-3B | hybrid | 3263тЖТ2147 | -34.2% | +2.03% | 82.4% | 84.2% |
| Llama-3.2-3B | premium | 3263тЖТ2577 | -21.0% | +0.98% | 71.3% | 67.3% |
Qwen2.5-1.5B is faster than its own Q8_0 baseline with Config I:
the compressed model fits in less VRAM, and on a small model the
TQ4_1S compute cost is offset by the reduced memory traffic.
All four models produce coherent output end-to-end and the
reductions line up with the TurboQuant paper's validation matrix
(┬з5.8). The remaining gap to Q8_0 on the bigger models is
compute-bound on the A380; it closes further on GPUs with more raw
throughput.
* vulkan: restructure TQ4_1S inner loop for cross-row smem reuse
Splits the dequant+accumulate phase into two sub-loops:
1. Pre-compute w_vals[n] for all NUM_ROWS rows (centroid lookup +
scale multiply, reads from weight buffer only).
2. Read the rotated activation from shared memory ONCE per column,
then FMA across all rows in a tight register loop.
This is the Vulkan analogue of the 'hot loop load dedup' from the
CUDA kernel (PR #57 optimisation #2). It makes the shared memory
read explicitly loop-invariant across rows, which helps compilers
that don't auto-hoist LDS loads out of unrolled loops.
Measured effect on Intel Arc A380 (Llama-3.2-3B premium,
llama-bench tg128, r=5): 15.50 -> 15.78 t/s (+1.8%, within noise
but not a regression). The structure is cleaner regardless and
should benefit architectures with higher LDS latency.
fix: inverse WHT in test-turbo-quant.c round-trip (#59)
fix(metal): disable TurboFlash by default тАФ corrupt output on Apple10
The TurboFlash two-pass fused attention kernel produces garbage output
on M5 Max (Apple10/Metal4) for all turbo3 V configs. Disabling by
default routes turbo3 through the standard FA path which works correctly.
Users can opt-in with TURBO_FLASH=1 for testing/debugging.
No perf regression тАФ standard FA path matches TurboFlash speed within
noise (~55-57 t/s tg128 for q8_0/turbo3 on M5 Max).
Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
fix: gate turbo V unpad on V type, not K type
fix(hip): bypass pool for FA f16 temp buffers to prevent OOM
The legacy memory pool (ggml_cuda_pool_leg) retains peak-sized allocations
permanently. For quantized KV flash attention, the f16 dequant temp buffers
stay allocated in the pool after use, consuming more VRAM than the KV
compression saves. This causes quantized KV (q8_0, q4_0, turbo3, turbo4)
to OOM before f16 at equivalent context lengths on HIP/ROCm.
Fix: on HIP, allocate f16 temp buffers with raw hipMalloc and free with
hipFree (via RAII destructor) instead of the pool. Memory is released
after the FA kernel completes via hipStreamSynchronize.
Compared to commit 1 (VEC force), this approach recovers prefill:
pp32768 q8_0/q8_0: 1137 t/s (VEC) -> 3060 t/s (bypass) = +169%
pp32768 q8_0/turbo4: 1011 t/s (VEC) -> 3061 t/s (bypass) = +203%
Decode: unchanged across all configs
Trade-off: one hipStreamSynchronize per FA call (~5% overhead at 32k).
Can be eliminated in future with hipFreeAsync (stream-ordered free).
Root cause: ggml_cuda_pool_leg::free() stores buffers for reuse and never
calls cudaFree. On CUDA with VMM the OS can reclaim unused virtual memory.
On HIP without VMM (gfx1100/gfx1200), pool permanently consumes peak VRAM.
Confirmed hardware: gfx1201 (RX 9070 XT, 16GB, Windows 11, HIP 7.1)
Impact: CUDA/Metal unaffected (#ifdef GGML_USE_HIP)
Refs: ggml-org/llama.cpp#20969
Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
fix: force VEC FA path for quantized KV on HIP/ROCm
The TILE/MMA/WMMA FA paths allocate unbounded f16 temp buffers
proportional to full KV cache length for any quantized KV type.
On ROCm/HIP these pool allocations persist at peak size, meaning
the temp buffer VRAM exceeds the savings from KV compression.
This causes quantized KV (q8_0, q4_0, turbo3, turbo4) to OOM
before f16 at the same context length. Confirmed on gfx1100
(RX 7900 XT) and gfx1200 (RX 9060 XT). Also affects stock
llama.cpp q4_0/q8_0 (not TurboQuant-specific).
Fix: on HIP, force VEC path for quantized KV when available
(head_dim <= 256). VEC does inline dequant with no temp buffer.
Trade-off: prefill throughput may decrease (VEC processes queries
sequentially). Decode is unaffected since VEC was already selected
for single-token generation.
Limitation: head_dim > 256 (e.g. Gemma 4 full_attention d=512)
cannot use VEC and still routes through TILE. Bounded temp buffer
in a separate compilation unit is the proper fix for those cases
(see domvox/llama.cpp-turboquant-hip a13c3db12 discussion).
Refs: ggml-org/llama.cpp#20969 (community reports)
Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
vulkan: fix turbo3 build + coopmat FA after April upstream sync
Origin's April upstream-sync rebase interleaved two changes that left the
Vulkan turbo3 KV path broken:
* ggml-org/llama.cpp upstream PR #21572 (1f30ac0ce) moved fp16 RTE
rounding to a runtime SPIR-V patch and dropped the _rte shader
variants plus rte.glsl itself.
* TheTom/llama-cpp-turboquant PR #62 (ff8bb7394) added turbo3 KV
support against a base that still had those variants.
After the rebase, the tree had dangling cpy_f32_*_rte_len / _data
references, a two-arg SET_ROWS macro called with one arg, a
MMQ shader variants generated for turbo3_0 even though the flash_attn
MMQ path has no turbo3 code. The result was that ggml-vulkan.cpp
failed to compile on a clean checkout (spirv-headers + all of the
above) and the shader-gen emitted garbage variants.
Separately, turbo3 flash-attn pipelines were only wired up for
FA_SCALAR. On a coopmat-capable device (e.g. RADV on a 7900 XTX) the
tuning heuristic picks FA_COOPMAT1 for most shapes, which landed in
ggml_vk_flash_attn with an uninitialized pipeline (wg_denoms={0,0,0})
and tripped the Br == wg_denoms[0] assertion as soon as a prefill
ubatch was dispatched. End-to-end llama-cli on Vulkan + -ctk turbo3
aborted on the first real forward pass.
Changes:
* Drop the if (float_controls_rte_fp16) / else branches around
cpy_f32_quant pipeline creation and collapse SET_ROWS to a single
variant, matching upstream post-1f30ac0ce.
* Remove the #include "rte.glsl" from copy_to_quant.comp.
* Skip the MMQ flash_attn shader variant for turbo3_0 in the shader
generator (no MMQ code path for it).
* Register CREATE_FA(GGML_TYPE_TURBO3_0, turbo3_0, FA_COOPMAT1, _cm1)
and the _cm2 counterpart alongside the other quant types.
Verified on AMD 7900 XTX (gfx1100 / RADV NAVI31, ROCm 7.2.1 + Vulkan
1.4.341, spirv-headers 1.4.341.0):
* Full HIP+Vulkan build is clean with no shader compile errors.
* test-backend-ops -o SET_ROWS -b Vulkan0 : 147/147
* test-backend-ops -o FLASH_ATTN_EXT -b Vulkan0 -p type_KV=turbo3 :
530 cases pass (previously aborted on case 3).
* test-backend-ops -o FLASH_ATTN_EXT -b ROCm0 -p type_KV=turbo3 :
still green (no HIP regression).
* llama-cli on Qwen3-8B Q4_K_M with -ngl 99 -fa on -ctk turbo3
-ctv turbo3 on Vulkan0 no longer aborts. The remaining head_dim=128
correctness issue on the Vulkan turbo3 decode path is pre-existing
and orthogonal to this change.
llama-bench on Qwen3.5-27B Q4_K_M, 7900 XTX OC, HIP backend:
F16 tg128=20.98 turbo3 tg128=20.13 turbo4 tg128=20.17
Refs: TheTom/llama-cpp-turboquant issues #50, #64, #81
fix(metal): add turbo2/3/4 types to FLASH_ATTN_EXT and CPY support checks
fix nix build: Add spirv-headers to vulkanBuildInputs
ref: https://github.com/TheTom/llama-cpp-turboquant/issues/81
spirv-headers were introduced by
https://github.com/TheTom/llama-cpp-turboquant/commit/1f30ac0ceac0e2b4400069d81857089b6e04872a
but not added to the nix build environment
fix(cuda): add F16-K + TURBO-V dispatch cases in fattn.cu
The flash attention vector dispatcher was missing instance files, extern
declarations, and dispatch cases for F16-K + TURBO-V combinations. Any
of `-ctk f16 -ctv turbo{2,3,4}` aborted at fattn.cu:339 on sm_89 and
sm_121 because no dispatch case matched.
The kernel already treats TURBO types as unquantized alongside F16 and
BF16 (fattn-vec.cuh:79-80), so this is a dispatch-plumbing gap, not a
kernel limitation. Pure additive change.
CMakeLists.txt is updated so builds without GGML_CUDA_FA_ALL_QUANTS (the
default) also link the new template instances.
Validated on:
- RTX 4090 (sm_89) with Qwen3-30B-A3B Q4_K_M, FA_ALL_QUANTS=ON
- DGX Spark GB10 (sm_121) with Q4_K_M and UD-Q4_K_XL, both FA_ALL_QUANTS=ON and =OFF
Key results:
- Pre-fix crash reproduced at fattn.cu:339 (exit 134 SIGABRT, sm_89)
- Post-fix: all three new combos (f16/turbo{2,3,4}) run in llama-bench on sm_89
- sm_89 tg128: 215-218 t/s for new combos (vs 242 t/s for f16/f16 baseline)
- sm_121 tg128: 83.78-85.11 t/s for f16/turbo3 across model and build-config combinations
- Single-run PPL on sm_89 wikitext-2: 7.5281 vs 7.4950 f16/f16 baseline (delta 0.44%, within within-run error)
- KV context memory at 4K ctx on sm_89: 229 MiB vs 384 MiB f16/f16 baseline
Fixes #83
fix(cuda): allow f16/bf16 + q8_0 mixed KV without GGML_CUDA_FA_ALL_QUANTS (#82)
The FA dispatcher rejected any K != V type combo unless all types were
in the turbo+q8_0 set. This meant common configs like `-ctk f16 -ctv q8_0`
fell back to CPU unless built with -DGGML_CUDA_FA_ALL_QUANTS=ON.
The vec template instances for f16/bf16 + q8_0 are already compiled
(fattn-vec-instance-{f16,bf16}-q8_0.cu and their reverse), so the
dispatcher was gating kernels that do exist.
Extend the predicate to include f16 and bf16 alongside turbo + q8_0.
Reported by @dentity007 on sm_89 (RTX 4090) and sm_121 (GB10), where
`-ctk f16 -ctv q8_0` showed 340x slowdown indicative of CPU fallback.
Co-Authored-By: [email protected]
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
fix: add TURBO2_0 to flash_attn auto-enable check
turbo2 V cache failed with "failed to create context" because the
auto-enable predicate only listed turbo3/turbo4. Without auto-enable,
the subsequent quantized-V-requires-FA check hard-fails.
Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
ci: fix turbo build and test failures
Four changes that together make the TheTom/llama-cpp-turboquant CI green
on top of feature/turboquant-kv-cache:
1. ggml-cpu/ops.cpp:ggml_compute_forward_clamp
The abort branch's -Werror=switch was missing the three TurboQuant KV
cache types (TURBO2_0/TURBO3_0/TURBO4_0), which broke every GCC build
after the turbo types were added. Added them next to the TQ* cases so
the fall-through to GGML_ABORT stays consistent.
2. ggml-rpc.h:RPC_PROTO_PATCH_VERSION / static_assert
GGML_OP_TURBO_WHT bumped GGML_OP_COUNT from 96 to 97 but the RPC
static_assert was not updated. Bumped the patch version 1->2 and the
assert to 97 so ubuntu-latest-rpc / windows-latest-hip / etc. build.
3. tests/test-quantize-fns.cpp
a) Heap-buffer-overflow (ASan trace): the scratch buffers
std::vector<uint8_t> tmp_q{,1,2}(2*test_size) are too small when
vec_dot_type == GGML_TYPE_F32 (which is the case for turbo quants),
because from_float then writes test_size*sizeof(float) bytes into
them. Size buffers to std::max(2*test_size, test_size*sizeof(float))
so every quant's from_float fits.
b) Skip TURBO2_0 / TURBO3_0 / TURBO4_0 in the harness. Their
dequantize_row_turbo*_0 intentionally stays in the WHT-rotated
domain; the inverse WHT is applied separately via GGML_OP_TURBO_WHT
in the attention graph, so a round-trip against the original float
buffer is not meaningful and the existing threshold table does not
apply.
c) Add TQ3_1S to the 3-bit threshold buckets (absolute error uses
MAX_QUANTIZATION_TOTAL_ERROR_3BITS, dot product uses
MAX_DOT_PRODUCT_ERROR_LOWBIT) so the 3-bit weight quant is held to
3-bit error budgets instead of the default 4-bit ones.
4. ggml-cuda/turbo-quant.cuh
Wrap all cudaMemcpyToSymbol / cudaMemcpyFromSymbol / cudaDeviceSynchronize
calls in CUDA_CHECK(...) so the HIP build (hipError_t is [[nodiscard]])
no longer trips -Werror on unused-result.
Verified locally on Arch Linux (CPU build):
ctest -L main -E "test-llama-archs|test-tokenizers-ggml-vocabs"
=> 100% tests passed, 0 tests failed out of 41
(the excluded tokenizer test needs the model-fetch fixture)
test-quantize-fns runs clean under AddressSanitizer as well.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Fix GGML_OP_COUNT assertion for RPC
When compiling with the `-DGGML_RPC=ON` option, a static assert fails for `GGML_OP_COUNT == 96`. It should be 97.
Fix memory explosion on Apple Silicon
Add GitHub Sponsors funding link
vulkan: add turbo3 backend tests
- test_turbo_wht: forward/inverse WHT, 18 configs. NMSE tolerance 1e-5
(f32 SIMD reduction order varies across GPU backends).
- test_turbo_wht_roundtrip: forward then inverse recovers original, 9
configs. NMSE tolerance 1e-5.
- test_set_rows_turbo3: full quantization round-trip at small and large
tensor sizes. Large tensors exercise the 2D dispatch grid. 21 configs.
- Existing: test_turbo_wht (18), FA with turbo3 KV (528).
- Total: 576 tests.
vulkan: fix and complete turbo3 KV cache support
feat: add CDNA4 (gfx950/MI355X) support + test results
Add AMD Instinct MI355X (gfx950) architecture support:
Code changes:
- vendors/hip.h: Add CDNA4 define for __gfx950__, include in CDNA family
- common.cuh: Add GGML_CUDA_CC_CDNA4 constant and IS_CDNA4 macro
- mma.cuh: Route CDNA4 to compatible MFMA instructions
* bf16: mfma_f32_16x16x16bf16_1k (same as CDNA3)
* int8: mfma_i32_16x16x32_i8 (same as CDNA3)
* f32: mfma_f32_16x16x4f32 (CDNA2 path, NOT xf32 which doesn't exist on gfx950)
- mmq.cuh: Include CDNA4 in stream-k dispatch
- common.cuh: Exclude CDNA4 from CDNA3-specific e4m3_fnuz FP8 path (gfx950 uses standard e4m3fn)
MI355X test results (Qwen2.5-1.5B Q4_K_M, single GPU):
- turbo3: 39,140 tok/s prefill (98% of f16), 162 tok/s decode (64%)
- turbo4: 39,232 tok/s prefill (98% of f16), 214 tok/s decode (84%)
- WHT roundtrip: PASS (max error 2.98e-07)
Note: non-FA MMQ path crashes on gfx950 (xf32 MFMA unsupported).
TurboQuant types force FA and work correctly.
Tested-by: Andy Luo <[email protected]>
docs: add AMD Instinct MI300X (gfx942) ROCm test results
TurboQuant KV cache compression (turbo2/turbo3/turbo4) builds and runs
correctly on AMD Instinct MI300X with ROCm 7.0.2. Zero code changes
required тАФ existing CUDA kernels compile via HIP translation.
Test results (Qwen2.5-1.5B Q4_K_M, single MI300X):
- WHT roundtrip: PASS (max error 2.98e-07)
- turbo3 prefill: +3% vs f16 (25,200 vs 24,453 tok/s)
- turbo3 decode: 88% of f16 (160 vs 181 tok/s)
- turbo4 prefill: +4% vs f16 (25,427 vs 24,453 tok/s)
- turbo4 decode: 89% of f16 (161 vs 181 tok/s)
MI355X (gfx950) compiles but needs gfx950 added to llama.cpp's
MMQ kernel dispatch (upstream issue, not TurboQuant-specific).
Tested-by: Andy Luo <[email protected]>
metal: add TurboFlash attention kernel for turbo3 KV cache decode
Two-pass block-parallel attention kernel optimized for turbo3 V cache
decode on Apple Silicon Metal. Supports both q8_0-K (asymmetric) and
turbo3-K (symmetric) configurations via compile-time function constant.
Architecture:
- Pass 1: 32-thread SIMD group per (query-head, block) pair
- Each lane handles DK/32 interleaved dimensions
- Q loaded to per-lane registers, K dequant via q8_0 or turbo3 path
- K scoring via simd_sum dot product
- turbo3 V unpack with register codebook (8 centroids)
- Online softmax (m/l/o state) entirely in registers
- Zero shared memory in pass 1
- Pass 2: merge partial results across blocks
- Online softmax correction with global max/sum
- Inverse WHT via simd_shuffle_xor (stages 0-4) + shared memory (stages 5-6)
- Eliminates 5 of 7 threadgroup barriers vs naive butterfly
Auto-detection: activates for single-token decode (ne01==1) when V is
turbo3 and K is q8_0 or turbo3. Controllable via TURBO_FLASH env var
(0=off, 1=force). Block size B=64 (proven optimal on Apple Silicon).
Benchmarks (Qwen2.5-7B Q8_0, asymmetric q8_0-K/turbo3-V):
- M5 Max 128GB: +1.5% decode at 8K (56.82 vs 56.00 tok/s), 93% of q8_0
- M2 Pro 32GB: +0.6% decode at 8K (20.55 vs 20.42 tok/s)
- Advantage scales with context (+7.3% at 32K)
Inspired by Eric Kryski's TurboFlash architecture (mlx-swift-lm).
Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
feat: Vulkan compute shader support for turbo3 KV cache
Full turbo3 quantize/dequant pipeline for Vulkan backend:
- types.glsl: block_turbo3_0 struct (norm + qs[8] + signs[4])
- dequant_turbo3_0.comp: standalone dequant shader (3-bit index
reconstruction from 2-bit qs + 1-bit signs, centroid lookup)
- dequant_funcs.glsl: inline dequant for get_rows/mul_mat paths
- dequant_funcs_cm2.glsl: cooperative matrix 2 FA path support
- copy_to_quant.comp: quantize function with norm correction
- vulkan-shaders-gen.cpp: turbo3_0 type registration
- ggml-vulkan.cpp: pipeline creation and supports_op dispatch
Tested on AMD 7900 XTX (RADV): 243 pp / 25.8 tg t/s with turbo3 KV.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
fix: AMD/RDNA4 arch dispatch тАФ scalar half path for TQ4_1S on AMD GPUs
The dp4a int8 kernel is optimized for NVIDIA Turing+ dp4a throughput
(240 t/s on 5090). On RDNA4, sudot4 has different throughput
characteristics and the q8_1 activation quantization adds overhead,
causing a regression vs the V12 float kernel (101 vs 135 t/s on
RX 9070 XT).
Fix: check GGML_CUDA_CC_IS_AMD(cc) at dispatch time and route AMD
GPUs to a scalar half-precision kernel (same pattern as TQ3_1S).
NVIDIA continues using the dp4a path.
Changes:
- Add mul_mat_tq4_1s_scalar_multi kernel: pre-rotated half activations,
shmem centroid LUT, scalar dot product (no dp4a/byte_perm)
- Dispatch: use_dp4a = !AMD && TQ4_1S. AMD falls through to scalar path.
- LAUNCH_SCALAR macro unifies TQ4_1S/TQ3_1S scalar dispatch
Expected RDNA4 result: restore V12-level decode (135 t/s, 130% of Q8_0)
instead of dp4a regression (101 t/s, 60% of Q8_0).
Co-Authored-By: Tom Turney <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
fix: replace __dp4a with ggml_cuda_dp4a for HIP/ROCm compatibility
feat: multi-token TQ4_1S dp4a kernel + multi-GPU fix + static build fix
- Multi-token dp4a kernel for ne[1]тЙд8 (speculative decoding, small batches)
loads weight data once per block, reuses across all ncols_dst tokens
- Runtime TQ4_1SтЖТfp16 dequant + cuBLAS for ne[1]>8 prefill
- Fix multi-GPU crash: replace static global CUDA buffers with per-device
pool allocations from ctx.pool(id), matching mmvq.cu pattern
- Fix static build: TURBO_IQ_API wrapped in #ifdef GGML_BACKEND_SHARED
perf: warp-cooperative TQ4_1S dequant (16├Ч less compute per block)
Replace per-element generic dequant template (which repeats the full
32-element WHT butterfly 16 times per block) with a warp-cooperative
version using __shfl_xor_sync. One WHT per block instead of 16.
Note: this improves the dequant kernel itself but doesn't fix the
prefill gap (5.9K vs 13.3K). The bottleneck is cuBLAS fp32 GEMM vs
the q8_0 conversion path's native int8 tensor core GEMM. The dequant
was never the slow part тАФ the GEMM dispatch is fundamentally different.
For prefill-heavy workloads, load-time q8_0 conversion remains the
recommended path (default ON). GGML_TQ_NATIVE=1 for decode-heavy
interactive chat where the +29% decode speed matters more.
perf: TQ4_1S native kernel 3.5├Ч faster тАФ 240 t/s (was 68), smaller VRAM than q8_0
Autoresearch-discovered optimizations for TQ4_1S weight mul_mat_vec kernel.
Native TQ4_1S at 5.0 bpv now runs 36% FASTER than the q8_0 load-time
conversion (240 vs 176 t/s) while using 1.7├Ч LESS VRAM (4.5 vs 7.5 GiB).
Key optimizations (found via 86 automated experiments):
1. fp16 activation buffer тАФ halves activation bandwidth (the bottleneck)
2. Shared-memory centroid LUT тАФ eliminates constant memory serialization
on divergent lane access (+89% single change)
3. Half2 arithmetic + strided block processing тАФ 2├Ч arithmetic density
4. Vectorized 128-bit loads тАФ uint32├Ч4 weights, int4 activations (+45%)
5. Register __byte_perm centroid decode тАФ zero-memory centroid lookup
6. NWARPS 8тЖТ4
Also:
- Load-time q8_0 conversion now opt-in (GGML_TQ_CONVERT_Q8=1) instead
of default. Native kernel is strictly better on both speed and VRAM.
- Autoresearch harness gains coherence testing (server API + factual Q&A)
to catch silent corruption that PPL alone misses.
Benchmarks (RTX 5090, Qwen2.5-7B-Instruct TQ4_1S):
Upstream V12 runtime: 67 t/s (4.5 GiB VRAM)
q8_0 conversion: 176 t/s (7.5 GiB VRAM)
Native optimized: 240 t/s (4.5 GiB VRAM) тЖР this PR
Quality (vs f16 baseline):
PPL: 7.54 (f16: 7.18, q8_0 conv: 7.55)
Mean KLD: 0.056 (q8_0 conv: 0.057, q4_0: 0.078)
NIAH: 5/5
Coherence: 4/4 (Paris, 4, print, Shakespeare)
fix: cap map0 kernel shmem for 256-expert MoE models
Graph reservation passes worst-case ne20=ne02 (256x256x2=128KB),
exceeding the 32KB threadgroup memory limit on Apple Silicon.
At runtime ne20 is the actual n_expert_used (e.g. 8), so shmem
= 256*8*2 = 4KB, well within limits.
Cap the reservation shmem to 32KB to prevent the assert from firing.
Tested on Qwen3.5-35B-A3B (256 experts) with llama-server + flash
attention тАФ previously crashed during warmup, now runs at 22 t/s.
Fixes #58
Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
feat: add MoE expert count kernel instantiations + TQ4_1S backend tests
Metal MoE support:
- Add kernel_mul_mm_id_map0 instantiations for ne20 = 32, 60, 64, 128, 160, 256
- Covers Yuan, Qwen1.5-MoE, OLMoE, Qwen2/3-MoE, Mistral Small 4,
Llama 4 Maverick, DeepSeek-V2/V3, Qwen3.5-35B/122B
- Note: ne02=256 (Qwen3.5-35B-A3B) hits shmem assert in llama-server
with flash attention тАФ needs chunked map0 dispatch (follow-up)
Backend tests:
- Add TQ3_1S and TQ4_1S to all_types array in test-backend-ops
- Enables GET_ROWS and MUL_MAT coverage for WHT-rotated weight types
Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
fix: GCC double extern in ops.cpp turbo3_cpu_wht_group_size
extern "C" GGML_API creates double extern on paths where GGML_API
expands to 'extern'. Wrap in extern "C" {} block instead.
Reported by Madreag on RTX 5090 WSL2.
Co-Authored-By: Tom Turney <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Update GGMLQuantizationType and LlamaFileType enums to include TQ3_1S and TQ4_1S quantization types with corresponding sizes in GGML_QUANT_SIZES.
Enhance Metal operations for TQ weights and concurrency handling for Gemma 4
- Introduced a new function to check if TQ source tensors mutate during operations.
- Updated matrix multiplication logic to handle TQ weights more effectively, ensuring correct concurrency behavior.
- Adjusted Metal kernel definitions to support TQ weights with improved dispatch parameters.
- Enhanced comments for clarity on concurrency issues related to TQ weights.
fix: remove redundant extern from GGML_API macro (GCC 13.3 hard error)
GCC 13.3 on Ubuntu 24.04 hard errors on the redundant `extern` in the
GGML_API macro when used inside `extern "C" {}` blocks. MSVC and Clang
accept it silently.
Reported independently by joemc1470 (RX 6600 HIP) and
christopheraleman1015 (WSL2 Ubuntu).
Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
feat: load-time TQ4_1S -> q8_0 conversion for CUDA dp4a speed
Cherry-picked from signalnine (daf0484, dca057a). TQ4_1S tensors are
converted to q8_0 at model load via fused CUDA kernel. Transparent to
downstream code. 40% smaller on disk, TQ4_1S quality, q8_0 decode speed.
signalnine's results (RTX 5090): 105 t/s converted vs 103 t/s native q8_0.
PPL 7.608 vs 7.599 (0.009 requantization rounding).
Also includes group_size=32 for ggml_turbo_wht (needed for TQ weight types).
Metal regression: clean (tested Q8_0, Config I, turbo3 KV on M5 Max).
Co-Authored-By: Gabe Ortiz <[email protected]>
Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Fix turbo4 C reference WHT dequant mismatch (#43)
Fix/turbo4 wht dequant
fix: CPU vec_dot heap allocation for turbo/TQ types (n > 4096 models)
Stack-allocated float tmp[4096] buffers in CPU vec_dot functions
crashed on models with intermediate_size > 4096 (e.g. TinyLlama 5632,
Qwen 27B 18944). Replaced with heap allocation.
Affects CPU-only inference fallback path. GPU users unaffected.
Reported by @oemc1470 on RX 6600 (gfx1032) where broken HIP forced
CPU fallback.
Tested: Qwen3.5-27B Config I, CPU-only (-ngl 0), intermediate_size=18944.
No crash, no assert.
Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
fix: add dk512 Metal FA kernel instances for turbo types (Gemma 4 support)
Gemma 4 uses global_head_dim=512 for full attention layers. The turbo
FA kernels were only instantiated up to dk256 for symmetric and
cross-turbo combos. Missing dk512_dv512 caused pipeline compilation
failure on Gemma 4 (and any future model with head_dim=512 + turbo KV).
Added 18 template instantiations (9 non-vec + 9 vec) for all turbo
type combinations at dk512_dv512. Asymmetric q8_0/turbo combos already
had dk512 and were not affected.
Tested: Gemma 4 31B on M5 Max, symmetric turbo3/turbo3 and asymmetric
q8_0/turbo4 both produce correct bench results at dk512.
Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
fix: AMD HIP/ROCm build support for TQ4_1S weight compression
- Add missing CUDA->HIP stream capture API mappings (vendors/hip.h)
- Add TURBO_IQ_API macro for cross-DLL symbol visibility (Windows + Linux)
- Add fileno/isatty POSIX compat macros for clang on Windows
No kernel changes needed. signalnine's fused mmvq-tq kernel uses
__shfl_xor_sync which maps directly to HIP warp shuffle on RDNA 4.
Tested: RX 9070 XT (gfx1201, RDNA 4), Qwen2.5-1.5B Config I.
Result: 30% faster decode than Q8_0 (135 vs 104 t/s), +1.8% PPL.
Metal regression: clean, no changes to non-Windows/non-HIP paths.
Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
fix: Windows MSVC build compatibility for TQ weight types
- Add _USE_MATH_DEFINES + M_PI fallback for MSVC (doesn't define M_PI)
- Add GGML_API to turbo3_cpu_wht_group_size for DLL export
- Move extern declaration to file scope with extern "C" GGML_API linkage
to fix C vs C++ name mangling across DLL boundary
All changes are no-ops on Linux/Mac. Fixes MSVC build errors:
C2065: 'M_PI': undeclared identifier
LNK2001: unresolved external symbol turbo3_cpu_wht_group_size
Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
perf: V12 single-phase fused TQ mmvq тАФ shmem activation, no global scratch
Replace two-phase approach (separate pre-rotation kernel + global memory
round-trip) with single-phase kernel where all 8 warps cooperatively
WHT-rotate activation into shared memory, then each warp processes one
row reading from shmem (broadcast reads from L1).
Key changes:
- No global scratch buffer (eliminates CUDA graph incompatibility)
- No separate kernel launch for pre-rotation
- Activation stays in shmem (~14-32 KB) instead of global memory
- Single __syncthreads between rotation and dot product (NOT in inner loop)
- V8 two-phase fallback retained for ncols > 12288 (48 KB shmem limit)
This avoids the NR0 regression that killed V3/V6/V11 тАФ those had sync
inside the dot product loop. V12's sync is between the two phases.
Expected: 30-50% decode improvement on Ampere+ (shmem broadcast eliminates
2x activation bandwidth). Pascal improvement smaller (still bandwidth bound).
NEEDS TESTING тАФ apply and benchmark on Ampere/Ada/Blackwell.
Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
fix: TQ4_1S on MoE models тАФ disable CUDA graphs for TQ MUL_MAT_ID
MoE models use MUL_MAT_ID which calls cudaStreamSynchronize in the
expert routing dispatch. This is incompatible with CUDA graph capture.
TQ4_1S types now disable CUDA graphs for MUL_MAT_ID nodes, matching
the existing behavior for non-quantized types.
Also: use persistent buffer for activation pre-rotation scratch,
with graph-capture-safe check.
Tested: Qwen3.5-35B TQ4_1S тАФ 47 t/s decode, PPL 6.42.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
perf: fused TQ4_1S/TQ3_1S mul_mat_vec тАФ 3.4x decode speedup
Two-phase approach: pre-rotate activation once via warp shuffle WHT,
then simple mmvq kernel reads pre-rotated values (centroid ├Ч scale
only, zero WHT per block).
Results (Qwen2.5-7B TQ4_1S, RTX 5090):
Decode: 20.3 тЖТ 69 t/s (3.4x speedup)
vs q8_0 (177 t/s): 39%
PPL: 8.82 (identical)
Comprehensive optimization log (13 versions tested):
cuBLAS baseline: 20 t/s
V1 per-warp WHT, 4 warps: 60 t/s (3.0x)
V3 shmem activation cache: 33 t/s (syncthreads kills it)
V5 multi-warp per row: 62 t/s
V6 LUT (shmem): 37 t/s (sync overhead)
V7 8 warps clean: 62 t/s
V8 pre-rotation (2-phase): 69 t/s тЖР BEST (3.4x)
V9 pre-rot + q8_1: 70 t/s (marginal)
V10 4-elem/thread: 57 t/s
V13 8-elem, 4-thread dot: 45 t/s
NR0=2/4/8: all regressed (register spill / cache thrash)
The gap to q4_0 (275 t/s) is from dp4a integer intrinsics and packed
int32 processing тАФ TQ4_1S requires float centroid lookup which can't
use dp4a. The gap to TheTom's Metal (85-99% of q8_0) is from
Apple Silicon's cooperative SIMD efficiency.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
fix: TQ4_1S CUDA тАФ mmvq exclusion for fused path + quantize tool registration
- ggml-cuda.cu: add TQ4_1S/TQ3_1S exclusion in ggml_cuda_should_fuse_
mul_mat_vec_q (was missing, causing ABORT in mmvq.cu)
- tools/quantize/quantize.cpp: register TQ3_1S/TQ4_1S in allowed types
Tested: Qwen2.5-7B TQ4_1S тАФ correct output, PPL 8.82 (+1.1% vs Q2_K),
6510 t/s prefill, 20 t/s decode (cuBLAS dequant-to-f16 path).
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
feat: CUDA port of TQ4_1S/TQ3_1S weight dequant (signalnine)
fix: disable upstream attn rotation by default (conflicts with TurboQuant)
Upstream commit 744c0c7 added graph-level Hadamard rotation for KV
cache quantization. This conflicts with our kernel-level WHT rotation
and causes graph hash table overflow on Phi-4 and potentially other
models.
Disable by default since TurboQuant already handles rotation at the
kernel level (more efficient, no extra graph nodes). Users can
re-enable with LLAMA_ATTN_ROT_DISABLE=0 if needed.
Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
fix: add post-unrotate memory barrier for in-layer mixing safety
Without this barrier, the GPU may start executing the next node's
matmul while the unrotate kernel is still modifying src1. This
causes data corruption when TQ and non-TQ tensors are mixed within
the same layer's attention block.
The barrier ensures the unrotate completes before any subsequent
operation reads from the same activation buffer.
Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
feat: TQ3_1S + TQ4_1S weight quantization with V2.1 fused Metal kernels
Add WHT-rotated weight quantization types:
- TQ3_1S (type 44): 3-bit, 8 Lloyd-Max centroids, 4.0 BPW
- TQ4_1S (type 45): 4-bit, 16 Lloyd-Max centroids, 5.0 BPW
Both use 32-element Randomized Hadamard Transform with dual half-block
scales (d0/d1). Quantization: forward RHT тЖТ scale search тЖТ iterative
refinement (6 iter) тЖТ pack indices.
Metal optimization (V2.1 fused kernel):
- Zero threadgroup memory for rotation (was 20KB+ on large models)
- Cooperative SIMD rotation via simd_shuffle_xor (registers only)
- Single simd_sum at end (not per-block)
- NR0=8 rows per threadgroup (amortizes rotation cost)
- Memory barriers between rotate/matmul/unrotate dispatches
- MoE MUL_MAT_ID support with rotated expert dispatch
Config I (recommended): attn+ffn_gate/up=TQ4_1S, ffn_down=Q4_K, boundary 2+2
Validated on Qwen2.5-1.5B, Qwen3.5-27B, Qwen3.5-35B-A3B MoE:
- 27-41% model size reduction
- +1.3-1.9% PPL (Qwen), 94-102% decode speed
- NIAH pass, KLD comparable to turbo3 KV
- Llama 3.1 70B shows +25% PPL тАФ needs investigation
Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Remove unused CENTROIDS_1BIT constant
Leftover from 1-bit VX experiment. Causes -Werror build failure in CI.
Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
fix: add missing TurboQuant FA template instances for HIP/ROCm build
The HIP build was missing 9 turbo cross-type flash attention vec
instantiations (turbo4 combos, turbo3/turbo2 cross-types) that were
present in the CUDA CMakeLists but not mirrored to the HIP CMakeLists.
Also guard the D>=576 tile kernel dispatch with #ifndef GGML_USE_HIP
since those instance files are already excluded from the HIP build
(they exceed HIP's 65536-byte local memory limit).
Tested on: ROCm 6.4.4, gfx1151 (AMD Ryzen AI Max+ 395 / Strix Halo)
Enable Sparse V on all Metal, auto-enable Boundary V for turbo2-V
Sparse V: now enabled by default on all Metal (was M5+ only).
Validated across 30+ testers with zero PPL impact. Opt-out: TURBO_SPARSE_V=0.
Boundary V: auto-enabled (mode 7) when -ctv turbo2 is set.
Protects first 2 + last 2 layers with q8_0-V, rest turbo2-V.
37-91% quality recovery across 4 tested models. Opt-out: TURBO_LAYER_ADAPTIVE=0.
Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
fix: CUDA warp-to-block mapping for block_size=128 (turbo3, turbo2)
The block_size=128 change (adac2c68d) broke CUDA quantization:
with QK=128, blocks_per_group=1, but the warp-cooperative packing
still used blk_base+warp_id, causing warps 1-3 to write OOB.
Fix: compute elem_in_block = j % QK_TURBO_N and use it for block
pointer (j / QK_TURBO_N) and byte offsets (elem_in_block / 4 for qs,
elem_in_block / 8 for signs). Works for both QK=32 and QK=128.
Validated on RTX 3090 (sm_86), llama3.1:8b Q4_K_M, q8_0/turbo3:
PPL = 7.587 (matches QK=32 baseline exactly).
Increase turbo3/turbo2 block size from 32 to 128
One norm per rotation group instead of four identical copies.
Eliminates 6 bytes of redundant storage per 128-element group.
turbo3: 3.50 -> 3.125 bits/value, 4.57x -> 5.12x compression
turbo2: 2.50 -> 2.125 bits/value, 6.4x -> 7.53x compression
Zero PPL regression validated across:
- Asymmetric q8_0-K + turbo{2,3}-V
- Symmetric turbo3/turbo3
- Boundary V (LA-V7)
- 3 architectures (dense, Qwen, MoE)
- 3 context lengths (512, 8K, 32K)
- 2 Apple Silicon platforms (M5 Max, M2 Pro)
- NIAH 3/3 pass
+3-7% decode on tested M2 Pro setup. No regression on M5.
Also adds derived NL_TURBO3/NL_TURBO2 macros replacing ~250
hardcoded FA template nl values. Block size is now a one-line
edit in ggml-common.h.
Credit to @AmesianX whose block_size=256 CUDA implementation
prompted this investigation.
Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
feat: HIP/ROCm porting for TheTom's turbo3/turbo2 warp-cooperative kernels
Port TheTom's warp-cooperative turbo3 SET_ROWS kernel and turbo2/turbo3
flash attention templates to HIP/ROCm (7900 XTX, gfx1100).
HIP vendor header fixes:
- Add cudaMemcpyToSymbol/FromSymbol -> hipMemcpyToSymbol/FromSymbol
- Add cudaMemcpyHostToDevice/DeviceToHost mappings
- Fix __shfl_sync, __shfl_xor_sync, __shfl_up_sync, __shfl_down_sync
to support both 3-arg and 4-arg calls (CUDA allows defaulting width
to warpSize, HIP macros required 4 args)
- Add __ballot_sync -> __ballot with uint32_t cast (HIP returns 64-bit
on wave64 platforms, turbo code expects 32-bit)
HIP CMakeLists:
- Add turbo3 and turbo2 flash attention template instances (same files
as CUDA CMakeLists, were missing from HIP build)
Tested: Mistral-Small-24B turbo3 PPL = 5.28 (+2.4% vs F16 baseline 5.16)
Previously showed catastrophic PPL ~15000 due to CPU quantize stub bug
(fixed by TheTom in 53f1298bd).
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
fix: KV state serialization uses padded tensor width (issue #28 follow-up)
state_write_data and state_read_data used hparams.n_embd_k_gqa (576)
for ggml_row_size, but turbo types zero-pad to 640. For turbo4
(QK=128), 576 % 128 != 0 тЖТ ggml_row_size assertion failure during
prompt cache save on llama-server slot reuse.
Fix: use k->ne[0] / v->ne[0] (actual padded tensor width) instead of
hparams values in all four serialization paths (K write, K read,
V write, V read).
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
feat: Boundary V (experimental) тАФ layer-aware V compression
Add V-only layer-adaptive modes to TURBO_LAYER_ADAPTIVE env var:
- Mode 5: first2+last2 V=turbo4, rest V=turbo2
- Mode 6: last8 V=turbo4, rest V=turbo2
- Mode 7 (recommended): first2+last2 V=q8_0, rest V=turbo2
Mode 7 ("Boundary V") protects quality-sensitive boundary layers with
q8_0-V while aggressively compressing middle layers with turbo2-V.
K cache is unchanged (stays at whatever -ctk specifies).
Validated on Metal (M5 Max) across 4 models, 2 context lengths:
- phi-4-Q8_0: 4.784 PPL (vs turbo2 4.835, turbo3 4.742)
- Qwen2.5-7B Q4_K_M: 6.835 (vs turbo2 6.911, turbo3 6.707)
- Qwen3.5-35B MoE: 5.148 (vs turbo2 5.257, turbo3 5.137)
- Qwen3.5-27B Dense: 6.423 (vs turbo2 6.534, turbo3 6.273)
- 8K context: stable, no collapse
- NIAH retrieval: pass
- Speed: no penalty
Effective V compression between turbo2 and turbo3, closer to turbo2
on deeper models. Quality consistently better than uniform turbo2-V.
Usage: TURBO_LAYER_ADAPTIVE=7 llama-server -m model.gguf -ctk q8_0 -ctv turbo2 -fa 1
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: [email protected]
fix: turbo4 on GLM-4.7 тАФ context init check accounts for zero-padding (issue #28)
The block-size divisibility check in llama-context.cpp rejected turbo4
on GLM-4.7 Flash (head_dim=576, QK_TURBO4=128, 576%128тЙа0) before the
KV cache zero-padding code could run.
Fix: for turbo types, compute the padded head_dim (ceil to 128) before
the divisibility check, matching what llama-kv-cache.cpp actually does.
Tested: GLM-4.7 Flash turbo4 loads and runs at 193 t/s.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
feat: CUDA port of turbo4 (4-bit, 3.8x compression) тАФ fixes issue #25 bug 1
Ports GGML_TYPE_TURBO4_0 to CUDA using the 4-bit PolarQuant format
(16 centroids, nibble-packed, no QJL). Previously turbo4 crashed on
CUDA with "cannot run the operation (SET_ROWS)".
Changes TURBO4_USE_4BIT default from Metal-only to all backends.
The 4-bit format (16 centroids) has better quality than the legacy
3-bit+QJL format and is simpler to implement (no residual projection).
Full CUDA stack:
- turbo-quant.cuh: 4-bit centroids, midpoints, nearest-centroid,
dequant element, per-block quantize
- set-rows.cu: k_set_rows_turbo4 kernel (128 threads, WHT rotation,
4-bit quantize, nibble pack via warp shuffle, corrected norm)
- dequantize.cuh + convert.cu: turbo4 to f16/f32
- fattn-common.cuh: vec_dot_KQ_turbo4 + dequantize_V_turbo4
- fattn-vec.cuh + fattn.cu: VEC dispatch + all cross-type instances
(turbo4├Чturbo4, turbo4├Чq8_0, turbo4├Чturbo3, turbo4├Чturbo2)
- ggml-cpu.c: CPU FA vec_dot for turbo4
PPL (Qwen3.5, wikitext-2): 6.23 (+0.8% vs q8_0) at 3.8├Ч compression
Speed: 217 t/s decode (comparable to turbo3 222 t/s)
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
fix: add turbo3/turbo2 cross-type VEC FA instances (issue #25 bug 2)
Mixed turbo3-K/turbo2-V and turbo2-K/turbo3-V had no CUDA FA kernel
instances, causing ~11x prefill regression (falling back to CPU FA).
Added VEC template instances for both cross-type pairs at D=64/128/256.
Updated the mixed-type guard in get_best_fattn_kernel to allow any
combination of turbo2, turbo3, and q8_0.
Tested: turbo3/turbo2 and turbo2/turbo3 both run at full CUDA VEC
speed (~170 t/s prefill, ~221 t/s decode on Qwen3.5 35B).
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
perf: CUDA MMA flash attention for D=640 (GLM-4.7 turbo3: 37тЖТ192 t/s)
GLM-4.7 Flash with turbo3 KV cache pads head_dim 576тЖТ640 for WHT.
D=640 had no CUDA FA kernel, falling back to CPU FA at 37 t/s.
Added MMA flash attention configs for D=640 (DKQ=640, DV=512),
using identical tile sizes as D=576 (nbatch_K2=288, nbatch_V2=256).
ncols1 capped at 2 for D=640: at ncols1тЙе4 the Q shared memory
(ncols ├Ч (DKQ/2+4) ├Ч 4 = 83KB at ncols=64) exceeds the per-block
limit. ncols1тЙд2 keeps total shared memory under 80KB.
Changes:
- fattn-mma-f16.cuh: D=640 config entries + extern declarations
(ncols2=16 only, ncols1тИИ{1,2,4})
- fattn.cu: case 640 in kernel selection + simplified MMA dispatch
(always ncols2=16, ncols1 capped at 2)
- fattn-tile.cuh/cu: D=640 tile configs + dispatch
- 3 MMA template instances + 1 tile instance
Tested:
GLM-4.7 Flash: 192 t/s (was 37), PPL 17.05 (vs 14.97 f16)
Qwen3.5: 222 t/s, PPL 6.31 (unchanged)
DeepSeek: 143 t/s, PPL 11.61 (unchanged)
16/16 coherence, NIAH 9-10/11 at 32K
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
feat: zero-pad non-128 heads for full 7-stage WHT (replaces q8_0 fallback)
Instead of falling back to q8_0 for models with non-128-aligned heads,
pad each head to the next multiple of 128 before WHT rotation. The
padded elements are zero and don't affect dot products since WHT
preserves inner products: <WHT(Q_pad), WHT(K_pad)> = <Q, K>.
This keeps turbo compression active on DeepSeek2, GLM-4.7 Flash, and
other non-128 head_dim models. Padding overhead is wasted bits on the
zero-padded quantized elements:
head_dim=192 тЖТ 256 (33% overhead, still 3.5x compression)
head_dim=576 тЖТ 640 (11% overhead, still 4.1x compression)
Changes:
- llama-kv-cache.cpp: allocate K/V cache at padded dimension, pad
k_cur/v_cur per-head via ggml_pad before set_rows, return padded
views from get_k/get_v
- llama-graph.cpp: pad Q per-head before turbo_wht, extract original
V head_dim from attention output after inverse WHT. All three
build_attn variants (KV, K-only/MLA, ISWA) updated.
PPL (wikitext-2, 512 context, 8 chunks):
DeepSeek (192тЖТ256): 11.61 vs 9.90 baseline (+17%)
Previously: 344,304 with 64-group WHT (catastrophic)
GLM-4.7 (576тЖТ640): 9.11 vs 14.97 baseline
Qwen3.5 (128): 6.31 unchanged
Tested: 16/16 coherence, NIAH 9-10/11 at 32K, CPU-only works.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
feat: asymmetric K/V support + q8_0 ├Ч turbo FA kernel instantiations
Add full asymmetric K/V quantization support for Metal flash attention:
- Pipeline naming uses k{type}_v{type} format for all FA kernels (335 total),
eliminating underscore ambiguity in type names
- 90 turbo ├Ч turbo asymmetric instantiations (turbo2/3/4 all combinations)
- 150 q8_0 ├Ч turbo asymmetric instantiations (both directions, all head dims)
- Gatekeeper and assertion updated to allow turbo ├Ч turbo and q8_0 ├Ч turbo pairs
- Zero regression on existing symmetric paths (validated across 4 models, 2 machines)
The q8_0 ├Ч turbo kernels fix a silent dispatch failure where mixed q8_0-K + turbo-V
configs would NaN (turbo4-V) or fall to undefined paths (turbo3-V). This enables
the asymmetric quality rescue: q8_0-K + turbo-V recovers near-baseline PPL on
low-bit models where symmetric turbo-K degrades.
Validated on Metal (M2 Pro + M5 Max):
- phi-4-Q8_0: symmetric turbo3 +4.2%, turbo4 +1.7% (no regression)
- Qwen2.5-7B Q4_K_M: q8_0-K + turbo4-V +1.0%, q8_0-K + turbo3-V +2.0% (rescued)
- Qwen3.5-35B MoE, 27B Dense, Mistral-24B: all healthy (no regression)
- Cross-hardware M2/M5 parity confirmed on all tested configs
Closes #27
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: [email protected]
feat: asymmetric K/V quant support for Metal flash attention
- Add mixed-type kernel instantiations for all turbo pairs (turbo2/3/4)
- Both vec and non-vec FA paths, all supported head dims
- Pipeline naming uses k/v prefix format (kturbo3_vturbo4) to avoid
underscore ambiguity in type names
- Relax symmetric K/V assertion to allow turbo mixed pairs
- Update pipeline name construction in both FA pipeline getters
- 90 new kernel instantiations (54 non-vec + 36 vec)
- All 335 FA kernels use unified k{type}_v{type} naming scheme
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: [email protected]
feat: Metal support for turbo2 (2-bit KV cache, 6.4x compression)
4 centroids, no signs byte. Simpler than turbo3.
PPL 6.507 (+6.48% vs q8_0) on Qwen3.5-35B-A3B.
Metal shader: quantize, dequant (vec + non-vec), SET_ROWS kernel,
FA template instantiations (non-vec nl=2, vec nl=8).
Runtime: supports_op, vec/non-vec gating, llama-bench parser.
Codex-reviewed: no bugs found, only known limitation is
non-128 head_dim tail handling (same as turbo3, covered by q8_0 fallback).
Closes #19
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: [email protected]
fix: require head_dim % 128 for turbo KV тАФ fall back to q8_0 otherwise
PPL benchmarks revealed that 64-group WHT (for non-128-aligned heads)
causes catastrophic quality loss on some models:
- DeepSeek (head_dim=192): PPL 344,304 vs 9.9 baseline
- GLM-4.7 (head_dim=576): PPL 22.79 vs 14.97 baseline (+52%)
The 64-group WHT passed NIAH/coherence but the weaker decorrelation
(6 stages, 3 groups per 192-dim head) doesn't preserve statistical
quality. Straight PolarQuant (no WHT) is even worse.
All turbo types now require head_dim divisible by 128. Models with
non-128-aligned heads (DeepSeek2, GLM-4.7 Flash) auto-fall back to
q8_0 with a warning. The 64-group WHT code remains for future
investigation but is not used.
PPL summary (Qwen3.5, head_dim=128, wikitext-2):
f16: 6.20 | q8_0: 6.18 | turbo3: 6.31 (+2.2%) | turbo2: 6.69 (+8.3%)
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
perf: sparse V dequant тАФ skip negligible attention weights in VEC kernel
In the VEC flash-attention kernel, skip V dequantization for KV
positions where ALL attention weights are below 1e-6. At long context
most positions contribute noise, not signal тАФ skipping their V dequant
saves compute with zero quality impact.
Both half2 and f32 paths are covered. The threshold (1e-6) matches
the existing SOFTMAX_FTZ_THRESHOLD behavior where exp() values below
this are flushed to zero.
Benefit scales with context length тАФ at short context nearly every
position contributes so no skip occurs. At 512K+ most positions are
skipped during generation.
Tested: 10/11 NIAH at 512K (matches pre-sparse-V), 3/3 coherence.
Generation at 512K: 25 t/s, prefill: 2535 t/s.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
feat: InnerQ per-channel equalization + turbo2 64-group fallback
InnerQ equalizes K channel variances before WHT rotation to reduce
quantization error on models with anisotropic K distributions.
Enabled via TURBO_INNERQ=N env var (N = calibration token count).
Pipeline: calibrate per-channel K┬▓ stats тЖТ compute scales тЖТ
apply scale to K before WHT (SET_ROWS) тЖТ apply 1/scale to Q and
V output via ggml_turbo_wht op (scale passed as src[1]).
Math: <Q/s, s*K> = <Q, K> preserves dot products.
Key design:
- d_innerq_active starts at 0 (CUDA zero-init) тАФ kernel never
multiplies by uninitialized scales
- Auto-disables for 64-group models (group_size < 128) where
channel mapping is not 1:1 across WHT groups
- Auto-disables when max channel ratio < 1.2 (already balanced)
- Cross-TU coordination via turbo-innerq.cu/cuh for scale_inv
tensor updates between SET_ROWS and graph-side WHT
- Scale_inv tensor stored in KV cache, initialized to identity
Also: turbo2 (2-bit) now requires head_dim divisible by 128.
At 64-group WHT, the 4-centroid codebook doesn't have enough
resolution тАФ DeepSeek (head_dim=192) produced garbage. turbo2
auto-falls back to q8_0 for non-128-aligned heads with a warning.
Tested: 18/18 coherence (4 models ├Ч 4+ KV combos), InnerQ active
on Qwen (222 t/s) and Mixtral (146 t/s), auto-disabled on GLM/DeepSeek.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
fix: MLA inverse WHT group_size derived from K (not V) тАФ fixes GLM-4.7
The mixed KV types commit changed the inverse WHT guard from checking
k->type to v->type. For MLA, V is a view of K's first 512 elements
(v->ne[0]=512, 512%128=0 тЖТ group=128). But K was quantized with
64-group WHT (k->ne[0]=576, 576%128тЙа0 тЖТ group=64). The mismatch
produced garbage output on GLM-4.7 Flash.
Fix: derive group_size from K when K is turbo (since K determines the
rotation used during quantization), from V only when K is not turbo.
Tested: 16/16 coherence (4 models ├Ч 4 KV combos), including GLM-4.7.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
feat: GGML_TYPE_TURBO2_0 тАФ 2-bit TurboQuant KV cache (6.4x compression)
Adds turbo2: 2-bit PolarQuant with WHT rotation, 2.5 bits/value,
6.4x compression vs f16. Same architecture as turbo3 but with a
4-centroid Lloyd-Max codebook instead of 8.
Block format: block_turbo2_0 = 10 bytes per 32 values
- norm (fp16, 2B): corrected L2 norm (grp_norm / recon_norm)
- qs (8B): 2-bit centroid indices, 4 per byte
Usage: -ctk turbo2 -ctv turbo2
Full stack:
- ggml.h/ggml-common.h: GGML_TYPE_TURBO2_0 enum + block_turbo2_0 struct
- ggml-turbo-quant.c: CPU quantize (with WHT) + dequantize
- turbo-quant.cuh: CUDA centroids, midpoints, nearest-centroid, dequant
- set-rows.cu: k_set_rows_turbo2 kernel (GROUP_SIZE-templated, parallel WHT)
- dequantize.cuh + convert.cu: turbo2 to f16/f32 conversion
- fattn-common.cuh: vec_dot_KQ_turbo2 + dequantize_V_turbo2
- fattn-vec.cuh + fattn.cu: VEC kernel dispatch + template instances
- Mixed types: turbo2/q8_0 cross-type FA instances
- common/arg.cpp: CLI --cache-type-k turbo2
- llama-graph.cpp + llama-kv-cache.cpp: graph + cache integration
NIAH (Qwen3.5 35B, RTX 5090, 4K-512K):
4K-16K: 11/11 | 32K: 9/11 | 64K: 10/11 | 128K-512K: 11/11
Coherence: 31/31 across 4 models x all KV combos (GPU + CPU)
Speed: 228 t/s decode on Qwen3.5 (comparable to turbo3 223 t/s)
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
fix: implement CPU turbo3 quantize (was a stub that zeroed qs/signs)
quantize_row_turbo3_0_ref was a stub that only stored the L2 norm and
zeroed out qs/signs тАФ any CPU-only path (-ngl 0) silently produced
garbage output.
Now implements full PolarQuant: L2 norm тЖТ normalize тЖТ forward WHT
rotation (signs1 тЖТ butterfly тЖТ signs2) тЖТ 3-bit centroid quantize тЖТ
pack qs/signs тЖТ corrected norm (grp_norm / recon_norm).
WHT group size (128 or 64) is communicated from the CPU SET_ROWS
handler via a global variable, read from the op_params that
llama-kv-cache.cpp sets based on head_dim. This handles models with
different K and V head dims (e.g. DeepSeek2 K=192тЖТ64, V=128тЖТ128).
Tested CPU-only (-ngl 0):
- Mixtral 8x7B (head_dim=128): correct output at 4.5 t/s
- DeepSeek-Coder-V2 (head_dim=192): correct output at 18.2 t/s
- GPU paths unchanged (Qwen 203 t/s, DeepSeek 164 t/s, GLM 202 t/s)
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
feat: mixed turbo3/q8_0 KV cache types (-ctk turbo3 -ctv q8_0 and vice versa)
Users can now mix turbo3 and q8_0 independently for K and V caches:
-ctk turbo3 -ctv q8_0 # compress K more, keep V at higher quality
-ctk q8_0 -ctv turbo3 # opposite tradeoff
Changes:
- New VEC FA template instances for turbo3/q8_0 cross-type pairs
(fattn-vec-instance-turbo3_0-q8_0.cu, fattn-vec-instance-q8_0-turbo3_0.cu)
- fattn-vec.cuh: extern declarations for mixed instances
- fattn.cu: dispatch + allow turbo3/q8_0 mix through the K!=V type guard
- llama-graph.cpp: inverse WHT guard now checks V type (not K type) тАФ
when K=turbo3 but V=q8_0, V values are NOT WHT-rotated so inverse
WHT must not fire. For MLA, V is a view of K so v->type correctly
reflects K's turbo type.
Tested:
- 16/16 coherence tests pass (4 models ├Ч 4 KV combos)
- NIAH at 4K+32K: all combos within baseline variance (10-11/11)
q8_0/q8_0: 10/11, q8_0/turbo3: 10/11, turbo3/turbo3: 10/11,
turbo3/q8_0: 9/11 (1 extra miss, normal variance)
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
feat: 64-element WHT groups + MLA Q rotation fix (issue #13)
Models with head_dim divisible by 64 but not 128 (e.g. DeepSeek2 MLA
head_dim=192, GLM-4.7 Flash head_dim=576) now use 64-element WHT
groups instead of crashing or falling back to q8_0.
Key changes:
**64-element WHT groups:**
- turbo-quant.cuh: 64-element sign arrays + FWHT-64 + rotate_64
- set-rows.cu: templated on GROUP_SIZE {128,64}, reads group_size
from SET_ROWS op_params (set by llama-kv-cache based on head_dim)
- turbo-wht.cu: templated on group_size, head-dim-aware dispatch
- ggml.h/ggml.c: ggml_turbo_wht() now takes explicit group_size
parameter (0=auto) to handle MLA where output dim differs from
K head dim
- ops.cpp: CPU WHT parameterized on group_size
**MLA fix тАФ missing Q rotation in K-only build_attn:**
- build_attn(inp_attn_k, ...) had no turbo Q pre-rotation, while
SET_ROWS was applying WHT to K. Result: <unrotated_Q, rotated_K>
= garbage. Now all three build_attn variants apply Q rotation.
- Inverse WHT moved inside build_attn_mha (before v_mla projection)
and also added to the non-FA attention path.
**Guards + fallback:**
- supports_op, fattn.cu, llama-graph.cpp: relaxed from %128 to %64
- llama-kv-cache.cpp: falls back to q8_0 only when head_dim%64!=0
- CPU type_traits_cpu turbo3 entry for CPU FA vec_dot
Tested: GLM-4.7 Flash (head_dim=576) 208 t/s, DeepSeek-V2 (192) 143 t/s,
Qwen3.5 (128) 223 t/s тАФ all producing correct output with turbo3.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
fix: graceful fallback for turbo3 on non-128-aligned head dims (issue #13)
Models with n_embd_head_k not divisible by 128 (e.g. GLM-4.7 Flash,
DeepSeek2 MLA with head_dim=192/576) previously crashed with
GGML_ASSERT in set-rows.cu or segfaulted in CPU flash attention.
Changes:
- llama-kv-cache.cpp: detect incompatible head_dim at KV cache init,
log a warning, and auto-fall back to q8_0 instead of crashing
- ggml-cuda.cu supports_op: return false for turbo3 SET_ROWS when
ne00 % 128 != 0, and for TURBO_WHT when ne[0] % 128 != 0
- fattn.cu: return BEST_FATTN_KERNEL_NONE for turbo3 at non-128 D
- ggml-cpu.c: add turbo3 entry to type_traits_cpu (vec_dot + from_float)
so CPU flash attention can handle turbo3 K/V for models where CUDA FA
returns NONE (e.g. D=192 which has no CUDA FA kernel for any type)
- set-rows.cu: add tail kernel for non-128 remainder (future use)
- turbo-wht.cu: head-dim-aware processing with tail pass-through
- ops.cpp: CPU WHT head-dim-aware with tail identity copy
Tested: DeepSeek-Coder-V2 (head_dim=192) now loads with -ctk turbo3
and auto-falls back to q8_0 with clear warning. Qwen3.5 (head_dim=128)
continues to use turbo3 at full speed (223 t/s).
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
fix: graceful fallback for turbo3 with non-128-aligned head dims (issue #13)
Models with n_embd_head_k not divisible by QK_TURBO3_GROUP (128) тАФ e.g.
GLM-4.7 Flash / DeepSeek2 MLA with head_dim=576 тАФ previously hard-crashed
with GGML_ASSERT(ne00 % QK_TURBO3_GROUP == 0) in set-rows.cu.
Fix:
- supports_op for SET_ROWS: return false when turbo3 and ne00 % 128 != 0,
so llama.cpp falls back to an unquantised KV path instead of asserting
- get_best_fattn_kernel: return BEST_FATTN_KERNEL_NONE for turbo3 when
K head dim is not 128-aligned (VEC kernel only instantiated for DтИИ{64,128,256})
Affected models can now load with -ctk turbo3 -ctv turbo3; the non-aligned
heads silently use f16 KV while 128-aligned heads continue to use turbo3.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
fix: VEC flash-attn Q/K stride mismatch in vec_dot_fattn_vec_KQ_turbo3_0
The outer loop in vec_dot_fattn_vec_KQ_turbo3_0 stepped k_KQ_0 by
`nthreads` (8), but the Q register file is loaded in blocks of
`nthreads*cpy_ne` (32) elements per thread тАФ the same pattern used by
the f16/bf16 VEC kernels. This caused thread t>0 to pair K element
(16s + 2t) against Q element (64*(s/4) + 8t + 2*(s%4)), a complete
index mismatch. Every generated token had garbage attention scores.
Fix: match the f16 kernel pattern тАФ step by nthreads*cpy_ne, add an
inner k_KQ_1 loop over cpy_ne pairs, and index Q_v as
Q_v[k_KQ_0/nthreads + k_KQ_1].
Also clean up stale "PPL 23.5 vs 6.19" TODO comments in llama-graph.cpp
that documented the symptom of this bug.
Tested on RTX 5090, Qwen3.5-35B-A3B-Q4_K_M:
- PPL (wikitext-2): 6.2023 тЖТ 6.2996 (+1.57%, within 5% target)
- NIAH: 11/11 at 4KтАУ256K (matches q8_0; was 0/11 before fix)
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
perf: parallel k_set_rows_turbo3 + optimise KQ/V dequant тАФ +31% decode (71тЖТ94 t/s, 98.5% of F16)
k_set_rows_turbo3 was the decode bottleneck: 1 thread/group serial kernel
gave 3.1% GPU utilisation (36.5 ┬╡s ├Ч 80 calls/token = ~21% of decode budget).
Replace with a fully parallel kernel тАФ 1 block per 128-element group,
128 threads per block (one thread per element):
тАв Shared-memory WHT butterfly (7 stages, no atomics)
тАв Warp-reduce L2 norm + inter-warp accumulate via smem
тАв qs packed with __shfl_sync (4-wide gather), signs with __ballot_sync
тАв Reconstruction norm same pattern; one write per sub-block (warp lane 0)
Also tighten flash-attention dequant paths (fattn-common.cuh):
тАв vec_dot_fattn_vec_KQ_turbo3_0: elem0/elem1 always share the same
turbo3 block тАФ load qs/signs once instead of twice per pair
тАв dequantize_V_turbo3_0: ne==4 fast path тАФ load one qs byte and one
signs byte for all 4 elements; unrolled float2 / half2 output pairs
Benchmark (Qwen3.5 35B, RTX 5090, tg128):
Before: 71.86 t/s (0.75├Ч q8_0)
After: 94.04 t/s (0.985├Ч q8_0, within measurement noise of parity)
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
perf: enable MMA/TILE flash attention for turbo3 тАФ 0.97x q8_0 prefill
Remove the 5-line early-return that forced turbo3 onto the VEC flash
attention kernel. The VEC kernel is still used for decode (Q->ne[1]==1)
via the existing dispatch logic, but prefill now goes through the Turing
MMA kernel (RTX 5090 is SM 12.0 >> 7.5).
launch_fattn already pre-dequantizes K/V to FP16 when need_f16_K/V are
set (which TILE/MMA always pass as true). Our ggml_get_to_fp16_cuda and
ggml_get_to_fp16_nc_cuda dispatchers for TURBO3_0 тАФ added in the original
CUDA port commit тАФ provide that conversion automatically. Stride
recalculation (nb11 = nb11*bs*sizeof(half)/ts) also works out correctly
for turbo3 (bs=32, ts=14): nb11*32*2/14 = ne[0]*sizeof(half). тЬУ
Before (VEC only): After (MMA for prefill):
2K prefill: 5032 t/s (0.73├Ч q8_0) 6734 t/s (0.98├Ч q8_0)
8K prefill: 3110 t/s (0.46├Ч q8_0) 6613 t/s (0.98├Ч q8_0)
32K prefill: 1215 t/s (0.19├Ч q8_0) 6168 t/s (0.97├Ч q8_0)
Matches Metal M5 Max result (0.99├Ч q8_0 flat across all context sizes).
Decode unchanged (VEC, ~0.64-0.82…
jimbothigpen
added a commit
to jimbothigpen/af-engn
that referenced
this pull request
Jun 14, 2026
…plit fix) Ports two genuinely-missing items from spiritbuun/buun-llama-cpp master, adapted to our tree. 2f (515a1a0) - contiguous-identity state-view fast-path for recurrent decode. build_rs_in() returns a ggml_view_2d of the state slot instead of a get_rows gather when states_are_contiguous_identity() holds (single-seq steady decode, rs_z==-1, no rollback remap, exact active-cell cover). Skips the per-layer get_rows + s_copy index fill on the GDN/SSM decode hot path (Qwen3.5/3.6). Graph-reuse re-checks the predicate via the new view_path flag so a baked view is never replayed over a remapped ubatch; the s_copy set_input fills are guarded on s_copy->buffer. Wired into delta-net conv-state + qwen35/qwen35moe/qwen3next ssm-state. Bit-identical per buun (KLD==noise floor, ~+1.5% TG). 2g (a3adfaa) - tensor-split (-sm tensor) split-planner fixes for GDN hybrids (ggml-org#59). handle_mul_mat: handle AXIS_2/3 batch-parallel MUL_MATs. handle_view: stride-match the outermost axis-3 split through non-permuted views (our generic block only covers axes 0..MAX_DIMS-2). Allow batch-parallel splits for SET / TRI / SOLVE_TRI (scalar_only false). delta-net identity matrix uses an independent allocation instead of a view into the (split) attn tensor, avoiding incorrect split propagation through FILL->DIAG. Struct-init adapted to our 4-field ggml_backend_meta_split_state {axis, ne, nr, n_segments}. Verify: Vulkan cell on ai01 clean compile+link; Qwen3.5-9B-Q4_K_M GDN single-turn decode produces coherent output (exercises build_rs_in + the identity change on the live single-GPU path). The 2g split-planner paths require multi-GPU CUDA (e.g. Kaggle 2xT4) to runtime-verify; compile-verified here. Batch dispositions (not ported - see worker brief): - 2b (87c351d fused turbo8-K/turbo4-V FA): BLOCKED on turbo8 codec - no functional GGML_TYPE_TURBO8_0 in main, only a non-wired skeleton on feature/buun-turbo8kv-codec-recon-draft. - 2c/2d (n_outputs==n_seqs / --no-logits-all): already-native via the n_outputs_max mechanism + server_n_outputs_max auto-compute (the mainline-canonical, more precise successor). - 2e (lean rms_norm bcast kernel): deferred - largely subsumed by our templated rms_norm_f32<has_mul,has_add> + PDL launch; marginal residual win, needs PDL adaptation, unverifiable on HIP/RDNA3.5. Source: spiritbuun/buun-llama-cpp (2f 515a1a0, 2g a3adfaa) Co-Authored-By: Claude Opus 4.8 <[email protected]>
HEchternacht
pushed a commit
to HEchternacht/llama.cpp
that referenced
this pull request
Jul 18, 2026
…gml-org#59) * metal: fix M5 device creation + add Q2_0 multi-column mul_mv kernels Two independent Metal changes: - The AGX_RELAX_CDM_CTXSTORE_TIMEOUT override (added for the long-context command-buffer timeout on M1/M2, ggml-org#20141) prevents MTLCreateSystemDefaultDevice() from returning a device on M5 / current macOS. Keep it on by default and disable it only when sysctl reports an M5 chip; GGML_METAL_RELAX_CDM_CTXSTORE_TIMEOUT=0/1 forces either way. - Add Q1_0-style multi-column mul_mv variants for Q2_0 (nr1 2/3/4): read the streamed weights once for nr1 output columns via a 2-bit weight expansion and an FMA inner loop, instead of re-reading them per column on the mul_mv_ext path. Opt-in via GGML_METAL_Q2_0_NR1 (default routing unchanged). Measured [4096,14336] on M5 Pro: nr1_2 93.2 us at ne11=2 vs 122 for the ext route. 41/41 test-backend-ops MUL_MAT q2_0 on both routings. * speculative: Metal DSpark Markov resample + quantized markov heads Adds a Metal device path for the block Markov resample, alongside the existing CUDA path. It builds one dependency-chain graph for the whole draft block (each step's GPU argmax feeds the next step's get_rows) and submits it once, reading the drafter's still-device-resident logits, so the sequential Markov dependency stays exact with a single sync. Falls back to the host path when the head type or backend is unsupported, or when DSPARK_MARKOV_CPU=1. Also teaches llama_model_dspark_get_markov to dequantize quantized markov head tensors (Q4_0/Q5_0/Q8_0) for the host/CUDA path, instead of rejecting everything but f32/f16/bf16 -- drafters that ship quantized heads previously had the correction silently disabled (has_markov=0). Validated on Metal: accept counts byte-identical to the CPU-forced path; the Metal resample runs ~1.8x the single-thread CPU Markov path.
ishikawa
added a commit
to ishikawa/llama.cpp
that referenced
this pull request
Jul 22, 2026
深部 KV の GQA 共有読み flash-attention vec カーネルの QK dot を `simdgroup_matrix` のタイル積に置き換える。 共有読みパスは 8 q head 分の QK dot を per-(head, 位置) の `simd_sum` 直列 (1 iteration あたり 32 位置 × 8 head = 256 回) で行っており、命令発行数が律速で深部の実効帯域が 151 GB/s に留まっていた (切り分けは ishikawa/local-llm#60)。Q (8 head × DK) と K (32 位置 × DK) の積を `simdgroup_half8x8` のタイル積 (float 累積) に載せ替え、simd reduction を行列ユニットに置換する。 設計記録: ishikawa/local-llm#62 ## 設計 - 発動条件: NH==8 の共有読みブロック内で K/Q が F16 direct の場合のみ (コンパイル時 `is_same` ゲート)。量子化 K は従来の dot + `simd_sum` パスにフォールバック - タイル構成: `simdgroup_float8x8` 累積に対し DK/16 反復 × C/8 出力タイル。K は device メモリから `transpose=true` で `simdgroup_load`、Q は threadgroup 上の共有 Q から読む - S への scale/softcap/bias/mask 適用は従来と等価 (タイルを `ss` に store した後、レーンごとに適用) - V accumulate は対象外。行列化には P の repack と rescale 用対角行列の構築で barrier 同期が増え、利得が相殺されることを実測して不採用とした ## 実測 > [!NOTE] > 計測環境: Mac mini M4 Pro。op は `test-backend-ops perf` の `FLASH_ATTN_EXT` (A3B decode 形状: `DK=DV=256`・q16/kv2・F16 KV・batch1)。decode は spec_bench (Qwen3.6-35B-A3B UD-Q4_K_XL、seed 42、同条件 A/B)。 op (baseline は ggml-org#59 反映後の再計測): <!-- prettier-ignore-start --> | kv | baseline us | 本 PR us | 改善 | メモリ床 | | ---: | ---: | ---: | ---: | ---: | | 98,304 | 1357 | 1148 | 15.4% | 844 | | 131,072 | 1745 | 1451 | 16.8% | 1124 | | 245,760 | 3058 | 2529 | 17.3% | 2103 | <!-- prettier-ignore-end --> 実モデル decode: <!-- prettier-ignore-start --> | 深度 | baseline tok/s | 本 PR tok/s | 差 | | ---: | ---: | ---: | ---: | | 4k | 43.64 | 44.6 | ノイズ内 (非共有パス不変) | | 245k | 19.00 | 21.12 | +11.2% | <!-- prettier-ignore-end --> - 245k の op 改善 17.3% のうち約 2/3 が実 decode に乗った - 245k は op 2529 us に対しメモリ床 2103 us で、まだ計算律速が残る ## 検証 - `FLASH_ATTN_EXT` correctness 全形状 pass (`-b MTL0`)。深部共有パス (kv=98304/131072/245760、kvpad 非整列・sinks 含む) の ERR 0.0022–0.0052 で baseline 同水準 (F16 累積) - kv≈65k 境界で従来から失敗する既知 5 件は変更前後で同一 (本変更起因でない) - 非共有パス・hsk≠256 形状の回帰なし - 実モデル evals (13 タスク、repeat 3) は ishikawa/local-llm#62 の受入ゲートとして実行し、結果は同 issue に記録する
ajaxdude
pushed a commit
to ajaxdude/llama.cpp
that referenced
this pull request
Sep 14, 2026
Integrate the exact PR ggml-org#59 successor that signals completed downloads before publishing final progress. Assisted-by: GPT-5.6 Sol Co-authored-by: Copilot App <[email protected]>
stew675
added a commit
to stew675/llama.cpp
that referenced
this pull request
Oct 8, 2026
The RDNA memory campaign, squashed into one block: six validated wins that
remove ~3.4 GiB/GPU of compute-buffer VRAM and ~1.2 GiB of host buffer on
qwen4exp (ctx 204800 / ub 2048 / q8_0 KV), plus ~800 MiB/GPU + 800 MiB host
on every dense model, at a measured ~1.3 % prefill / ~0.3 % decode cost.
Each win keeps an environment kill-switch for A/B (the V4 arm is opt-in).
W1 - QSA score-chain memory (GGML_QSA_SCORE_MEM, default 1)
relu before the 4-D reshape (elementwise, bit-identical, but it stops the
allocator from holding the mul_mat result and its relu simultaneously) +
n_blocks-chunked assembly with ggml_concat past a size threshold.
qwen4exp ub 2048: 6690.40 -> 4450.40 MiB/GPU.
W2 - derived QSA per-block bias + derived visibility (GGML_QSA_DERIVED_BIAS,
GGML_QSA_DERIVED_VIS, LLAMA_QSA_SPARSE_FA, defaults 1/1/sparse): the
n_blocks x n_tps F32 bias tensor and the additive kq mask are no longer
materialised; the fused top-k/FA kernels derive both in-kernel from
compact per-cell state. Includes the input-fill null guards (a tensor the
graph never consumes is left unallocated by the gallocr, so every
fill site must tolerate buffer == nullptr) and the llm_graph_input_attn_k
null-mask guard. qwen4exp ub 2048: 4450.40 -> 3251.39 MiB/GPU, host
1262.70 -> 63.69 MiB.
W3 - keys-only QSA indexer cache (LLAMA_QSA_KEYS_ONLY, default 1): the
indexer scores blocks of keys and never reads a stored value, so its
cache is created with no V tensor. Indexer KV 956.26 -> 318.76 MiB/GPU
at ctx 204800 (the store is replicated on every GPU).
W4 - ggml-alloc: release view sources whose views are never consumed (the
counting pass increments view_src->n_views for every view node, but the
free pass only decrements it when the view is released - a view with no
consumers is never released, so the inflated count blocks the view
source's release and in-place reuse). Repro 56.00 -> 16.00 MiB. No gate:
it is a bug fix, A/B with beta/block-15-campaign-wins/ab/w4-revert.patch.
V3 - derived kq mask for the plain attention path (LLAMA_KQ_MASK_DERIVED,
default 1): the packed n_kv x n_tps F16 mask and its host mirror are no
longer materialised - the MMA FA kernel derives each cell's visibility
from compact per-cell state (GGML_OP_FLASH_ATTN_EXT gains src[5..7]: cell
positions, per-token hi/lo bounds). The packed tensor is still created in
every graph, so it simply ends up with no consumer: the allocator leaves
it unallocated and the existing fill guards skip the fill (no model list,
no consumer can be mis-served). The predicate is proven cell-by-cell
value-identical (including both SWA cache variants and non-causal) and
gates itself off on every unsupported case (alibi, multi-sequence,
small/verify batches, non-MMA backends, M-RoPE ext clause). Dense models:
-799.20 MiB/GPU and -799.21 MiB host; gemma-4-E4B (ISWA) -809.18/-809.18;
gemma-4-31B (ISWA) -811.17/-811.18; scaling exactly n_kv x n_tps x 2 B.
The backend support probe is skipped entirely on a multi-stream KV cache
(n_seq_max > 1 without kv_unified, and deepseek4, which keeps per-sequence
streams even in unified mode): it forces a single-sequence probe graph, and
on such a cache deepseek4's indexer stream layout asserts, while the derived
form is unreachable there anyway (kq_mask_derivable() requires a single
stream).
V4 - native q8_0 K/V in the flash-attention kernels (GGML_CUDA_FA_KV_NATIVE,
OPT-IN, default 0): the whole-cache F16 staging scratch and its per-ubatch
conversion are replaced by dequantising each 16-byte staged chunk while
the shared K/V tiles are loaded (a chunk is 8 elements = a quarter q8_0
block, and every MMA/TILE batch is a multiple of 8 elements, so a chunk
never straddles a block). The staged values are bit-identical to
dequantize_block_q8_0_f16. Dense models: -744 MiB/GPU (4B), -632 (27B),
-1224 (gemma-4-31B) at ctx 204800/ub 2048, more at smaller ub; qwen4exp
unchanged. Ships opt-in: it costs ~1.7-1.9 % prefill (the lost cp_async
pipeline - a quantized source cannot be copied asynchronously) with a
large memory win and no cheap way to close the gap; decode is untouched.
TILE and VEC already read bf16/f16 natively.
Validation (2026-09-10, 3x R9700/RDNA4, ctx 204800, q8_0 KV unless noted;
full record: beta/block-15-campaign-wins/):
- reserve matrix, all five models x ub 2048/1024/512 x V4 off/on: every
number matches the per-win records (the wins compose additively:
-2240 W1, -1199 W2, 0/-637.5 W3, -799 V3, -744/-632 V4 per GPU).
- same-seed generated text byte-identical on 4B, 27B, gemma-4-E4B (ISWA),
gemma-4-31B (ISWA) and qwen4exp across every gate combination (V3 on/off
x V4 on/off; qwen4exp W1/W2/W3/W4/V3/V4 flips - 7 configurations), at a
short and a 40k-token prompt.
- adaptive-MTP gate unchanged: 27B inline draft 0.76744 (66/86, mean 3.28)
identical in all four gate combinations; qwen4exp draft 0.44262 (54/122)
identical in all six, and equal to the block-14 baseline; MTP still
+26 % over plain decode.
- test-backend-ops: FLASH_ATTN_EXT on ROCm0 (both V4 gates) and CPU, the
derived FA cases, VIEW/CONT/CPY/DUP/CONCAT; test-alloc and
test-batch-alloc; the W4 repro goes 56.00 -> 16.00 MiB and the revert
patch restores ggml-alloc.c byte-identically.
- prefill cost, interleaved same-binary A/B: V3 -1.28 % pp20480/ub 2048 on
the 4B (the 27B is neutral, +0.28 %), V4 a further -1.85 % (4B) /
-1.72 % (27B); decode within noise in every case.
Known pre-existing issue found during this validation (NOT introduced here,
reproduces on block 14): gemma-4-E4B-it on 3 GPUs with -sm tensor aborts in
the meta splitter (ggml-backend-meta.cpp:1177, a FLASH_ATTN_EXT node whose K
source has zero extent on one buffer because n_head_kv = 2 < 3 devices).
It works on 1 GPU, on 2 GPUs, and on 3 GPUs with -sm layer. All other
models are unaffected. Out of scope for this block.
Beta staging, gate table and the full validation record:
beta/block-15-campaign-wins/README.md; the per-win designs:
wip/arch-independent-memory/{V3-DERIVED-KQ-MASK-PLAN,V4-NATIVE-Q8-KV-PLAN,
DERIVED-MASK-DESIGN}.md and wip/qwen4exp/qsa-memory/.
Amended 2026-09-10 with V5 - native bf16 K/V in the MMA flash-attention
kernel (gated by the SAME GGML_CUDA_FA_KV_NATIVE switch as V4, default 0,
i.e. opt-in): a bf16 K/V cache no longer needs the F16 staging scratch. A
bf16 source row and the F16 tile it feeds have the same byte layout (2
bytes per element, 16-byte chunks), so the MMA loader converts each staged
chunk in registers (bf16 -> f32 -> f16, bit-identical to the launcher's
ggml_get_to_fp16_cuda(GGML_TYPE_BF16)) instead of copying it, and the
scratch sizing plus the whole-cache conversion pass are skipped for that
operand. The staging source is now a single type code
(fattn_kv_native_t{FATTN_KV_NATIVE_NONE,Q8_0,BF16}) shared by the launcher,
the alloc-size query and both kernels, so they cannot disagree on whether
the scratch exists (the old use_q8_K/use_q8_V flags are subsumed).
- reserve (ctx 204800, ub 2048, bf16 KV, arm on): 4B 968.86 -> 256.86,
27B 1072.86 -> 488.86, gemma-4-E4B (ISWA) 1062.89 -> 404.89,
gemma-4-31B (ISWA) 2068.89 -> 716.89 MiB/GPU - exactly the F16 cache's
footprint; ub 1024/512 win 756/778 (4B) and 746 (27B); qwen4exp is
unaffected (its FA path never staged bf16 - f16 == bf16 == on/off there),
and the TILE/VEC paths already read bf16 natively (ub 8: 8.09 both ways).
- same-seed generated text byte-identical (bf16 native vs staged vs f16) on
4B, 27B, gemma-4-E4B and gemma-4-31B, short and 3k/40k-token prompts,
with the V3 derived mask active; the two wins are additive (4B: derived
mask -799.2 MiB, bf16 scratch -712.0 MiB, both verified independently).
- adaptive-MTP gate unchanged: 27B 0.82716 and qwen4exp 0.44262 identical
with the arm on and off; the recorded q8_0 references (27B 0.76744,
qwen4exp 0.44262) are unchanged by the refactor.
- test-backend-ops FLASH_ATTN_EXT: 7859/7859 on ROCm0 and CPU; the 2704
bf16 K/V cases (every head size, including the 576/512 MLA V-is-K-view
layout) and the 365 q8_0 cases pass with the arm on and off, with
identical case lists.
- prefill cost (interleaved same-binary A/B, arm off -> on): the conversion
itself is free (native bf16 staging measures within 0.2 % of an F16
cache), but dropping the scratch costs 4B -0.2 % (pp2048), +0.3 % (8192),
-1.06 % (20480), -2.36 % (40960) and 27B -0.76 % (20480); decode is
within 0.1 % everywhere. The launcher's F16 copy is a dense, normalized
copy of the cache view (the GQA heads are interleaved - for the 4B nb[1]
is 2048 B for a 512 B row), and the native path re-reads that view on
every staging pass. Hence opt-in, exactly like V4 (D9: a sub-2 % loss
with a large memory win and no cheap fix ships behind a switch).
Mixed K/V cache types (bf16+q8_0, f16+q8_0, either direction) remain a
pre-existing trap, documented but not fixed here: the attention falls off
the GPU kernel path (graph splits 18 vs 2, ~1.5 GiB host compute buffer,
4B pp2048 7924 -> 640-1049 t/s). Same-type K/V is the practical choice.
2026-09-10 RDNA3_5 (gfx1151) amendment: V3 (derived kq mask) now
engages on a ROCm/HIP iGPU. The probe rejected
GGML_BACKEND_DEVICE_TYPE_IGPU as "not the CUDA/HIP backend", so on
Strix Halo V3 was silently disabled and its ~800 MiB compute + ~800 MiB
host win was lost. The device-type gate now accepts IGPU (the ROCm/HIP
reg name is still required), and the derived form additionally requires
a single KV stream: build_attn_mha derives the attention stream count
from the KV tensor (k->ne[3] == the cache's n_stream), so with
n_seq_max > 1 -- even for a single-sequence ubatch -- the derived tok_lo
was built for one stream while Q was reshaped for n_seq_max streams and
the shape assert in ggml_flash_attn_ext_add_kq_derived aborted context
creation. kq_mask_derivable() now rejects n_stream != 1, so a
multi-slot context keeps the packed mask (no crash) and a single-stream
context gets the win.
Validated on Strix Halo (gfx1151, ROCm 7.14): V3 on/off byte-identical
over 7 KV/arm configs x 16 runs x 129 tokens (2064 gate cells each);
reserves reproduce the RDNA4 numbers exactly (4B ctx 204800/ub 2048:
V3 -799.20 MiB compute / -799.21 host, V5 bf16 968.86 -> 256.86, V4 q8_0
1001.13 -> 257.13); the derived test-backend-ops cases pass on ROCm0;
and llama-server --parallel 4 (the config that aborted before) now
serves and passes the 16-run gate. Discrete GPUs are unaffected (they
report GGML_BACKEND_DEVICE_TYPE_GPU and normally have n_stream == 1).
Amended 2026-09-11 (9th re-cut): fix a variable-shadowing bug in build_attn_qsa that broke the
LLAMA_QSA_SPARSE_FA=0 dense arm for every model/type. The V2/V3 refactor wrapped the top-k mask
chain in `if (kq_mask != nullptr) { ... }` and added an outer `kq_mask_top_k` declaration, leaving
the chain's own `ggml_tensor * kq_mask_top_k = ggml_set_rows(...)` inside the block as a NEW local.
The chain was therefore built (whenever the mask existed) but its result never reached the
attention: build_attn_mha got the outer `nullptr`, the chain's nodes were unreachable from the
graph output (so ggml never emitted them), the packed mask lost its only consumer (so the
allocator dropped it and set_input_kq_mask was skipped), and the dense arm attended with no mask
at all - a full causal leak. Observed as qwen4exp perplexity ~1.02-1.06 on every KV type
(delivery: 6.49-6.55), and as ~1.03 on RANDOM text (delivery ~18.4), with dense-arm greedy text
differing from the delivery. Fixed by assigning the block's result to the outer variable
(dropping the inner `ggml_tensor *`). The production (sparse) arm never enters that block, so it
is bit-identical before and after. See beta/block-15-campaign-wins/BETA-TESTING.md 4c and
WORKLOG.md 2026-09-11 (11).
2026-09-14 amendment (issue ggml-org#30, "wider configuration"): V4 is no longer opt-in for
the sub-F16 quantized cache types, and q4_0 gains a native arm.
- GGML_CUDA_FA_KV_NATIVE is now a three-state policy: unset = auto (native
q8_0/q4_0 ON, native bf16 OFF), =1 forces both on, =0 forces the pre-amendment
F16-staging path (the escape hatch). The whole-cache F16 staging pass is
proportional to n_kv and runs on every decode step, so removing it for the
sub-F16 quants is worth +23 % tg64 at d65536 on gfx1201 (q8_0 18.92 -> 23.29
vs stock 22.43) at ~1.2 % prefill, and it recovers ~744 MiB/GPU of scratch.
- Native q4_0 arm beside q8_0/bf16 (ggml_cuda_fattn_dequantize_q4_0_chunk,
arithmetic-identical to convert.cu's dequantize_block_q4_0) in the tile and
MMA kernels: q4_0 d65536 19.72 -> 22.82 vs stock 21.03, ~1.3 % prefill.
- Bit-identical to the staging path (same-seed greedy text) and width-pure
(W = 1..8 one logits hash per KV type); MTP n_max 3 acceptance unchanged
(0.75182). Full evidence: wip/issue-30-mtp-decode-regression/MEASUREMENTS.md.
- Side effect: also fixes the adaptive-MTP high-context load failure
(--spec-draft-n-max 12 -c 196608 q8_0, default 4 slots): the F16 staging
scratch was exactly the 260 MiB the draft context was short, so it now loads
and generates.
2026-09-15 amendment (issue ggml-org#30, the reporter's r3 review): the q4_0 NaN fix, the prefill band
split, and native arms for the last four quantized K/V types.
- Mixed-K/V kernel contract (the reporter's 4 NaN failures in test-backend-ops -o
FLASH_ATTN_EXT). The tile kernel is instantiated with ONE type_KV for both operands and
builds its native descriptors from that compile-time type, while launch_fattn chose its
native read per tensor; a mixed pair (K=q4_0, V=f16) therefore fell back to the F16 tile
with K's staging skipped, and the kernel read raw q4_0 as F16. launch_fattn now takes the
kernel's native type explicitly (kv_native_kernel; the tile passes its type_KV, the vec
passes NONE, the MMA keeps per-operand semantics). llama.cpp rejects mixed caches, so only
the op test could see it.
- ggml_cuda_flash_attn_ext_get_alloc_size's TILE case never learned the q4_0 arm, so a q4_0
cache kept reserving the F16 scratch the launcher no longer used: -c 196608 q4_0
849.04 -> 123.04 MiB -- the arm's memory win had never actually been delivered.
- Prefill band split: a prefill (n_q > 8) stages the operand into F16 while decode/verify
(n_q <= 8) keeps the native read, recovering the quantized-KV prefill cost (q8_0 pp150000
661.0 -> 691.4 on 1 GPU, 996.0 -> 1076.9 on 2, 1111.4 -> 1199.0 on 3; q4_0 694.5). The
staging scratch comes from a new per-context, per-stream arena
(ggml_backend_cuda_context::fattn_stage / fattn_stage_get) instead of the compute-graph
reserve, which sized it for n_ctx (~726 MiB at a 200k context) even though the real
scratch tracks the prefix; a multi-token graph is never CUDA-graph captured, so a runtime
allocation there is safe. Bounded by GGML_CUDA_FA_STAGE_MAX_MB (default 512 MiB, 0 =
unbounded). Arch-gated: RDNA3_5 keeps the native read at prefill (it wins at every depth
there: gfx1151 9B q8_0 pp16k 1410 vs 1405, pp65k 1059 vs 1043), RDNA4/RDNA3_0 stage.
- Native arms for q4_1 / q5_0 / q5_1 / iq4_nl (ggml_cuda_fattn_dequantize_{q4_1,q5_0,q5_1,
iq4_nl}_chunk, arithmetic-identical to convert.cu), closing the last gap in the V4 set --
the four types stage through F16 otherwise. tg64 @ d32768 staged -> native: gfx1201
+9.9/+10.8/+12.5/+8.8 % (q4_1 23.14 -> 25.44, q5_0 22.16 -> 24.56, q5_1 22.23 -> 25.00,
iq4_nl 22.92 -> 24.94) with prefill unchanged; gfx1151 (9B) +22.9/+26.0/+26.7/+22.0 % for a
0.6-1.1 % prefill cost. Two bugs the op test caught on the way: the tile loader chose the
native branch with a hand-written `type_KV == Q8_0 || Q4_0` test (the new instantiations
then took the F16 branch and read an unwritten staging buffer -- the hsk=72 NaNs), and the
q5_0/q5_1 chunk helpers took the low nibble in both halves.
- Same-seed greedy text is bit-identical native vs staging for all eight KV types on both
arches, and test-backend-ops -o FLASH_ATTN_EXT is 5951/5951 on both. Width purity: gfx1151
pure for all eight types; gfx1201 pure except the documented pre-existing q4_0 logits-level
band edges (GREEDY-PURITY.md 36, whose guarantee is now stated at the text/acceptance
level).
2026-09-15 amendment (build time): the tile kernel's native-KV type axis is instantiated in the
generated template-instance TUs again instead of implicitly in the tile dispatch TU.
Block 03 turned type_KV into a template parameter of ggml_cuda_flash_attn_ext_tile_case so the tile
kernel could read BF16 (and later the quantized types) natively, while DECL_FATTN_TILE_CASE /
EXTERN_DECL_FATTN_TILE_CASES kept covering only F16/BF16. Because the dispatch in fattn-tile.cu has an
unconditional `case` per native type, the other six types were then instantiated *implicitly in that
TU*: 12 head-size combinations x 6 types = 72 case instantiations (96 symbols including the 24 externed
F16/BF16), each pulling in both softcap variants and the whole ncols2 chain. With block 08's
FA_QUANTS default (8 diagonal pairs) that single TU took 509 s of a 538 s `-j16` backend build on a
16-core machine (measured 2026-09-15, gfx1201) -- it *was* the critical path, and no amount of build
parallelism could help.
The macros now cover every type the dispatch can select, so the 12 generated
template-instances/fattn-tile-instance-*.cu files instantiate 8 cases each and the dispatch TU holds
only `extern` declarations. Build time: `ggml-hip` 538 s -> 330 s, and the tile dispatch TU itself
drops from 509 s to under 10 s.
The remaining critical path is the `fattn-mma-f16` instance set, and that one is ours too: this
block's native-KV arms instantiate the whole WMMA kernel once per KV type *inside every instance TU*
(the arm chain in `ggml_cuda_flash_attn_ext_mma_f16_case`), so each of the 21 instance files compiles
8 kernel copies. Measured on the same TU (`ncols1_4-ncols2_4`): object 0.90 MB -> 7.26 MB, compile
6.7 s -> 229 s. Fixing it needs either a finer generated-file granularity (~21 -> ~150 TUs) or a
runtime KV-type dispatch in the WMMA loader, i.e. a code-path change with its own A/B, so it is left
as a follow-up rather than folded in here.
Nothing about the kernels changed -- same template arguments, same flags, same device code; only the TU
that emits them differs. Verified: `test-backend-ops -o FLASH_ATTN_EXT` 5951/5951 with zero failures,
the 27B prose text hashes bit-identical to the pre-amendment build (q8_0 472b282950b5, q4_0
118eb7f5fe85, f16 70960317a203), and `tg64@32768`/`pp8192` reproduce the recorded values within
run-to-run noise across five KV types.
Amended 2026-09-17: the HIP build now passes `-Wno-pass-failed`. The FA
kernels carry bare `#pragma unroll` hints on runtime-bounded loops, so AMDGPU
clang reports every one it cannot honour; the native-KV arms instantiate the
WMMA kernel per KV type per instance TU and multiply that into ~10k "loop not
unrolled" warning lines per clean build. The hints are advisory and the pass
already failed, so the build output is unchanged -- only the flood is gone.
HIP-only (the diagnostic is Clang/AMDGPU). See wip/build-time-regression/.
Amended 2026-09-18: the tile template instances are generated per (head size, KV type) instead of
per head size, matching the per-type axis this block introduced. Build-time only: the same 96
instantiations, identical symbols.
Amended 2026-09-25 (issue ggml-org#45): the RDNA4 GQA-6 decode/verify flash-attention band.
At head 256 with GQA 6, the tile kernel can only fold ncols2 = 2 (its ncols2 must divide
the GQA ratio), so the whole n_q <= 8 band fetched and dequantized every K/V element once
per head pair -- three times per query row at 276 GB/s on q8_0. The band now routes the
whole band (n_q = 1 included) to the WMMA kernel with the GQA group folded into ncols2 = 8
(existing (256, ncols1 4|2, ncols2 8) instances, no new instantiations): one block covers
the group, and the KV is split round-robin over a fixed P = nsm blocks per output tile
(launch_fattn, GGML_HIP_FA_BAND_WMMA_SPLIT override). P depends on neither n_q nor the KV
length, so decode and every verify width accumulate the same partials in the same order --
the round-robin form is what keeps the GREEDY-PURITY band invariant (a contiguous stream-k
split moved its split points with the 256-padded KV length and broke it).
- kernel chooser, ncols dispatcher and launch_fattn share one self-contained predicate
(ggml_cuda_fattn_band_wmma_applies), and launch_fattn also requires the ncols2 == 8
template parameter, so a disagreement can never launch the 2-D grid into a kernel whose
fast path is compiled out.
- coverage follows ggml_cuda_fattn_kv_native_type, not a hand-written type list: every
native quantized K/V type wins (q8_0, q4_0, q4_1, q5_0, q5_1, iq4_nl); f16 stays on tile
(DRAM-bound) and bf16 stays on tile while its native arm is opt-in.
- default ON (maintainer policy); GGML_HIP_FA_BAND_WMMA=0 opts out (=2 picks ncols1 = 2).
GGML_CUDA_FA_WMMA_256=0 / GGML_CUDA_FA_WMMA_MAX_HEAD<256 still disable the band.
Measured on gfx1201 (R9700), 27B qwen35 head 256 GQA 6, q8_0 KV, op level kv 16384
(tile -> band, us/run): n_q 3 326 -> 150, n_q 5 524 -> 225, n_q 8 814 -> 230; n_q 1
141 -> 148 (q4_0/q4_1/iq4_nl are faster at n_q 1 too). End to end, 27B UD-Q4_K_XL
draft-mtp n3 at ~40k ctx, band off -> on: 1 GPU 43.3 -> 51.3, 2 GPU tensor 67.9 -> 76.6,
3 GPU tensor 77.6 -> 88.8 t/s (+13-18 %), while pp512/2048/4096 are flat (the band is
gated to n_q <= 8, so prefill is untouched by construction).
Purity re-verified with the band on: test-backend-ops -o FLASH_ATTN_EXT 6340/6340 on
ROCm0 (389 GQA-6 cases across all eight KV types, both layouts); plain == draft-mtp
byte-identical on all eight KV types at ~40k ctx, 3-GPU tensor (acceptance 0.83-0.86),
and q8_0/q4_0 text identical across --spec-draft-n-max 3/5/7 (verify widths 4/6/8);
1 GPU layer, 2/3 GPU tensor and 3 GPU layer are all pure. New qwen35-band eval and
perf cases added to tests/test-backend-ops.cpp.
Folds beta/mmb-general: 0002 (qsa3 packed WMMA), 0003 (qwen4exp always-QSA flip), 0004 (HC16
native-BF16 producers), 0005 (fused indexer top-k), 0008 (HC16/beneficial defaults on
ggml-cuda.cu + llama-context.cpp), 0011 (qsa3 on RDNA3_0), 0013 (hc_gate_mix), 0016 (-lzm auto
+ managed PLE gate), 0017 (HC BF16 streams), 0018 (out_xn BF16), 0019 (indexer relu+head-sum),
0020 (F32 activations on eval callback), 0021 (sparse MTP-draft attention), 0022 (derived indexer
cache ON), 0023 (QSA gfx1151 crossover), 0024 (HC16 per-backend state), 0026 (meta child
graph_optimize markings).
Amended 2026-09-27 (issue ggml-org#53): the derived kq-mask inputs must not be read on
the host, and the frontend test cases must set tensors through the backend API.
The r10 fully-masked KV-group skip built its batch-wide bitmap by dereferencing
`tok_lo`/`tok_hi` on the CPU in `launch_fattn`. Those are host graph inputs
(GGML_TENSOR_FLAG_INPUT), and the backend scheduler copies such an input to the
compute backend, so the tensors the launcher sees are the *device* copies. A
host read of device memory is an access violation wherever the allocation is
not CPU-mapped - on Windows/WDDM it is a 0xC0000005 in ggml-hip.dll on the very
first prefill ubatch (the reporter's r10 crash) - and a race against the
in-flight copy everywhere else. The batch-wide [lo_min, hi_max] window is now
computed inside `flash_attn_kq_derived_blocks` from the device-resident
`tok_lo`/`tok_hi`; the bitmap it produces is unchanged (same integer min/max),
so the skip is still exact. Verified on gfx1201: test-backend-ops
-o FLASH_ATTN_EXT 6354/6354 with the MMA and the tile kernel (and the 20
derived/mask_hole cases specifically), FLASH_ATTN_QSA 26/26, and 4B Q8_0
same-seed text identical across {skip on, skip=0, derived=0}.
The same class of bug is fixed in tests/test-backend-ops.cpp: the derived
(`cell_pos`/`tok_lo`/`tok_hi`), packed `mask_hole` and `FLASH_ATTN_QSA`
(`idx`/`m`) initializers wrote `t->data` directly instead of going through
`ggml_backend_tensor_set`, so on Windows the first `derived=1` case segfaulted
before any derived case ran (also reported in issue ggml-org#53). The QSA tensors are
block-14 test code; the fix rides in block 15 because it is the last block.
Amended 2026-09-29 (issue ggml-org#65): cache the getenv() lookups on the fusion and staging hot paths.
ggml_can_fuse_subgraph_ext() read LLAMA_HC_CN_DEBUG for every candidate fusion window (millions of
calls per pass), ggml_cuda_try_fuse() read it again in the four hc_combine_norm matcher paths, and
gdn_conv_enabled()/ple_conv_enabled() read GGML_CUDA_DISABLE_CONV_FUSION once per conv launch. On
Linux getenv() is cheap, but on Windows it takes a lock and rescans the environment block: the
reporter measured 2,431,189 LLAMA_HC_CN_DEBUG calls and 31,204 GGML_CUDA_DISABLE_CONV_FUSION calls
per 256 decoded tokens, ~15 ms of extra host time per graph, and a GPU that sat idle waiting on the
host (Windows decode ~40 vs ~45 t/s against v16-ebbb18522-r11; Linux unaffected because getenv() is
cheap there). Each switch is now resolved once (a static at the call site, or a file-static where
the same flag is read from several sites).
The same sweep caches the other debug/A-B flags that sit on per-op, per-graph and per-tensor paths:
GGML_CUDA_GCDBG, GGML_CUDA_OP_TIMING, GGML_STREAMDBG, GGML_CUDA_MMB_MARK_LOG, the GGML_META_*
staging/gather gates, GGML_CUDA_MMQ_J_MAX/_ROUTED, GGML_Q6_COMPACT_J, GGML_CUDA_DISABLE_MMID_512,
GGML_PAIR_2X, GGML_CUDA_GDN_CHUNKED(_BF16), GDN_DBG_*, GGML_CUDA_FA_WMMA_256/MAX_HEAD,
GGML_CUDA_QSA_SLICES/IDENTITY, the scheduler's GGML_SCHED_* gates (in ggml-backend.cpp), the meta
backend's GGML_META_* gates, and GGML_CPU_MOE_OFFLOAD_THREADS. The exact-affecting conv switches
fold into block 08's files; everything else rides in block 15 because it is the last block. The
values are read at first use, before any graph runs, so behaviour is unchanged.
This also fixes the clean-build warnings: the ggml_backend_graph_optimize_params aggregate now sets
marks_only/allocs_only, the meta debug prints test tensor->name[0] instead of the always-true array
address, the ignored cudaFree()/hipHostRegister() results are cast to void, the unused
llama_kv_cache::v_enabled member (shadowed by the constructor parameter) is dropped, and the test
probe's unused jmax is removed. Verified on gfx1201 (ROCm 7.14, 3x R9700): same-seed greedy text
byte-identical to the pre-amendment build on the 4B (83eec5e9b4f0), clean backend build with zero
warnings.
Amended 2026-09-29 (PR ggml-org#64, @briansp2020): three bit-exact RDNA4 verify-band wins folded in.
1) FA band: one 64-column block for query widths 5..8. The band ran ncols1 = 4 (32 columns)
per block, so a 5..8-token verify launched two column tiles that each streamed the whole KV
cache (q8_0 attention ~70 % slower at n_q = 5 than at n_q = 4). A ncols == 64 band row
(512 threads, nbatch_combine 32) keeps 4 warps per Q column group, so every column sees the
same KV-row split and combine order; it is used for the ncols1 == 4 band from 4096 KV rows.
GGML_HIP_FA_BAND_WIDE=0 restores the two-tile launch. gfx1201 q8_0 n_q 5..8: -10..-15 %.
2) ssm_gate_beta_fused_q8_0 gets an ncols template parameter, so the fused Q8_0 alpha/beta
projections + softplus/sigmoid chain serves the 2..8-token verify band too (each token keeps
the single-token K order, cross-warp reduction and calc_nwarps_weight() selector). -144
launches per 5-token pass. GGML_CUDA_FUSE_GATE_BETA_VERIFY=0 is the off switch.
3) The residual ADD in front of rms_norm_q8_1 (a standalone k_bin_bcast at 2..8 tokens, folded
into the mmvq epilogue at one token) is computed inside the norm kernel
(rms_norm_q8_1_f32<.., has_add>). -127 launches per 5-token pass.
GGML_CUDA_FUSE_ADD_RMS_Q8=0 is the off switch.
All three are default-on (maintainer policy) with per-patch kill switches. Independently
re-verified here on gfx1201 / ROCm 7.14 / 3x R9700: test-backend-ops -o FLASH_ATTN_EXT
6354/6354; test-logits-width-probe (27B UD-Q4_K_XL, q8_0 KV, RS=from_w) PASS with every W and
row0/row1 hash byte-identical with the fusions on vs off and with the wide band on vs off; the
4B same-seed coherence hash is unchanged (83eec5e9b4f0); clean build. The contributor measured
-1.4..-2.6 % ms per server verify step; only ROCm 10.0 was measured on their side.
Campaign fold (wip/moe-expert-cache, beta2): the CUDA consumer hooks of the
decode-side MoE expert cache. Adds the cache-aware fused gate+up+GLU and down
folds, the `MUL_MAT_ID` takeover and the cache-band fusion stand-down in
ggml-cuda.cu, the backend iface assignment, the `h2d_pin`/`h2d_scratch`
staging helpers the gather uses in common.cuh, and the `stage_gather`
return-value guard in ggml-backend-meta.cpp. The engine and the kernel slot
lookup are in block 13; the generic interface and the scheduler/Meta
delegation are in block 06; the gemma4 `-sm tensor` exclusion is in block 14.
These pieces ride here because they interleave with block 15's own fusion and
staging code. The campaign's bring-up/A-B instrumentation (the CPU routing
profiler, the CPU-computes split, the adaptive staging probe, the
debug/verify/progress/timing/fail-alloc knobs and the unsafe GGML_META_NOSYNC)
was stripped for the promotion candidate.
beta5 cleanup (2026-10-02): removed the campaign's leftover env-gated debug/A-B instrumentation
(documented as a follow-up at r16). All 25 knobs are gone, with their defaults hard-coded:
GGML_META_DEBUG/CNDBG/SSDBG/SS_FIX/REDDBG/VIEWDBG/BUFDBG/SPLITDBG/TOUCHSRC/UPLOADDBG/
NO_2D/SYNCUPLOAD/STAGEDBG/GCDBG/EXECDBG/READIDS/SYNCEACH/GATHERDBG/GATHER_MODE/
PINSRC/PINHOST/PINRING/D2DSPLICE, plus GGML_SCHED_SYNCDBG and GGML_SET_BYTES/SET_NAMES and the
TEMP INSTRUMENT blocks they powered (g_ss_*, g_ring_*, g_meta_gc_*, g_gather_*, g_h2d_*, the pool /
per-op timers). Behaviour is unchanged on every default path: build warning-free, MUL_MAT_ID
929/929, byte-identity de8be4d0c90c / 15038c19ddc8, width purity, MTP n3 0.75273. Keeps the
functional delivery kill-switches (GGML_CUDA_SPLICE_GATHER, GGML_CUDA_GCDBG, GGML_SCHED_STAGE*,
etc.). 521 lines removed.
Amended 2026-10-04 (issue ggml-org#59 closed; issue ggml-org#60, gfx1100): the qwen4exp prefill policy fix,
folded into block 15 and promoted to release v16-84e76d8a2-r34 from the gfx1100 candidate branch
wip/issues-59-60 (based on r27). Three parts:
- gate qsa3 off on RDNA3_0 by default (GGML_CUDA_QSA3=1 opts in, =0 force-off) and skip the
natural F16 K/V packs when the acting backend will not run the packed kernel. The model probes
the packed op through ggml_backend_dev_supports_op (qsa3_op_supported), so disabling qsa3 frees
its two full F16 cache copies as well; the RDNA3_5/RDNA4 defaults are unchanged. (ggml-org#59, reporter
confirmed.)
- keep the generic 4-head lightning-indexer prefill score supported on RDNA3_0 and make the
fused-vs-chain decision geometry-aware in build_qsa_top_k's use_wmma. Auto selects the fused op
on RDNA3_0 once the score exceeds LLAMA_QSA_SCORE_WMMA_MB (default 64 MiB; 0 = always fused) and
keeps the faster chain below it; on the reporter's r=4 geometry 64 MiB is n_kv about 64K, which
caps the chain's reserve before the 196K prefill's ceiling. The unfused chain's mul_mat+relu and
its chunked form now use ggml_relu_inplace, so the chain never holds the score and its relu at
once (bit-identical, and it removes the chain's 2x-score reserve peak). LLAMA_QSA_SCORE_WMMA=0/1
forces the chain/fused op. (ggml-org#60.)
- account for the FA prefill staging arena in llama_get_memory_breakdown / --fit, bounded by
min(2*GGML_CUDA_FA_STAGE_MAX_MB, F16 attention-KV size), so --fit no longer under-provisions a
deep prefill (issue ggml-org#33 follow-up).
Verified on the r27-based candidate on gfx1100 (ROCm 7.14): clean build; FLASH_ATTN_QSA 23/23
(26/26 with GGML_CUDA_QSA3=1), LIGHTNING_INDEXER 225/225, TOPK_QSA 4/4, FLASH_ATTN_EXT 6354/6354;
dense 27B same-seed 1acb04bd9104, byte-identical to r20. Re-folded onto r33 with no conflicts;
full record in wip/issues-59-60/ and WORKLOG.md 2026-10-04 (r34).
Amended 2026-10-05 (PR ggml-org#91, @briansp2020): BF16 hyper-connection hc_mix fusion (Flash-Next
GSQ-RCO). The ISTA-DASLab GSQ-RCO quants keep hc_{attn,ffn}_{down,up,inject} in BF16, and the
fused HC_MIX op was Q8_0-only, so those models ran the six-dispatch unfused chain (96 mixers per
token, a dispatch-bound decode). The op gains a BF16 arm that replays the unfused BF16 chain in
three dispatches with the same per-thread K order and reductions (bit-identical):
hc_mix_rms_gamma_quant without the quantize; the down rows and the inject rows in one grid
(mul_mat_vec_f<bf16,float,nt,256>); and the up rows of the four hc streams of one column plus the
gated collapse in one block (mul_mat_vec_f_vb<bf16,160,4> and dsv4_hc_pre_f32). The CUDA support
predicate requires hc_lr == 320 (the emulated mmvf block) and a GPU-resident buffer;
LLAMA_HC_MIX_BF16=0 keeps the chain. The CPU HC_MIX reference gained the matching BF16 arm and,
with the new BF16 test-backend-ops cases, exposed and fixed a pre-existing dst-stride bug for the
no-inject case at nt > 1 (the reference hard-coded the n_embd + hc row stride; it is n_embd
without a tail). Gates: test-backend-ops HC_MIX 30/30 (20 Q8_0 + 10 BF16) on gfx1201;
fused == unfused byte-identical for nt 1/3/5/8 on a BF16-hc Flash-Next fixture (+3.8 % tg256 on
the 4-layer fixture). Record: WORKLOG.md 2026-10-05 (r37), wip/rdna4-hc-mix-bf16/.
Amended 2026-10-06 (OPEN 1 / TODO ggml-org#42): the arena slot-count fix, the layer-uniform re-size, the MTP
draft cap default, and the cli-only wide-prefill drop.
- alloc_table_locked kept t.slots at the REQUESTED count after the r19 slot-count retry shrank the
arena, so a shrunk table advertised more slots than its arena held and the decode band read past
the allocation (silent corruption: `////` + MTP acceptance 0.007 on an over-filled arena). t.slots
is now the achieved count, and g_arena_bytes accounts the achieved count too.
- The arena is allocated per LAYER as a unit (alloc_all_locked): all of a layer's gate/up/down tables
get the SAME slot count, or an expert resident for one role is not resident for the others and the
shared remap names the wrong expert. A shortfall now re-sizes the whole layer down (largest expert
slice allocated first, retry at the achieved minimum) instead of shrinking one table; a final
non-uniform check disables the cache rather than risk a role mismatch.
- MTP draft compute-buffer cap default 512 (MTP_DRAFT_N_UBATCH=0 restores the target's -ub): the
draft's encoder-injection buffer is sized for its n_ubatch chunk, so at the target's full -ub it
held ~1.6 GiB/device that the MoE arena could use.
- The wide-prefill compute-layout drop (TODO ggml-org#42) is now default ON for llama-cli only
(common_params::drop_compute_buffers -> llama_context_params -> llama_cparams): llama-cli is a
single-wide-prefill workload, where the drop gives a large arena and meets the -ub 8192 decode DoD
(measured 78.7 t/s decode / 1683 t/s prefill at 16k, coherent, MTP acc 0.9245). llama-server
leaves it off: a later wide prefill needs a contiguous ~12.4-12.9 GB layout back and nothing the
arena can yield is large enough (-ub 4096 reclaims, -ub 8192 does not), so a server must not drop.
LLAMA_DROP_COMPUTE_BUFFERS overrides either default for A/B. The drop's extra arena reserve now
defaults to 0 (the compute-buffer margin covers the small post-drop growth;
LLAMA_DROP_EXTRA_RESERVE_MIB=N raises it). A non-uniform arena layer no longer corrupts: the
over-filled case degrades one layer to a uniform 3 slots and stays coherent (72.2 t/s).
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Oct 24, 2026
…b and cache engine) old-06 (generic MoE expert-cache iface, scheduler routed-expert rebalance, Meta delegation, the movable-boundary slab + allocator fail-soft, the host-expert pinned loader / --host-experts, the expert-cache engine, the h2d staging ring, GGML_ENV_STR) + old-09b (slab headroom) + old-11 (graph handling for expert-offload decode) + old-15's slab/cache extensions (narrow2, host pool, stage_gather, the fattn_stage arena accounting, the cache-aware mmvq/mmq reads and the try_fuse stand-down). The qwen4exp/HC and cache-blocks (cpy_batch) try_fuse arms are still stripped (they belong to 10 qwen4exp); the cache-aware arms present here are the slab/engine ones. Gates: build all OK; 35B-A3B -ncmoe 40 cache off == on (identical greedy text). Env-read hygiene (no behaviour change): resolve the environment variables this block adds on hot paths once into function-local statics instead of calling getenv() per alloc/reserve/ubatch -- GGML_SCHED_STAGE, LLAMA_DROP_COMPUTE_BUFFERS, GGML_CUDA_WORK_ALLOC_DEBUG, GGML_CUDA_CACHE_GEOM_DEBUG, GGML_CUDA_POOL_MIN_FREE_MIB, MOE_EXPERT_CACHE_VALIDATE_LAYER. Also make GGML_ENV_STR cache the value (std::string) rather than the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Prefill cache staging (r83): a whole-table staging copy of a host-resident expert table is now filled from the cache arena for the experts already resident and from the pinned host master for the rest, instead of re-uploading every expert over PCIe. The source map is a per-table "prefill residency snapshot": a small device copy of the authoritative host `expert_slot`, rebuilt whenever the cache writes (`g_write_seq`), the arena moves or the slot count changes, never mutated by decode, and not the removed device-remap policy. The destination is the ordinary staged table in expert order, so every consumer is unchanged and the bytes are identical. DEFAULT ON; kill switch `GGML_MOE_CACHE_STAGE=0` restores the plain whole-table upload. A table the slab stands down mid-prefill, an unpinned host master or a geometry mismatch declines and falls back to the plain upload. `moe_cache_report` prints the staged arena/host split. Measured (2x R9700 gfx1201, Qwen3.8-Flash-Next IQ4_NL 176.9B-A3B, `-sm tensor -ncmoe 48`, 32k ctx): prefill 1092 -> 1436 t/s (16k-token prompt, `-ub 4096`), 583 -> 839 (`-ub 2048`), 1181 -> 1585 (31.6k); `-sm layer` 742 -> 1269. Staged H2D falls to 27% of the table (arena 46.6 GiB, 71.9% residency). Greedy text byte-identical to r82; prefill-logit mean KLD 0 / same-top-p 100%. Slab drop reference (r85): the prefill -> decode drop recorded the work region it had just re-reserved as its "settled narrow" reference, but that re-reserve is the `n_rs_batch` shape, narrower than the real MTP decode/verify graph. Every following decode pass therefore looked "materially wider" and dropped again: measured one drop per decode step, 66 tables re-armed and ~3.65 GiB/device of arena evicted each time (decode 17-25 t/s instead of 45). The reference is now max(work region observed before the drop, shape the drop re-reserved). Fold (r86): beta 12, slab-transient-absorption (common half). The draft reserve is derived from the draft GGUF instead of assumed, the draft model is loaded before the target context so the slab measures its per-device footprint, and the common-layer and all-reduce transients are served by the slab. Coherence identical, prefill-logit KLD 0.000000 / same-top-p 100 %, adaptive-MTP 4 axes + phase probe exactly equal on the development box. Fold (r87): force the post-prefill drop on a wide -> narrow transition. r85 recorded `slab_narrow_boundary = max(re-reserved narrow, drop_observed)`, but at a prefill -> decode drop `drop_observed` is the WIDE prefill region, so an equally-wide second prefill compared equal and never dropped: the wide work buffer stayed allocated, the arena was not re-armed, and every request after the first decoded at ~half speed (Flash-Next IQ4_NL field config, 2 GPUs -sm tensor -ncmoe 46 -ub 6144 + MTP n6: 68.5 -> 35.7 t/s; with the fix 68.1 -> 69.4). Fold (r91): never auto-size the MoE expert arena on a shared host/device memory pool. On an integrated GPU (gfx1151/Strix Halo) the device "VRAM" window is the same physical pool as host RAM, so AUTO arena sizing and the movable-boundary slab (free - reserve) both map the machine: measured 121 GiB resident + 13 GiB swap, and bounding the arena alone hands the same overcommit to the slab. `moe_cache_preflight` now declines the cache on `prop.integrated`, keyed before any table registers, so the run is the documented host-expert path and the wrapper disarms the slab; `common/fit.cpp` stops reserving slab headroom + arena for such a device. Opt-in override `MOE_EXPERT_CACHE_UNIFIED=1` requires an explicit `MOE_EXPERT_CACHE_MIB` AND an explicit `GGML_CUDA_SLAB_RESERVE_MIB` (bounded by construction). A discrete GPU is untouched: gfx1201 35B-A3B `-ncmoe 40` loads with identical preflight/SLAB_INIT/arena lines; coherence and the prefill-logit gate are unchanged (guard == `MOE_EXPERT_CACHE_MIB=0`). Record: archive/work/umem-arena-guard/. Fold (r95): rdna3-verify-fusions (PR ggml-org#193, briansp2020): the batched f32 CPY run is admitted on RDNA3_0 as well (GGML_CUDA_CC_IS_RDNA3_0 alongside GGML_CUDA_CC_IS_RDNA4; RDNA3_5 stays out). One launch for up to 16 same-layout copies, element copies in ggml_cpy's flat order: bit-identical. The fusion is inactive where a split's concurrent events are live, and GGML_CUDA_FUSE_CPY_BATCH=0 still turns it off. Fold (r96, PR ggml-org#186, briansp2020): in `ggml_backend_sched_split_graph`, a second `MUL_MAT_ID` consumer of the expert weights the current split already stages starts a split of its own, so the re-registration path stages them again for that consumer's own routing. With both consumers in one split neither can be served by the expert cache (the arena holds one routing's slots) and the scheduler's guarded fast paths decline, so the whole table is copied for every such prompt chunk: qwen4exp's gathered logits tail next to its full-row MTP export tail meant the last layer's 1062 MiB table per chunk (Flash-Next `-sm tensor -ncmoe 10`: -30 % / -47 % TTFT on the follow-up turns, bit-identical text), and on `-sm layer` the second consumer read the arena slots staged for the first consumer's routing, which silently produced non-greedy-pure text with 0.00000 draft acceptance. `GGML_SCHED_MOE_DUP_SPLIT=0` restores the merged split (A/B and bisection). Fold (r96, PR ggml-org#189, briansp2020): the meta backend's `get_tensor_async` shares the synchronous read's split arithmetic instead of asserting `offset == 0` and one segment, so a caller can batch many per-device reads behind one synchronize (a context checkpoint's per-sequence cells). Calls that worked before issue the same copies as before. Fold (r99, TODO ggml-org#56): the scheduler must invoke the copy callback again, so the upstream `llama_moe_cache` (`--moe-cache-mib`) works. This block's rewrite of `ggml_backend_sched_copy_input` kept no `sched->callback_copy` call, and that call is the only thing in the tree that drives `llama_moe_cache::copy()`: the slot map stayed `0xff` (-1) while the graph had already swapped the routed op's `src0` for the cache bank and its ids for `GET_ROWS(slot_map, ids)`, so `MUL_MAT_ID` indexed the bank with -1 (wrong values where the page below the bank is mapped, an HSA page fault where it is not). The call is restored at base's position (after the wait-before-overwrite) and in the branch with no `MUL_MAT_ID` consumer, which is where the slot map lands (its consumer is a `GET_ROWS`); the delivery's own expert branch (device gather, cache take-over, pruning) is byte-for-byte unchanged, so no host expert table can reach the callback. `llama_context::sched_copy_experts` now answers only for the upstream cache: its per-op staging/pruning copy has been dead since this block's scheduler took that over, and would double-stage every host expert table if it ever ran again. Inert unless `--moe-cache-mib` is set (`moe_cache` is then null and the callback returns false). Gates (gfx1201, ROCm 10.1.0): `test-llama-archs -s 42` **375/375** (was 373/375; `deepseek2`'s `MoE cache` row 2.10e-10, the upstream base's own value, was 4.02e-03), also 375/375 with `GGML_CUDA_ASYNC_INPUT=0`; host-expert greedy text byte-identical to r98 (35B-A3B `-ncmoe 40`); prefill-logit KLD 0.000000 / 100.000 %. The upstream cache's large-batch `copy_experts()` arm stays unreached (this block's scheduler owns that pruning); values are identical either way, so it is a missing upstream optimisation on a path the delivery serves with its own cache, not a correctness gap. `--moe-cache-mib` is now correct but slower than `MOE_EXPERT_CACHE_MIB` on this box (decode 50.1 -> 37.8 t/s on 35B-A3B `-ncmoe 40`), so it stays documented as "works, not recommended". Split-state walk scratch (r100, issue ggml-org#184): the per-buffer-context split-state cache pre-warm walks the not-yet-cached ancestors on an explicit stack, and its wstack/wseen containers allocated one heap node per visited tensor (plus the rehash and the frees) on every graph re-allocation -- ~4.7k split states and ~150k tensors per re-allocation in the reporter's 4-stream workload, where 94% of the mallocs under ggml_gallocr_alloc_graph came from that set. Both containers now use a reused per-thread monotonic_buffer_resource (1 MiB, released per walk); only the outermost call walks, so the resource is never re-entered, the walk visits the same tensors in the same order and computes the same states, and an exhausted arena falls back to the upstream allocator. GGML_META_SS_SCRATCH=0 restores the heap containers (A/B only). Second-scheduler slot for DFlash/DFlash2 drafts (issue ggml-org#208): the draft context's second scheduler (LLAMA_DRAFT_SCHED2) was selected with `n_outputs > 0`. That fits MTP (a no-output ingest graph and a draft step with an output) but not a DFlash2 draft block, which has no outputs either: its lattice is read from the nextn embeddings, not from logits (`output = !is_dflash2`). The KV injection and the noise-block draft step therefore shared one scheduler AND one `gf_res_prev` slot, so they overwrote each other's graph every cycle and the draft context rebuilt and re-allocated both of them on every verify step (measured 0 of 362 draft ubatches reused). `sched_alt_for()` now selects the slot from the batch kind for LLM_ARCH_DFLASH -- the injection is the batch that carries the target features (host embd rows, or the F1 device injection whose token ids are target rows), the draft step is the token batch -- and keeps `n_outputs` for every other arch, where the batch kind would merge MTP's ingest and step graphs instead of separating them. `get_gf_res_prev()` takes the same decision, so the scheduler and the graph-reuse slot cannot disagree. Measured (gfx1201, 512 greedy tokens, `prompts/prose-rdna-boosts.txt`): draft graph reuse 0 -> 97.8 % (dense 27B UD-Q4_K_XL 2 GPU tensor) and 97.9 % (35B-A3B Q4_K_M `-ncmoe 40`); decode +1.4 % (27B 2 GPU), +1.8 % (27B 3 GPU), +4.0 % (35B-A3B host experts), +1.3 % (host injection, GGML_LF_DFLASH_DEV=0), +0.5 % (27B `-sm layer`), +0.2 % (27B 1 GPU); a 2-slot unified server with two concurrent requests is identical per slot (text, acceptance 0.66894 / 0.73801) at +1.0 / +1.9 %. Generated text is byte-identical in every arm, the dense 4B coherence hash is unchanged, and the adaptive-MTP four-axis gate (27B, `-n 3000`, reasoning pinned per axis) is identical to the pre-fix build on all four axes (t/s, acceptance and text). `LLAMA_DRAFT_SCHED2=0` reproduces the old behaviour exactly. Per-block build (blocks own their code): the identity-preference layer-drop ranking (r117) called `heat_rank_vec()`, which block 12 introduces with the band-split heat prior (r114), so block 09 alone did not compile (`use of undeclared identifier 'heat_rank_vec'`) since r117. This block now ranks by `t.heat`, which is byte-identical in this tree (there is no decode counter yet), and block 12 switches this site over along with the two it already owns. `gate-per-block-build.sh` selects block 09 again. Verify-width band clamp (TODO ggml-org#59, ngram-mod x host experts): the expert cache serves a routed `MUL_MAT_ID` from its arena only up to its decode/verify band (`moe_cache_max_tok_dev()`: 16 tokens on RDNA4, 8 on RDNA3/NVIDIA). A WIDER batch leaves the arena entirely -- `moe_cache_update_host()` returns false above the band, so the routed experts are streamed from the pinned host master on every step. A speculative verify batch is `n_draft + 1` rows, and while the MTP/draft family is bounded to 15 (i.e. 16 rows) by `LLAMA_SPEC_DRAFT_N_MAX_CLAMP`, the DRAFTLESS n-gram speculators have no width bound at all: `ngram_mod.n_max` defaults to 64 (`n_min` 48), the ngram-map family's `size_m` to 48. On a host-expert config the README's own `draft-mtp-adaptive,ngram-mod` recommendation therefore put every ngram step outside the band, which is the "ngram-mod halves decode with host-resident experts" report (TODO ggml-org#59). Measured (2x R9700 gfx1201, Flash-Next IQ4_NL + MTP head, `-sm tensor -ncmoe 36`, `-c 16384`, `prompts/recall.txt`, `-n 2000 --temp 0 --seed 42`): sweeping `--spec-ngram-mod-n-max` gives 154.8 t/s at 12 (13-row verify), 159.2 t/s at 15 (16 rows, in band), **55.0 t/s at 16 (17 rows -- one extra row, -65 %)**, 58.1-58.3 at 20/24, 48.1 at 32; the arena hit rate drops 0.978 -> 0.898 and the cache's counted `reaches` collapse 1086540 -> 129660 (the wide steps never reach the arena). The README combo measures 73.9 t/s uncapped against **168.3 t/s** at a 15-token draft. Controls: fully device-resident (3 GPU, `-ncmoe 0`) 144.7 (MTP n3) -> 378.7 (ngram default) vs 244.6 capped -- there the wide draft is the win; the CPU expert path (`MOE_EXPERT_CACHE_MIB=0`) 38.5 -> 67.6 (wide) vs 52.2 capped -- upstream's shape and the reason the reporter's config in issue ggml-org#214 was fine there. The fix is a new `moe_cache_band` device query (appended to `ggml_backend_device_i`, zero-initialized for backends that do not set it; CUDA answers `moe_cache_enabled() ? moe_cache_max_tok_dev(device) : 0`), `llama_model_moe_cache_band()` (the smallest band across the model's host-expert devices), and `common_speculative_clamp_ngram_n_max()`: `common_init_from_params` clamps an ENABLED n-gram speculator's draft length to `band - 1` once the model (and therefore the preflight's decision) is known, lowering `n_min` with it (ngram-mod discards a draft shorter than `n_min`, so a naked `n_max` clamp would silently disable it), and refreshes `cparams.n_rs_batch` so the slab's narrow verify floor and the chunked-GDN rollback bound see the capped depth (the uncapped default also cost ~5 GiB of arena: 32938 -> 27814 MiB). `LLAMA_SPEC_NGRAM_MOD_BAND_CLAMP=0` restores the uncapped draft. A model with no active arena reports band 0 and is never clamped; a `draft.n_max` above the band is warned about, not clamped (the 15 bound is a correctness one and matches RDNA4's band). Gates: prefilled-text purity with `ROCBLAS_USE_HIPBLASLT=0` (per the delivery's fresh-process rule) -- `plain` / `draft-mtp n3` / `ngram-mod` hand-capped / `ngram-mod` auto-clamped all hash identically (1793 chars, sha 9d914f47aebb) on the host-expert cell, the same hashes the pre-amend build produced; `LLAMA_SPEC_NGRAM_MOD_BAND_CLAMP=0` reproduces 74.1 t/s exactly; the device-resident and CPU-expert controls are unchanged (380.2 and 68.1 t/s, no clamp line). The clamp never touches a non-ngram config (the MTP-only arms log no clamp). Record: `wip/ngram-mod-host-experts/EVIDENCE-2026-10-24.md`.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Oct 24, 2026
…b and cache engine) old-06 (generic MoE expert-cache iface, scheduler routed-expert rebalance, Meta delegation, the movable-boundary slab + allocator fail-soft, the host-expert pinned loader / --host-experts, the expert-cache engine, the h2d staging ring, GGML_ENV_STR) + old-09b (slab headroom) + old-11 (graph handling for expert-offload decode) + old-15's slab/cache extensions (narrow2, host pool, stage_gather, the fattn_stage arena accounting, the cache-aware mmvq/mmq reads and the try_fuse stand-down). The qwen4exp/HC and cache-blocks (cpy_batch) try_fuse arms are still stripped (they belong to 10 qwen4exp); the cache-aware arms present here are the slab/engine ones. Gates: build all OK; 35B-A3B -ncmoe 40 cache off == on (identical greedy text). Env-read hygiene (no behaviour change): resolve the environment variables this block adds on hot paths once into function-local statics instead of calling getenv() per alloc/reserve/ubatch -- GGML_SCHED_STAGE, LLAMA_DROP_COMPUTE_BUFFERS, GGML_CUDA_WORK_ALLOC_DEBUG, GGML_CUDA_CACHE_GEOM_DEBUG, GGML_CUDA_POOL_MIN_FREE_MIB, MOE_EXPERT_CACHE_VALIDATE_LAYER. Also make GGML_ENV_STR cache the value (std::string) rather than the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Prefill cache staging (r83): a whole-table staging copy of a host-resident expert table is now filled from the cache arena for the experts already resident and from the pinned host master for the rest, instead of re-uploading every expert over PCIe. The source map is a per-table "prefill residency snapshot": a small device copy of the authoritative host `expert_slot`, rebuilt whenever the cache writes (`g_write_seq`), the arena moves or the slot count changes, never mutated by decode, and not the removed device-remap policy. The destination is the ordinary staged table in expert order, so every consumer is unchanged and the bytes are identical. DEFAULT ON; kill switch `GGML_MOE_CACHE_STAGE=0` restores the plain whole-table upload. A table the slab stands down mid-prefill, an unpinned host master or a geometry mismatch declines and falls back to the plain upload. `moe_cache_report` prints the staged arena/host split. Measured (2x R9700 gfx1201, Qwen3.8-Flash-Next IQ4_NL 176.9B-A3B, `-sm tensor -ncmoe 48`, 32k ctx): prefill 1092 -> 1436 t/s (16k-token prompt, `-ub 4096`), 583 -> 839 (`-ub 2048`), 1181 -> 1585 (31.6k); `-sm layer` 742 -> 1269. Staged H2D falls to 27% of the table (arena 46.6 GiB, 71.9% residency). Greedy text byte-identical to r82; prefill-logit mean KLD 0 / same-top-p 100%. Slab drop reference (r85): the prefill -> decode drop recorded the work region it had just re-reserved as its "settled narrow" reference, but that re-reserve is the `n_rs_batch` shape, narrower than the real MTP decode/verify graph. Every following decode pass therefore looked "materially wider" and dropped again: measured one drop per decode step, 66 tables re-armed and ~3.65 GiB/device of arena evicted each time (decode 17-25 t/s instead of 45). The reference is now max(work region observed before the drop, shape the drop re-reserved). Fold (r86): beta 12, slab-transient-absorption (common half). The draft reserve is derived from the draft GGUF instead of assumed, the draft model is loaded before the target context so the slab measures its per-device footprint, and the common-layer and all-reduce transients are served by the slab. Coherence identical, prefill-logit KLD 0.000000 / same-top-p 100 %, adaptive-MTP 4 axes + phase probe exactly equal on the development box. Fold (r87): force the post-prefill drop on a wide -> narrow transition. r85 recorded `slab_narrow_boundary = max(re-reserved narrow, drop_observed)`, but at a prefill -> decode drop `drop_observed` is the WIDE prefill region, so an equally-wide second prefill compared equal and never dropped: the wide work buffer stayed allocated, the arena was not re-armed, and every request after the first decoded at ~half speed (Flash-Next IQ4_NL field config, 2 GPUs -sm tensor -ncmoe 46 -ub 6144 + MTP n6: 68.5 -> 35.7 t/s; with the fix 68.1 -> 69.4). Fold (r91): never auto-size the MoE expert arena on a shared host/device memory pool. On an integrated GPU (gfx1151/Strix Halo) the device "VRAM" window is the same physical pool as host RAM, so AUTO arena sizing and the movable-boundary slab (free - reserve) both map the machine: measured 121 GiB resident + 13 GiB swap, and bounding the arena alone hands the same overcommit to the slab. `moe_cache_preflight` now declines the cache on `prop.integrated`, keyed before any table registers, so the run is the documented host-expert path and the wrapper disarms the slab; `common/fit.cpp` stops reserving slab headroom + arena for such a device. Opt-in override `MOE_EXPERT_CACHE_UNIFIED=1` requires an explicit `MOE_EXPERT_CACHE_MIB` AND an explicit `GGML_CUDA_SLAB_RESERVE_MIB` (bounded by construction). A discrete GPU is untouched: gfx1201 35B-A3B `-ncmoe 40` loads with identical preflight/SLAB_INIT/arena lines; coherence and the prefill-logit gate are unchanged (guard == `MOE_EXPERT_CACHE_MIB=0`). Record: archive/work/umem-arena-guard/. Fold (r95): rdna3-verify-fusions (PR ggml-org#193, briansp2020): the batched f32 CPY run is admitted on RDNA3_0 as well (GGML_CUDA_CC_IS_RDNA3_0 alongside GGML_CUDA_CC_IS_RDNA4; RDNA3_5 stays out). One launch for up to 16 same-layout copies, element copies in ggml_cpy's flat order: bit-identical. The fusion is inactive where a split's concurrent events are live, and GGML_CUDA_FUSE_CPY_BATCH=0 still turns it off. Fold (r96, PR ggml-org#186, briansp2020): in `ggml_backend_sched_split_graph`, a second `MUL_MAT_ID` consumer of the expert weights the current split already stages starts a split of its own, so the re-registration path stages them again for that consumer's own routing. With both consumers in one split neither can be served by the expert cache (the arena holds one routing's slots) and the scheduler's guarded fast paths decline, so the whole table is copied for every such prompt chunk: qwen4exp's gathered logits tail next to its full-row MTP export tail meant the last layer's 1062 MiB table per chunk (Flash-Next `-sm tensor -ncmoe 10`: -30 % / -47 % TTFT on the follow-up turns, bit-identical text), and on `-sm layer` the second consumer read the arena slots staged for the first consumer's routing, which silently produced non-greedy-pure text with 0.00000 draft acceptance. `GGML_SCHED_MOE_DUP_SPLIT=0` restores the merged split (A/B and bisection). Fold (r96, PR ggml-org#189, briansp2020): the meta backend's `get_tensor_async` shares the synchronous read's split arithmetic instead of asserting `offset == 0` and one segment, so a caller can batch many per-device reads behind one synchronize (a context checkpoint's per-sequence cells). Calls that worked before issue the same copies as before. Fold (r99, TODO ggml-org#56): the scheduler must invoke the copy callback again, so the upstream `llama_moe_cache` (`--moe-cache-mib`) works. This block's rewrite of `ggml_backend_sched_copy_input` kept no `sched->callback_copy` call, and that call is the only thing in the tree that drives `llama_moe_cache::copy()`: the slot map stayed `0xff` (-1) while the graph had already swapped the routed op's `src0` for the cache bank and its ids for `GET_ROWS(slot_map, ids)`, so `MUL_MAT_ID` indexed the bank with -1 (wrong values where the page below the bank is mapped, an HSA page fault where it is not). The call is restored at base's position (after the wait-before-overwrite) and in the branch with no `MUL_MAT_ID` consumer, which is where the slot map lands (its consumer is a `GET_ROWS`); the delivery's own expert branch (device gather, cache take-over, pruning) is byte-for-byte unchanged, so no host expert table can reach the callback. `llama_context::sched_copy_experts` now answers only for the upstream cache: its per-op staging/pruning copy has been dead since this block's scheduler took that over, and would double-stage every host expert table if it ever ran again. Inert unless `--moe-cache-mib` is set (`moe_cache` is then null and the callback returns false). Gates (gfx1201, ROCm 10.1.0): `test-llama-archs -s 42` **375/375** (was 373/375; `deepseek2`'s `MoE cache` row 2.10e-10, the upstream base's own value, was 4.02e-03), also 375/375 with `GGML_CUDA_ASYNC_INPUT=0`; host-expert greedy text byte-identical to r98 (35B-A3B `-ncmoe 40`); prefill-logit KLD 0.000000 / 100.000 %. The upstream cache's large-batch `copy_experts()` arm stays unreached (this block's scheduler owns that pruning); values are identical either way, so it is a missing upstream optimisation on a path the delivery serves with its own cache, not a correctness gap. `--moe-cache-mib` is now correct but slower than `MOE_EXPERT_CACHE_MIB` on this box (decode 50.1 -> 37.8 t/s on 35B-A3B `-ncmoe 40`), so it stays documented as "works, not recommended". Split-state walk scratch (r100, issue ggml-org#184): the per-buffer-context split-state cache pre-warm walks the not-yet-cached ancestors on an explicit stack, and its wstack/wseen containers allocated one heap node per visited tensor (plus the rehash and the frees) on every graph re-allocation -- ~4.7k split states and ~150k tensors per re-allocation in the reporter's 4-stream workload, where 94% of the mallocs under ggml_gallocr_alloc_graph came from that set. Both containers now use a reused per-thread monotonic_buffer_resource (1 MiB, released per walk); only the outermost call walks, so the resource is never re-entered, the walk visits the same tensors in the same order and computes the same states, and an exhausted arena falls back to the upstream allocator. GGML_META_SS_SCRATCH=0 restores the heap containers (A/B only). Second-scheduler slot for DFlash/DFlash2 drafts (issue ggml-org#208): the draft context's second scheduler (LLAMA_DRAFT_SCHED2) was selected with `n_outputs > 0`. That fits MTP (a no-output ingest graph and a draft step with an output) but not a DFlash2 draft block, which has no outputs either: its lattice is read from the nextn embeddings, not from logits (`output = !is_dflash2`). The KV injection and the noise-block draft step therefore shared one scheduler AND one `gf_res_prev` slot, so they overwrote each other's graph every cycle and the draft context rebuilt and re-allocated both of them on every verify step (measured 0 of 362 draft ubatches reused). `sched_alt_for()` now selects the slot from the batch kind for LLM_ARCH_DFLASH -- the injection is the batch that carries the target features (host embd rows, or the F1 device injection whose token ids are target rows), the draft step is the token batch -- and keeps `n_outputs` for every other arch, where the batch kind would merge MTP's ingest and step graphs instead of separating them. `get_gf_res_prev()` takes the same decision, so the scheduler and the graph-reuse slot cannot disagree. Measured (gfx1201, 512 greedy tokens, `prompts/prose-rdna-boosts.txt`): draft graph reuse 0 -> 97.8 % (dense 27B UD-Q4_K_XL 2 GPU tensor) and 97.9 % (35B-A3B Q4_K_M `-ncmoe 40`); decode +1.4 % (27B 2 GPU), +1.8 % (27B 3 GPU), +4.0 % (35B-A3B host experts), +1.3 % (host injection, GGML_LF_DFLASH_DEV=0), +0.5 % (27B `-sm layer`), +0.2 % (27B 1 GPU); a 2-slot unified server with two concurrent requests is identical per slot (text, acceptance 0.66894 / 0.73801) at +1.0 / +1.9 %. Generated text is byte-identical in every arm, the dense 4B coherence hash is unchanged, and the adaptive-MTP four-axis gate (27B, `-n 3000`, reasoning pinned per axis) is identical to the pre-fix build on all four axes (t/s, acceptance and text). `LLAMA_DRAFT_SCHED2=0` reproduces the old behaviour exactly. Per-block build (blocks own their code): the identity-preference layer-drop ranking (r117) called `heat_rank_vec()`, which block 12 introduces with the band-split heat prior (r114), so block 09 alone did not compile (`use of undeclared identifier 'heat_rank_vec'`) since r117. This block now ranks by `t.heat`, which is byte-identical in this tree (there is no decode counter yet), and block 12 switches this site over along with the two it already owns. `gate-per-block-build.sh` selects block 09 again. Verify-width band clamp (TODO ggml-org#59, ngram-mod x host experts): the expert cache serves a routed `MUL_MAT_ID` from its arena only up to its decode/verify band (`moe_cache_max_tok_dev()`: 16 tokens on RDNA4, 8 on RDNA3/NVIDIA). A WIDER batch leaves the arena entirely -- `moe_cache_update_host()` returns false above the band, so the routed experts are streamed from the pinned host master on every step. A speculative verify batch is `n_draft + 1` rows, and while the MTP/draft family is bounded to 15 (i.e. 16 rows) by `LLAMA_SPEC_DRAFT_N_MAX_CLAMP`, the DRAFTLESS n-gram speculators have no width bound at all: `ngram_mod.n_max` defaults to 64 (`n_min` 48), the ngram-map family's `size_m` to 48. On a host-expert config the README's own `draft-mtp-adaptive,ngram-mod` recommendation therefore put every ngram step outside the band, which is the "ngram-mod halves decode with host-resident experts" report (TODO ggml-org#59). Measured (2x R9700 gfx1201, Flash-Next IQ4_NL + MTP head, `-sm tensor -ncmoe 36`, `-c 16384`, `prompts/recall.txt`, `-n 2000 --temp 0 --seed 42`): sweeping `--spec-ngram-mod-n-max` gives 154.8 t/s at 12 (13-row verify), 159.2 t/s at 15 (16 rows, in band), **55.0 t/s at 16 (17 rows -- one extra row, -65 %)**, 58.1-58.3 at 20/24, 48.1 at 32; the arena hit rate drops 0.978 -> 0.898 and the cache's counted `reaches` collapse 1086540 -> 129660 (the wide steps never reach the arena). The README combo measures 73.9 t/s uncapped against **168.3 t/s** at a 15-token draft. Controls: fully device-resident (3 GPU, `-ncmoe 0`) 144.7 (MTP n3) -> 378.7 (ngram default) vs 244.6 capped -- there the wide draft is the win; the CPU expert path (`MOE_EXPERT_CACHE_MIB=0`) 38.5 -> 67.6 (wide) vs 52.2 capped -- upstream's shape and the reason the reporter's config in issue ggml-org#214 was fine there. The fix is a new `moe_cache_band` device query (appended to `ggml_backend_device_i`, zero-initialized for backends that do not set it; CUDA answers `moe_cache_enabled() ? moe_cache_max_tok_dev(device) : 0`), `llama_model_moe_cache_band()` (the smallest band across the model's host-expert devices), and `common_speculative_clamp_ngram_n_max()`: `common_init_from_params` clamps an ENABLED n-gram speculator's draft length to `band - 1` once the model (and therefore the preflight's decision) is known, lowering `n_min` with it (ngram-mod discards a draft shorter than `n_min`, so a naked `n_max` clamp would silently disable it), and refreshes `cparams.n_rs_batch` so the slab's narrow verify floor and the chunked-GDN rollback bound see the capped depth (the uncapped default also cost ~5 GiB of arena: 32938 -> 27814 MiB). `LLAMA_SPEC_NGRAM_MOD_BAND_CLAMP=0` restores the uncapped draft. A model with no active arena reports band 0 and is never clamped; a `draft.n_max` above the band is warned about, not clamped (the 15 bound is a correctness one and matches RDNA4's band). Gates: prefilled-text purity with `ROCBLAS_USE_HIPBLASLT=0` (per the delivery's fresh-process rule) -- `plain` / `draft-mtp n3` / `ngram-mod` hand-capped / `ngram-mod` auto-clamped all hash identically (1793 chars, sha 9d914f47aebb) on the host-expert cell, the same hashes the pre-amend build produced; `LLAMA_SPEC_NGRAM_MOD_BAND_CLAMP=0` reproduces 74.1 t/s exactly; the device-resident and CPU-expert controls are unchanged (380.2 and 68.1 t/s, no clamp line). The clamp never touches a non-ngram config (the MTP-only arms log no clamp). Record: `wip/ngram-mod-host-experts/EVIDENCE-2026-10-24.md`. Windows HIP build (issue ggml-org#217): the three `std::min`/`std::max` calls on int64_t in moe-expert-cache.cu (the sizing slack guard, the auto-arena floor and the heat-coverage bound) are replaced with two local ternary helpers. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (int64_t is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged: greedy text is byte-identical on the dense 4B (`-sm tensor`, 3 GPU) and the host-expert arm (35B-A3B `-ncmoe 40`), prefill-logit mean KLD 0.000000 / same-top-p 100.000 %, MTP acceptance 0.73881.
stew675
pushed a commit
to stew675/llama.cpp
that referenced
this pull request
Oct 24, 2026
…b and cache engine) old-06 (generic MoE expert-cache iface, scheduler routed-expert rebalance, Meta delegation, the movable-boundary slab + allocator fail-soft, the host-expert pinned loader / --host-experts, the expert-cache engine, the h2d staging ring, GGML_ENV_STR) + old-09b (slab headroom) + old-11 (graph handling for expert-offload decode) + old-15's slab/cache extensions (narrow2, host pool, stage_gather, the fattn_stage arena accounting, the cache-aware mmvq/mmq reads and the try_fuse stand-down). The qwen4exp/HC and cache-blocks (cpy_batch) try_fuse arms are still stripped (they belong to 10 qwen4exp); the cache-aware arms present here are the slab/engine ones. Gates: build all OK; 35B-A3B -ncmoe 40 cache off == on (identical greedy text). Env-read hygiene (no behaviour change): resolve the environment variables this block adds on hot paths once into function-local statics instead of calling getenv() per alloc/reserve/ubatch -- GGML_SCHED_STAGE, LLAMA_DROP_COMPUTE_BUFFERS, GGML_CUDA_WORK_ALLOC_DEBUG, GGML_CUDA_CACHE_GEOM_DEBUG, GGML_CUDA_POOL_MIN_FREE_MIB, MOE_EXPERT_CACHE_VALIDATE_LAYER. Also make GGML_ENV_STR cache the value (std::string) rather than the getenv() pointer: the MSVC CRT returns a buffer that the next getenv() call overwrites, so a cached pointer is unsafe on Windows. Prefill cache staging (r83): a whole-table staging copy of a host-resident expert table is now filled from the cache arena for the experts already resident and from the pinned host master for the rest, instead of re-uploading every expert over PCIe. The source map is a per-table "prefill residency snapshot": a small device copy of the authoritative host `expert_slot`, rebuilt whenever the cache writes (`g_write_seq`), the arena moves or the slot count changes, never mutated by decode, and not the removed device-remap policy. The destination is the ordinary staged table in expert order, so every consumer is unchanged and the bytes are identical. DEFAULT ON; kill switch `GGML_MOE_CACHE_STAGE=0` restores the plain whole-table upload. A table the slab stands down mid-prefill, an unpinned host master or a geometry mismatch declines and falls back to the plain upload. `moe_cache_report` prints the staged arena/host split. Measured (2x R9700 gfx1201, Qwen3.8-Flash-Next IQ4_NL 176.9B-A3B, `-sm tensor -ncmoe 48`, 32k ctx): prefill 1092 -> 1436 t/s (16k-token prompt, `-ub 4096`), 583 -> 839 (`-ub 2048`), 1181 -> 1585 (31.6k); `-sm layer` 742 -> 1269. Staged H2D falls to 27% of the table (arena 46.6 GiB, 71.9% residency). Greedy text byte-identical to r82; prefill-logit mean KLD 0 / same-top-p 100%. Slab drop reference (r85): the prefill -> decode drop recorded the work region it had just re-reserved as its "settled narrow" reference, but that re-reserve is the `n_rs_batch` shape, narrower than the real MTP decode/verify graph. Every following decode pass therefore looked "materially wider" and dropped again: measured one drop per decode step, 66 tables re-armed and ~3.65 GiB/device of arena evicted each time (decode 17-25 t/s instead of 45). The reference is now max(work region observed before the drop, shape the drop re-reserved). Fold (r86): beta 12, slab-transient-absorption (common half). The draft reserve is derived from the draft GGUF instead of assumed, the draft model is loaded before the target context so the slab measures its per-device footprint, and the common-layer and all-reduce transients are served by the slab. Coherence identical, prefill-logit KLD 0.000000 / same-top-p 100 %, adaptive-MTP 4 axes + phase probe exactly equal on the development box. Fold (r87): force the post-prefill drop on a wide -> narrow transition. r85 recorded `slab_narrow_boundary = max(re-reserved narrow, drop_observed)`, but at a prefill -> decode drop `drop_observed` is the WIDE prefill region, so an equally-wide second prefill compared equal and never dropped: the wide work buffer stayed allocated, the arena was not re-armed, and every request after the first decoded at ~half speed (Flash-Next IQ4_NL field config, 2 GPUs -sm tensor -ncmoe 46 -ub 6144 + MTP n6: 68.5 -> 35.7 t/s; with the fix 68.1 -> 69.4). Fold (r91): never auto-size the MoE expert arena on a shared host/device memory pool. On an integrated GPU (gfx1151/Strix Halo) the device "VRAM" window is the same physical pool as host RAM, so AUTO arena sizing and the movable-boundary slab (free - reserve) both map the machine: measured 121 GiB resident + 13 GiB swap, and bounding the arena alone hands the same overcommit to the slab. `moe_cache_preflight` now declines the cache on `prop.integrated`, keyed before any table registers, so the run is the documented host-expert path and the wrapper disarms the slab; `common/fit.cpp` stops reserving slab headroom + arena for such a device. Opt-in override `MOE_EXPERT_CACHE_UNIFIED=1` requires an explicit `MOE_EXPERT_CACHE_MIB` AND an explicit `GGML_CUDA_SLAB_RESERVE_MIB` (bounded by construction). A discrete GPU is untouched: gfx1201 35B-A3B `-ncmoe 40` loads with identical preflight/SLAB_INIT/arena lines; coherence and the prefill-logit gate are unchanged (guard == `MOE_EXPERT_CACHE_MIB=0`). Record: archive/work/umem-arena-guard/. Fold (r95): rdna3-verify-fusions (PR ggml-org#193, briansp2020): the batched f32 CPY run is admitted on RDNA3_0 as well (GGML_CUDA_CC_IS_RDNA3_0 alongside GGML_CUDA_CC_IS_RDNA4; RDNA3_5 stays out). One launch for up to 16 same-layout copies, element copies in ggml_cpy's flat order: bit-identical. The fusion is inactive where a split's concurrent events are live, and GGML_CUDA_FUSE_CPY_BATCH=0 still turns it off. Fold (r96, PR ggml-org#186, briansp2020): in `ggml_backend_sched_split_graph`, a second `MUL_MAT_ID` consumer of the expert weights the current split already stages starts a split of its own, so the re-registration path stages them again for that consumer's own routing. With both consumers in one split neither can be served by the expert cache (the arena holds one routing's slots) and the scheduler's guarded fast paths decline, so the whole table is copied for every such prompt chunk: qwen4exp's gathered logits tail next to its full-row MTP export tail meant the last layer's 1062 MiB table per chunk (Flash-Next `-sm tensor -ncmoe 10`: -30 % / -47 % TTFT on the follow-up turns, bit-identical text), and on `-sm layer` the second consumer read the arena slots staged for the first consumer's routing, which silently produced non-greedy-pure text with 0.00000 draft acceptance. `GGML_SCHED_MOE_DUP_SPLIT=0` restores the merged split (A/B and bisection). Fold (r96, PR ggml-org#189, briansp2020): the meta backend's `get_tensor_async` shares the synchronous read's split arithmetic instead of asserting `offset == 0` and one segment, so a caller can batch many per-device reads behind one synchronize (a context checkpoint's per-sequence cells). Calls that worked before issue the same copies as before. Fold (r99, TODO ggml-org#56): the scheduler must invoke the copy callback again, so the upstream `llama_moe_cache` (`--moe-cache-mib`) works. This block's rewrite of `ggml_backend_sched_copy_input` kept no `sched->callback_copy` call, and that call is the only thing in the tree that drives `llama_moe_cache::copy()`: the slot map stayed `0xff` (-1) while the graph had already swapped the routed op's `src0` for the cache bank and its ids for `GET_ROWS(slot_map, ids)`, so `MUL_MAT_ID` indexed the bank with -1 (wrong values where the page below the bank is mapped, an HSA page fault where it is not). The call is restored at base's position (after the wait-before-overwrite) and in the branch with no `MUL_MAT_ID` consumer, which is where the slot map lands (its consumer is a `GET_ROWS`); the delivery's own expert branch (device gather, cache take-over, pruning) is byte-for-byte unchanged, so no host expert table can reach the callback. `llama_context::sched_copy_experts` now answers only for the upstream cache: its per-op staging/pruning copy has been dead since this block's scheduler took that over, and would double-stage every host expert table if it ever ran again. Inert unless `--moe-cache-mib` is set (`moe_cache` is then null and the callback returns false). Gates (gfx1201, ROCm 10.1.0): `test-llama-archs -s 42` **375/375** (was 373/375; `deepseek2`'s `MoE cache` row 2.10e-10, the upstream base's own value, was 4.02e-03), also 375/375 with `GGML_CUDA_ASYNC_INPUT=0`; host-expert greedy text byte-identical to r98 (35B-A3B `-ncmoe 40`); prefill-logit KLD 0.000000 / 100.000 %. The upstream cache's large-batch `copy_experts()` arm stays unreached (this block's scheduler owns that pruning); values are identical either way, so it is a missing upstream optimisation on a path the delivery serves with its own cache, not a correctness gap. `--moe-cache-mib` is now correct but slower than `MOE_EXPERT_CACHE_MIB` on this box (decode 50.1 -> 37.8 t/s on 35B-A3B `-ncmoe 40`), so it stays documented as "works, not recommended". Split-state walk scratch (r100, issue ggml-org#184): the per-buffer-context split-state cache pre-warm walks the not-yet-cached ancestors on an explicit stack, and its wstack/wseen containers allocated one heap node per visited tensor (plus the rehash and the frees) on every graph re-allocation -- ~4.7k split states and ~150k tensors per re-allocation in the reporter's 4-stream workload, where 94% of the mallocs under ggml_gallocr_alloc_graph came from that set. Both containers now use a reused per-thread monotonic_buffer_resource (1 MiB, released per walk); only the outermost call walks, so the resource is never re-entered, the walk visits the same tensors in the same order and computes the same states, and an exhausted arena falls back to the upstream allocator. GGML_META_SS_SCRATCH=0 restores the heap containers (A/B only). Second-scheduler slot for DFlash/DFlash2 drafts (issue ggml-org#208): the draft context's second scheduler (LLAMA_DRAFT_SCHED2) was selected with `n_outputs > 0`. That fits MTP (a no-output ingest graph and a draft step with an output) but not a DFlash2 draft block, which has no outputs either: its lattice is read from the nextn embeddings, not from logits (`output = !is_dflash2`). The KV injection and the noise-block draft step therefore shared one scheduler AND one `gf_res_prev` slot, so they overwrote each other's graph every cycle and the draft context rebuilt and re-allocated both of them on every verify step (measured 0 of 362 draft ubatches reused). `sched_alt_for()` now selects the slot from the batch kind for LLM_ARCH_DFLASH -- the injection is the batch that carries the target features (host embd rows, or the F1 device injection whose token ids are target rows), the draft step is the token batch -- and keeps `n_outputs` for every other arch, where the batch kind would merge MTP's ingest and step graphs instead of separating them. `get_gf_res_prev()` takes the same decision, so the scheduler and the graph-reuse slot cannot disagree. Measured (gfx1201, 512 greedy tokens, `prompts/prose-rdna-boosts.txt`): draft graph reuse 0 -> 97.8 % (dense 27B UD-Q4_K_XL 2 GPU tensor) and 97.9 % (35B-A3B Q4_K_M `-ncmoe 40`); decode +1.4 % (27B 2 GPU), +1.8 % (27B 3 GPU), +4.0 % (35B-A3B host experts), +1.3 % (host injection, GGML_LF_DFLASH_DEV=0), +0.5 % (27B `-sm layer`), +0.2 % (27B 1 GPU); a 2-slot unified server with two concurrent requests is identical per slot (text, acceptance 0.66894 / 0.73801) at +1.0 / +1.9 %. Generated text is byte-identical in every arm, the dense 4B coherence hash is unchanged, and the adaptive-MTP four-axis gate (27B, `-n 3000`, reasoning pinned per axis) is identical to the pre-fix build on all four axes (t/s, acceptance and text). `LLAMA_DRAFT_SCHED2=0` reproduces the old behaviour exactly. Per-block build (blocks own their code): the identity-preference layer-drop ranking (r117) called `heat_rank_vec()`, which block 12 introduces with the band-split heat prior (r114), so block 09 alone did not compile (`use of undeclared identifier 'heat_rank_vec'`) since r117. This block now ranks by `t.heat`, which is byte-identical in this tree (there is no decode counter yet), and block 12 switches this site over along with the two it already owns. `gate-per-block-build.sh` selects block 09 again. Verify-width band clamp (TODO ggml-org#59, ngram-mod x host experts): the expert cache serves a routed `MUL_MAT_ID` from its arena only up to its decode/verify band (`moe_cache_max_tok_dev()`: 16 tokens on RDNA4, 8 on RDNA3/NVIDIA). A WIDER batch leaves the arena entirely -- `moe_cache_update_host()` returns false above the band, so the routed experts are streamed from the pinned host master on every step. A speculative verify batch is `n_draft + 1` rows, and while the MTP/draft family is bounded to 15 (i.e. 16 rows) by `LLAMA_SPEC_DRAFT_N_MAX_CLAMP`, the DRAFTLESS n-gram speculators have no width bound at all: `ngram_mod.n_max` defaults to 64 (`n_min` 48), the ngram-map family's `size_m` to 48. On a host-expert config the README's own `draft-mtp-adaptive,ngram-mod` recommendation therefore put every ngram step outside the band, which is the "ngram-mod halves decode with host-resident experts" report (TODO ggml-org#59). Measured (2x R9700 gfx1201, Flash-Next IQ4_NL + MTP head, `-sm tensor -ncmoe 36`, `-c 16384`, `prompts/recall.txt`, `-n 2000 --temp 0 --seed 42`): sweeping `--spec-ngram-mod-n-max` gives 154.8 t/s at 12 (13-row verify), 159.2 t/s at 15 (16 rows, in band), **55.0 t/s at 16 (17 rows -- one extra row, -65 %)**, 58.1-58.3 at 20/24, 48.1 at 32; the arena hit rate drops 0.978 -> 0.898 and the cache's counted `reaches` collapse 1086540 -> 129660 (the wide steps never reach the arena). The README combo measures 73.9 t/s uncapped against **168.3 t/s** at a 15-token draft. Controls: fully device-resident (3 GPU, `-ncmoe 0`) 144.7 (MTP n3) -> 378.7 (ngram default) vs 244.6 capped -- there the wide draft is the win; the CPU expert path (`MOE_EXPERT_CACHE_MIB=0`) 38.5 -> 67.6 (wide) vs 52.2 capped -- upstream's shape and the reason the reporter's config in issue ggml-org#214 was fine there. The fix is a new `moe_cache_band` device query (appended to `ggml_backend_device_i`, zero-initialized for backends that do not set it; CUDA answers `moe_cache_enabled() ? moe_cache_max_tok_dev(device) : 0`), `llama_model_moe_cache_band()` (the smallest band across the model's host-expert devices), and `common_speculative_clamp_ngram_n_max()`: `common_init_from_params` clamps an ENABLED n-gram speculator's draft length to `band - 1` once the model (and therefore the preflight's decision) is known, lowering `n_min` with it (ngram-mod discards a draft shorter than `n_min`, so a naked `n_max` clamp would silently disable it), and refreshes `cparams.n_rs_batch` so the slab's narrow verify floor and the chunked-GDN rollback bound see the capped depth (the uncapped default also cost ~5 GiB of arena: 32938 -> 27814 MiB). `LLAMA_SPEC_NGRAM_MOD_BAND_CLAMP=0` restores the uncapped draft. A model with no active arena reports band 0 and is never clamped; a `draft.n_max` above the band is warned about, not clamped (the 15 bound is a correctness one and matches RDNA4's band). Gates: prefilled-text purity with `ROCBLAS_USE_HIPBLASLT=0` (per the delivery's fresh-process rule) -- `plain` / `draft-mtp n3` / `ngram-mod` hand-capped / `ngram-mod` auto-clamped all hash identically (1793 chars, sha 9d914f47aebb) on the host-expert cell, the same hashes the pre-amend build produced; `LLAMA_SPEC_NGRAM_MOD_BAND_CLAMP=0` reproduces 74.1 t/s exactly; the device-resident and CPU-expert controls are unchanged (380.2 and 68.1 t/s, no clamp line). The clamp never touches a non-ngram config (the MTP-only arms log no clamp). Record: `wip/ngram-mod-host-experts/EVIDENCE-2026-10-24.md`. Windows HIP build (issue ggml-org#217): the three `std::min`/`std::max` calls on int64_t in moe-expert-cache.cu (the sizing slack guard, the auto-arena floor and the heat-coverage bound) are replaced with two local ternary helpers. With HIP on Windows (clang + the MSVC STL) clang's force-included `cuda_wrappers/algorithm` and the MSVC STL `<utility>` each define an inline `std::min<long long>` (int64_t is `__int64` there, and the `enable_if` that makes clang's version win overload resolution is not part of the mangled name), so a translation unit that instantiates both fails to codegen with "definition with same mangled name". Behaviour is unchanged: greedy text is byte-identical on the dense 4B (`-sm tensor`, 3 GPU) and the host-expert arm (35B-A3B `-ncmoe 40`), prefill-logit mean KLD 0.000000 / same-top-p 100.000 %, MTP acceptance 0.73881. Amended r125 (issue ggml-org#216): the draft-reserve log line is now gated on the model actually having host-resident experts (llama_model_moe_host_expert_dev_count() > 0). llama_model_moe_cache_preflight() is a no-op without one, so a dense model used to print "keeping the flat 3584 MiB draft reserve" for a reserve nothing consumed -- and in issue ggml-org#216 that line was read as evidence that the slab or the expert-cache arena was involved in a dense model's VRAM failure. No behaviour change: the reserve, the derived value and the MOE_EXPERT_CACHE_AUX_RESERVE_MIB override are identical wherever they are actually used.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This lets you use prompts stored in files, which makes it much easier to keep track of multiple prompts or to provide longer prompts.