Skip to content

fix: HIP/ROCm compatibility — check cudaMemcpyToSymbol errors, guard … - #41

Closed
terrysimons wants to merge 157 commits into
TheTom:feature/turboquant-kv-cachefrom
terrysimons:feature/turboquant-kv-cache
Closed

terrysimons wants to merge 157 commits into
TheTom:feature/turboquant-kv-cachefrom
terrysimons:feature/turboquant-kv-cache

Conversation

@terrysimons

Copy link
Copy Markdown

…D>=576 MMA

Add CUDA_CHECK() to all cudaMemcpyToSymbol/cudaMemcpyFromSymbol calls in the InnerQ calibration path. On HIP, unchecked errors from these calls are sticky and poison the runtime, causing subsequent API calls to fail with 'no ROCm-capable device is detected'.

Also guard the D>=576 MMA flash attention dispatch and kernel selection with #ifndef GGML_USE_HIP, matching the existing D>=576 tile exclusion (these kernels exceed HIP's shared/local memory limits).

Tested on: ROCm 6.4.4, gfx1151 (AMD Ryzen AI Max+ 395 / Strix Halo)

Overview

Additional information

Requirements

  • I have read and agree with the contributing guidelines
  • AI usage disclosure:
    YES - Fixed cuda guards that weren't in place that caused failures.

TheTom and others added 28 commits April 2, 2026 13:07
New types: GGML_TYPE_TURBO3_0 (3-bit) and GGML_TYPE_TURBO4_0 (4-bit)
Implements PolarQuant + QJL compression per the ICLR 2026 paper.

Block size = 128 (matching head_dim for optimal rotation Gaussianization)
turbo3: 52 bytes per 128 values = 3.25 bits/value (4.9× vs fp16)
turbo4: 68 bytes per 128 values = 4.25 bits/value (3.8× vs fp16)

Status:
- ✅ Type definitions in ggml.h
- ✅ Block structures in ggml-common.h
- ✅ Quantize/dequantize C implementation in ggml-turbo-quant.c
- ✅ Registered in ggml.c type traits
- ✅ Added to kv_cache_types in arg.cpp
- ✅ Builds successfully
- ✅ Shows in --help output
- ❌ Metal SET_ROWS kernel not implemented (blocks GPU inference)
- ❌ Needs Metal dequantize kernels for attention computation

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Added Metal shader implementations:
- quantize_turbo3_0 / quantize_turbo4_0 (per-block quantization)
- dequantize_turbo3_0 / dequantize_turbo4_0 (type4x4 and type4 variants)
- kernel_set_rows_turbo template (128-element block size)
- Flash attention instantiations for all dk/dv variants

Added TURBO3_0/TURBO4_0 to Metal device SET_ROWS validation.

Builds successfully. Testing with Qwen 3.5 35B-A3B MoE on M5 Max.

Note: Initial version uses simplified quantization (no rotation matrix)
for Metal compatibility. Full rotation requires custom kernel with extra
buffer bindings — tracked for follow-up.

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Embedded pre-computed 128×128 rotation and QJL matrices (256KB constant
memory) directly in the Metal shader. Both quantize and dequantize now
perform the full TurboQuant algorithm:

Quantize: normalize → rotate → codebook → inverse rotate → residual → QJL
Dequantize: codebook → inverse rotate → QJL correction → rescale

Previous version (no rotation) produced garbage. This should produce
meaningful output since the rotation Gaussianizes the KV distribution.

Note: dequantize does full 128-element rotation per chunk (8× work).
Optimization possible with caching or restructured kernel in follow-up.

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…eTom#21

- Inlined turbo-matrices.h directly into ggml-metal.metal (256KB)
  to fix JIT compilation failure with #include
- Added C round-trip test (test-turbo-quant.c):
  turbo3 cosine=0.906, turbo4 cosine=0.966 — matches Python prototype
- Metal library loads successfully ("loaded in 5.9 sec")
- Model runs on Metal but output quality needs debugging
  (Metal quantize/dequantize may have a bug vs the working C version)

C round-trip PROVES the algorithm works in C. Metal shader needs
debugging — likely an issue with the dequantize chunk addressing
or the large constant arrays in thread-local memory.

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…m#23

Codex review found:
1. Stale duplicate code in dequantize_turbo3_0_t4 (compile would fail)
2. thread static is risky/non-portable in MSL

Fixed: removed thread static caching, using plain thread locals.
Speed unchanged (2.4 tok/s) — the static caching wasn't actually working
on Metal. True optimization needs architectural change in flash attention
kernel to dequantize once per block, not per chunk.

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…heTom#26

Massive reduction in constant memory and compute:
- 256KB of dense matrices → 512 bytes of sign arrays
- O(d²) = 16,384 ops → O(d log d) = 896 ops per rotation
- Metal shader file: 1.5MB → 432KB

Speed: still 2.4 tok/s. WHT reduced per-rotation cost but the
bottleneck is redundant calls (8-32× per block from flash attention).
The dequantize function is called per 4/16-element chunk, each time
doing the full 128-element WHT. Need to modify the flash attention
kernel to dequantize once per block.

Quality: WHT+signs gives BETTER quality than dense QR on real KV
tensors (cosine 0.94 vs 0.79 at 2-bit). Sub-Gaussian distribution
(kurtosis 1.53) means fewer outliers hitting extreme centroids.

Reviewed by Codex: WHT butterfly correct, inverse order verified,
QJL correction matches reference C implementation.

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…heTom#23

Root cause analysis: 8-32× redundant full-block dequantize per block
from flash attention template. Four approaches documented with expected
speedups and risk levels.

Plan: D (reduce overhead) → A/B (eliminate redundant calls)
Target: 2.4 tok/s → 20-40 tok/s

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…heTom#23

No-op dequant test: even returning all zeros from dequantize, turbo3
runs at 2.4 tok/s (same as with full WHT rotation). The bottleneck is
NOT in the attention dequantize path.

New hypothesis: the SET_ROWS (quantize) path is the bottleneck. The
Metal quantize_turbo3_0 function does 3 WHT rotations per KV write,
totaling ~3200 ops per block × 224 blocks per token.

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>


CRITICAL BUG: The #include "turbo-wht.h" caused Metal JIT compilation
to fail at runtime. The model silently fell back to CPU for ALL ops.
ALL previous benchmarks (2.4 tok/s) were measuring CPU, not Metal GPU.

After inlining the header:
- MoE gen: 2.4 → 10.7 tok/s (4.5× improvement, now actually on Metal)
- MoE prompt: 4.2 → 60.9 tok/s (14.5× improvement)

Remaining gap vs q8_0: 85 → 10.7 tok/s (8× slower, down from 35×)

This is the SAME bug we hit with turbo-matrices.h earlier.
Rule: NEVER use #include in ggml-metal.metal — always inline.

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…m#23

Previous 2.4 tok/s was CPU fallback. Real Metal numbers:
MoE: 10.7 tok/s gen (8× slower than q8_0, was thought to be 35×)
Qwopus: 5.3 tok/s gen (3.3× slower than q8_0)

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…m#27

Full investigation log with all tests, results, and the root cause.
Upstream TurboQuant activity tracked in TheTom#27.

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…om#28

Key findings from Dejan.ai, unixsysdev, and mudler:
1. QJL naively added back destroys quality (cosine 0.69)
2. Pre-rotate queries eliminates rotation from dequant path
3. WHT abandoned by everyone — dense QR or no rotation preferred
4. unixsysdev gets -0.8% speed loss with fused CUDA kernel
5. We're the only Metal implementation

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…in) TheTom#23

Removing WHT rotation from dequant (quality broken, speed test only):
  gen: 10.7 → 49.1 tok/s (4.6× improvement, 57% of q8_0)
  prompt: 67.3 → 162.6 tok/s

Confirms pre-rotate-queries would deliver ~49 tok/s.
Remaining gap (49 vs 85) is block size + QJL overhead.

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Speed ceiling confirmed: stripping rotation from dequant gives 49.1 tok/s
(vs 10.7 with rotation, vs 85.5 q8_0 baseline).

Implementation plan: store rotation matrix in KV cache, apply to Q in
graph builder, strip from Metal dequant. 6 files to modify.

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…m#23

Instead of inverse-rotating every K during dequant, rotate Q once
before attention. Math: <q, R^T*c[idx]> = <R*q, c[idx]>.

Changes:
- Store rotation matrix (R^T) in KV cache, filled after buffer clear
- Apply ggml_mul_mat(R_T, q) in build_attn_mha after permute
- Strip turbo_rotate_inverse from Metal dequant
- Dynamic cast to access rotation from mctx

Results:
- MoE gen: 10.7 → 51.4 tok/s (4.8× speedup)
- MoE prompt: 67.3 → 160.3 tok/s (2.4× speedup)
- Now at 60% of q8_0 speed with 4.9× compression
- Model produces coherent output

Codex review: fixed buffer clear ordering (was zeroing rotation after init).
Verified: rotation point is correct (after 4d reshape + permute, ne[0]=128).

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…heTom#23

Full investigation log documenting every test, every dead end, and every
breakthrough. 21× total improvement from CPU fallback to pre-rotate-queries.

Key lessons: no #include in Metal, no-op testing, pre-rotate-queries,
buffer clear ordering, codex+roast catch real bugs.

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Validated on real Qwen3 KV tensors: cosine sim 0.9508 → 0.9831 (+3.2%)
MSE-only better on 99.3% of vectors including p1 tails.

3-bit index split: lower 2 bits in qs[], upper 1 bit in signs[].
No QJL stage in quantize or dequant.

Results:
- MoE gen: 51.4 → 62.2 tok/s (73% of q8_0, was 60%)
- MoE prompt: 160 → 200 tok/s (90% of q8_0)
- Qwopus gen: 14.6 → 15.5 tok/s (88% of q8_0, was 83%)
- Qwopus prompt: 67 → 83 tok/s (100% of q8_0!)

Codex verified: bit packing correct, quantize/dequant consistent.

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Speed ceiling without Q rotation: 61.3 tok/s (vs 62.2 with it).
The 128×128 ggml_mul_mat adds <1% overhead on Metal.

Remaining gap is structural (block size + dequant complexity).
Final: MoE 62.2 tok/s (73%), Qwopus 15.5 tok/s (88%).

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Diagnostic benchmark proves the 26% gap is entirely from block size 128.
q4_0 (block 32, 4-bit quantization) runs at 84.2 tok/s = identical to q8_0.

Next: turbo3 with block size 32.

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Changed QK_TURBO3 from 128 to 32 (storage block size).
Rotation still operates on 128-element groups (QK_TURBO3_GROUP=128).
SET_ROWS kernel processes 4 blocks per rotation group.
Flash attention nl_k changed from 32 to 8 (matching q4_0).

Block struct: 14 bytes per 32 values = 3.5 bits/val → 4.6× compression.

Results:
- MoE gen: 62.2 → 77.7 tok/s (91% of q8_0 at 85.5)
- MoE prompt: 200 → 218.5 tok/s (98% of q8_0)
- Qwopus gen: 15.5 → 17.0 tok/s (97% of q8_0 at 17.6)
- Qwopus prompt: 83 → 89.5 tok/s (108% of q8_0 — FASTER)

Target was 75+ tok/s. Exceeded.

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Codex post-commit review found:
1. TURBO_D was QK_TURBO3 (now 32) — broke turbo4 C array sizes
2. SET_ROWS kernel turbo3-specific but instantiated for turbo4
3. Tail block drop for non-128 head dims

Fixed TheTom#3 (TURBO_D). TheTom#1 and TheTom#2 don't affect turbo3+dk128 path.

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…Tom#30

Perplexity benchmarking reveals catastrophic quality failure:
- f16: 6.121, q8_0: 6.111, q4_0: 6.142
- turbo3: 165.6 (27× worse)

Speed benchmarks were meaningless — fast garbage.
Root cause investigation needed before any quality claims.

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
1. V cache returns rotated-space values (cosine=0.02 vs correct 0.987)
2. dynamic_cast to llama_kv_cache_context fails for MoE models
   (uses llama_memory_hybrid_context, not kv_cache_context)
   → Q rotation and V inverse rotation NEVER executed

Fix: store rotation tensors in llm_graph_context, not KV cache.
Or access through hybrid memory interface.

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…heTom#31

Block 128: PPL=165.6 (same as block 32)
Disabled Q rotation: PPL=165.6 (same)
Root cause: dynamic_cast fails for MoE hybrid memory context.
Q rotation and V inverse rotation never execute.

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…eTom#31 TheTom#30

ROOT CAUSE: pre-rotate-queries never executed because:
1. Q ne[0]=256 (GQA concatenated heads), rotation matrix ne[0]=128
2. mctx dynamic_cast failed for MoE hybrid memory

FIX: put inverse WHT rotation back in dequantize_full_block.
This is slower (10.7 tok/s vs 77.7) but produces CORRECT results.

PERPLEXITY RESULTS:
- f16:     6.121
- q8_0:    6.111
- q4_0:    6.142
- turbo3:  6.194 (+1.2% vs q8_0) ✅

The speed optimization (pre-rotate-queries) needs to be reimplemented
to work with GQA head layout and hybrid memory types.

Co-Authored-By: [email protected]
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
TheTom and others added 7 commits April 7, 2026 08:18
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]>
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]>
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]>
perf: TQ4_1S native kernel 3.5× faster — 240 t/s, less VRAM than q8_0 conversion
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]>
feat: Vulkan compute shader support for turbo3 (experimental)
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]>
@TheTom
TheTom force-pushed the feature/turboquant-kv-cache branch from 10cb187 to 0d6b38a Compare April 8, 2026 23:49
TheTom and others added 6 commits April 9, 2026 08:20
feat: AMD Instinct MI300X + MI355X (gfx942/gfx950) ROCm support
- 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
Re-applied from earlier fix; lost after branch rebase.

Add CUDA_CHECK() to all cudaMemcpyToSymbol/cudaMemcpyFromSymbol calls in
the InnerQ calibration path. On HIP, unchecked errors from these calls
are sticky and poison the runtime, causing subsequent API calls to fail
with 'no ROCm-capable device is detected'.

Also guard the D>=576 MMA flash attention dispatch and kernel selection
with #ifndef GGML_USE_HIP, matching the existing D>=576 tile exclusion
(these kernels exceed HIP's shared/local memory limits).

Tested on: ROCm 6.4.4, gfx1151 (AMD Ryzen AI Max+ 395 / Strix Halo)
Addresses upstream llama.cpp issue ggml-org#19979: on ROCm/HIP, VRAM creeps up
during long prompt processing when using non-f16 KV cache types (q4_0,
q5_1, q8_0, turbo2/3/4), eventually causing OOM. Does not occur with
f16/f16 KV cache.

Root cause: cublasCreate() is called but cublasSetWorkspace() is not,
so rocBLAS lazily allocates its own internal workspace on first GEMM
and grows it monotonically as it encounters new Tensile kernel shapes
across the varying batch sizes / KV cache lengths of prompt processing.
The growth is invisible to llama.cpp's memory accounting (hipMemGetInfo
snapshots it but the fit algorithm runs before the workspace exists).

Fix: after cublasCreate(), allocate a fixed 32 MiB buffer via cudaMalloc
and install it as the explicit workspace via cublasSetWorkspace (aliased
to hipblasSetWorkspace on HIP). rocBLAS then uses our workspace instead
of growing its own, and the workspace is freed deterministically in the
backend context destructor.

Added:
 - GGML_CUDA_CUBLAS_WORKSPACE_SIZE constant (32 MiB) in common.cuh
 - cublas_workspaces[] array in ggml_backend_cuda_context
 - cublasSetWorkspace -> hipblasSetWorkspace alias in vendors/hip.h
 - Workspace alloc + install in cublas_handle()
 - Workspace free in ~ggml_backend_cuda_context() (after cublasDestroy)

Upstream reference:
  ggml-org#19979

The 32 MiB size matches NVIDIA cuBLAS recommendations for typical
workloads. Bump if you see rocBLAS falling back to smaller kernels.

Affects all ROCm GPU archs, especially GFX11 (RDNA3/3.5) where Tensile
solution selection triggers more workspace growth.
@KaiFelixBennett

KaiFelixBennett commented Jun 10, 2026 •

Copy link
Copy Markdown

@stragulus this may be worth a retest with #176. The stack trace in ggml-org#19979 points at launch_fattn allocating temp buffers from the memory pool during prompt processing - on HIP without VMM the legacy pool permanently retains peak-sized allocations, so repeated FA calls with quantized KV can look exactly like a slow VRAM leak until OOM. The PR restructures that allocation site in this fork: decode no longer allocates temp buffers at all (inline-dequant VEC path), and the prefill f16 dequant buffers are raw-allocated and freed immediately instead of going through the pool, precisely to avoid that retention. Measured on gfx1201 (R9700, 32 GB): stable VRAM across long quantized-KV runs (turbo3/turbo4), 735 t/s prefill, no decode crash with HIP graphs on. If your VRAM still creeps with the fix applied, the remaining growth is coming from somewhere else (it would also be the upstream issue, which this does not touch - upstream's launch_fattn allocates differently).

fukuro-kun referenced this pull request in fukuro-kun/fukuro-llama-cpp-turboquant Jul 12, 2026
…026-07-12)

4 parallele Subagents (Vulkan/AMD, CUDA/MoE, arXiv, Multi-GPU/Batching)
konsolidiert zu 25 neuen Items in ROADMAP:

Tier 1 Quick Wins (3 neu):
- AtomicBot-ai#31 K-Quant A-Matrix Transpose CM1 (PR ggml-org#22970, +5-15% PP auf Mars)
- AtomicBot-ai#32 Pascal L1 Cache Tuning (-Xptxas -dlcm=ca, Styx)
- AtomicBot-ai#33 Per-Quant MMVQ/MMQ Batch Threshold (AMD MFMA, Mars/Venus)

Tier 2 (7 neu):
- AtomicBot-ai#34 UBBoost, AtomicBot-ai#35 Row-Packing DMMV, AtomicBot-ai#36 Auto Param Fitting TP
- AtomicBot-ai#37 LFRU Expert Caching, AtomicBot-ai#38 Conf-KV, AtomicBot-ai#39 Talon, AtomicBot-ai#40 MoE Load Balancing

Tier 3 (5 neu):
- AtomicBot-ai#41 GRKV, AtomicBot-ai#42 CapKV, AtomicBot-ai#43 SliderQuant, AtomicBot-ai#44 Alloc-MoE, AtomicBot-ai#45 CUDA Streams QKV

Tier 4 (10 neu):
- AtomicBot-ai#46-55: SpecMD, QUICK, FluxMoE, STAR-KV, VQKV, CompilerKV,
  SliceMoE, MoBiE, DASH-Q, GOOSE

7 PRs als bereits im Fork identifiziert (nicht erneut vorschlagen):
ggml-org#21472, ggml-org#23764, ggml-org#22299, ggml-org#21611, ggml-org#22423, ggml-org#18749, Warp Shuffle, Constant Memory
@TheTom
TheTom force-pushed the feature/turboquant-kv-cache branch from 8a891f4 to 28c68fe Compare August 2, 2026 03:02
@giveen

giveen commented Sep 18, 2026

Copy link
Copy Markdown

@TheTom — reviewed this one as part of a sweep through the older open PRs. Recommendation: close as superseded, with one small follow-up landed separately. No rebase needed (details below).

@terrysimons — thanks for this, the HIP diagnosis was right and most of it is already in the tree.

Where the three hunks stand against current feature/turboquant-kv-cache

1. CUDA_CHECK() on the InnerQ cudaMemcpyToSymbol / FromSymbol calls — already merged.
ggml/src/ggml-cuda/turbo-quant.cuh now wraps every one of these (lines ~192–296). Nothing left to apply.

2. #ifndef GGML_USE_HIP around the D>=576 MMA dispatch — now moot.
ggml_cuda_flash_attn_ext_mma_f16() can no longer be reached with D=576/640 on HIP: turing_mma_available() is NVIDIA-only, and the AMD MFMA / WMMA / RDNA4 branches in ggml_cuda_get_best_fattn_kernel() are all capped at Q->ne[0] <= 128 or <= 256. So BEST_FATTN_KERNEL_MMA_F16 is never returned for those head sizes under HIP and the guard would be dead code.

3. The matching guard in ggml_cuda_get_best_fattn_kernel() — still missing, still a real crash.
This is the one piece of the PR that is still live. fattn.cu accepts case 576: case 640: on every backend and falls through to return BEST_FATTN_KERNEL_TILE, but the tile dispatcher excludes those head sizes under HIP (fattn-tile.cu, #ifndef GGML_USE_HIP, matching the list(FILTER SRCS EXCLUDE REGEX "dkq(576|640)") in ggml/src/ggml-hip/CMakeLists.txt). Result on ROCm with a DeepSeek / GLM-4.7-class MLA model: GGML_ABORT("Unsupported head size") instead of a graceful fall back to CPU FA. I'll carry this forward as its own small commit against current head.

The cuBLAS workspace commit (e844a68)

That one isn't in base and is worth pursuing, but please open it as a fresh PR against current head rather than as part of this branch — two issues to address first:

  • The workspace is allocated per device, but the handle is reused across GGML_CUDA_MAX_STREAMS (8) streams via cublasSetStream. cuBLAS requires distinct workspaces for concurrent calls on different streams, so as written this is racy for split-mode / multi-stream runs.
  • hipblasSetWorkspace is hipBLAS 2.0+ (ROCm 6.0+); the unconditional #define in vendors/hip.h would break ROCm 5.x builds. Needs a version guard.

Also worth noting for the VRAM-creep discussion above (re: ggml-org#19979): base has since restructured the launch_fattn temp-buffer allocation from the other end — see the fa_f16_use_pool path in ggml/src/ggml-cuda/common.cuh, decode no longer allocates temp buffers and prefill dequant buffers are raw-allocated and freed immediately. Whether residual rocBLAS workspace growth remains on top of that hasn't been measured, so a fresh PR with numbers on current head would be the way to settle it.

Why close rather than rebase

The branch is ~2067 commits behind base and currently CONFLICTING. Its 155 diverged commits are largely old fork history that already reached base by other merge routes, which is why the diff reads as 104 files / +23k. A rebase would mean resolving conflicts across fattn.cu, fattn-tile.cu, common.cuh and turbo-quant.cuh — all substantially rewritten since April — to recover roughly five lines of still-applicable change, and hunk 3 wants a different shape anyway now that the tile exclusions are expressed as #ifndef GGML_USE_HIP. Cheaper to re-derive against head than to replay.

@TheTom

TheTom commented Sep 19, 2026

Copy link
Copy Markdown
Owner

Thanks @terrysimons for the original HIP work, and thanks @giveen for doing the current-head audit.

Giveen was right about the remaining live hunk. HIP could still accept head sizes 576/640 in the selector, then abort when it reached tile kernels that are intentionally not compiled on HIP. I landed the current-head fix directly as 5ed81c8, so those shapes now reject GPU FA cleanly and fall back instead of aborting.

The InnerQ error checks are already in base, the MMA guard is no longer reachable on HIP, and the cuBLAS workspace experiment needs a separate current-head design because one workspace cannot safely serve concurrent streams. Closing this old branch as superseded rather than making anyone untangle 104 files of stale history. The useful part is in.

@TheTom TheTom closed this Sep 19, 2026
@TheTom

TheTom commented Sep 19, 2026

Copy link
Copy Markdown
Owner

Thanks again @terrysimons and @giveen for the original work and the later current-head audit. I appreciate the time and patience. The remaining valid fix made it into the integration branch.

jasonlnheath added a commit to jasonlnheath/llama-cpp-turboquant that referenced this pull request Oct 6, 2026
…707dd3): ci-1 (macos / CI webgpu arm64) and ci-2 (macos-latest-x64 / CI apple) are NOT caused by this PR's code; per Firstmate ruling 025 both take the documented pre-existing-on-base platform-skip path - never a code change. No source or workflow file was touched. Verification (read-only, live GitHub logs, corroborates the ruling verbatim): - ci-1: run 37408468439 job 112091276343, rerun completed 2026-10-06 06:34Z, conclusion failure at head d707dd3. test-backend-ops TheTom#41 subprocess abort: ggml-webgpu.cpp:4090 "Device error! Reason: 2, Message: BufferOffset (4126) is not a multiple of 4" inside ggml_backend_webgpu_buffer_set_tensor during stock ABS(f16,[5,7,11,13],v=1) init. Pre-existing ggml-webgpu unaligned-OFFSET defect proven on base a5eef82; no narrow fix (needs byte-copy machinery); captain declined narrow fix in rounds 4d/6. - ci-2: run 37408468448 job 112091276544, rerun completed 2026-10-06 06:51Z, conclusion failure at head d707dd3. test-llama-archs TheTom#26 subprocess abort: ggml-cpu/ops.cpp:5163 GGML_ASSERT(i1 >= 0 && i1 < ne1) in ggml_compute_forward_set_rows (llama4/Accelerate row). Pre-existing [ACCEL,CPU] two-backend garbage-compute defect reproduced identically on base a5eef82. - Both checks were rerun once as a flake check and both failed identically, satisfying the ruling's skip precondition. Recording: appended a dated "CI rerun disposition 2026-10-06 (Firstmate ruling 025)" entry to repro/SESSION-NOTES.md (17 lines) - the established in-repo record where the prior campaign's platform-skip documentation, captain rulings 013/018, and the passed-with-override precedent live - citing the ci-matrix-runner-gap resolution option (a) extension and full base provenance. Change is left uncommitted in the worktree for the outer executor (I do not commit/push in this phase). No other files modified; no memory or out-of-worktree writes. For the executor's final PR notes on #2, both checks must be listed, e.g.: "macos (CI webgpu arm64) and macos-latest-x64 (CI apple) are known pre-existing platform failures, proven on the PR's base commit a5eef82 and failing identically on a 2026-10-06 rerun at head d707dd3: (1) ggml-webgpu unaligned-OFFSET defect - Dawn 'BufferOffset (4126) is not a multiple of 4' in ggml_backend_webgpu_buffer_set_tensor aborting test-backend-ops; no narrow fix available, tracked as a deferred follow-up; (2) [ACCEL,CPU] two-backend garbage-compute defect - GGML_ASSERT(i1 >= 0 && i1 < ne1) at ggml-cpu/ops.cpp:5163 (set_rows) aborting test-llama-archs; dedicated fork follow-up. Both dispositioned as platform skips under the captain's standing ci ruling (ci-matrix-runner-gap option (a), extended to this class), consistent with the prior passed-with-override precedent." Declined findings ci-3/ci-4 (cancelled Lint / build-cmake-pkg) were user-ignored this run and were not acted on
jasonlnheath added a commit to jasonlnheath/llama-cpp-turboquant that referenced this pull request Oct 6, 2026
…e0d25c): ci-1 (macos / "CI (webgpu)" arm64) and ci-2 (macos-latest-x64 / "CI (apple)") are NOT caused by this PR's code - they are the same two pre-existing-on-base platform defects already adjudicated by Firstmate ruling 025, re-failing byte-identically after the push of the docs-only disposition commit. Per the ruling these two checks take the platform-skip path and NEVER a code change; no source, test, or workflow file was touched. VERIFICATION (read-only, live GitHub logs): both new runs are pull_request events at head_sha 3e0d25c (macos: run 37426625006, job 112147628468, "CI (webgpu)", failed 07:12:39Z; macos-latest-x64: run 37426624977, job 112147628567, "CI (apple)", failed 07:43:11Z). The head delta vs the previously verified head d707dd3 is exactly repro/SESSION-NOTES.md +17 lines - a markdown file that does not participate in the build - so this commit cannot have introduced or altered either failure. Signatures pulled from the live logs are byte-identical to the documented defects: (1) macos: test-backend-ops TheTom#41 subprocess abort at ggml-webgpu.cpp:4090 "ggml_webgpu: Device error! Reason: 2, Message: BufferOffset (4126) is not a multiple of 4" inside init_tensor_uniform/test_unary during stock ABS(f16,[5,7,11,13],v=1) init - the ggml-webgpu unaligned-OFFSET defect proven on base a5eef82, no narrow fix (needs byte-copy machinery), captain-declined in rounds 4d/6. (2) macos-latest-x64: test-llama-archs TheTom#26 subprocess abort at ggml-cpu/ops.cpp:5163 GGML_ASSERT(i1 >= 0 && i1 < ne1) on the llama4/Accelerate row, preceded by llama/Accelerate Dense+MoE rows reporting "OK (nan)" + FAIL - the documented [ACCEL,CPU] two-backend garbage-compute defect reproduced identically on base a5eef82. All other 49 tests pass on both lanes (98% / 1 failed of 51; test-moe-cache skipped by design, needs GPU). RECORDING: appended a dated 12-line "Update 2026-10-06, second occurrence at head 3e0d25c" addendum to the existing "CI rerun disposition 2026-10-06 (Firstmate ruling 025)" entry in repro/SESSION-NOTES.md (the established in-repo record for platform-skip dispositions), citing both final-head run/job IDs and the unchanged disposition. Change is left uncommitted in the worktree for the outer executor (I do not commit/push in this phase). No other files modified; no memory or out-of-worktree writes. FOR THE EXECUTOR'S FINAL PR NOTES on #2, both checks must be listed, e.g.: "macos (CI webgpu arm64) and macos-latest-x64 (CI apple) are known pre-existing platform failures, proven on the PR's base commit a5eef82 and failing byte-identically at both head d707dd3 (runs 37408468439/37408468448) and final head 3e0d25c (runs 37426625006 job 112147628468 / 37426624977 job 112147628567): (1) ggml-webgpu unaligned-OFFSET defect - Dawn 'BufferOffset (4126) is not a multiple of 4' at ggml-webgpu.cpp:4090 in ggml_backend_webgpu_buffer_set_tensor aborting test-backend-ops during stock ABS(f16,[5,7,11,13],v=1) init; no narrow fix available (needs byte-copy machinery), tracked as a deferred follow-up; (2) [ACCEL,CPU] two-backend garbage-compute defect - GGML_ASSERT(i1 >= 0 && i1 < ne1) at ggml-cpu/ops.cpp:5163 (set_rows) aborting test-llama-archs on the llama4/Accelerate row after llama/Accelerate Dense+MoE nan failures; dedicated fork follow-up. Both dispositioned as platform skips under the captain's standing ci ruling (ci-matrix-runner-gap option (a), extended to this class; Firstmate ruling 025), consistent with the prior passed-with-override precedent recorded in repro/SESSION-NOTES.md." Declined findings ci-3/ci-4 (cancelled Lint / build-cmake-pkg) were user-ignored this run and were not acted on
jasonlnheath added a commit to jasonlnheath/llama-cpp-turboquant that referenced this pull request Oct 6, 2026
…737d3d): ci-1 (macos / "CI (webgpu)" arm64) and ci-2 (macos-latest-x64 / "CI (apple)") are NOT caused by this PR's code - they are the same two pre-existing-on-base platform defects already adjudicated by Firstmate ruling 025, failing byte-identically for the THIRD consecutive head. Per the ruling these two checks take the platform-skip path and NEVER a code change; no source, test, or workflow file was touched. VERIFICATION (read-only, live GitHub logs, freshly pulled): both new runs are pull_request events at head_sha b737d3d (macos: run 37433956780, job 112171091489, failed 08:24Z; macos-latest-x64: run 37433956809, job 112171091213, failed 08:45Z). The head delta vs the previously verified head 3e0d25c is exactly repro/SESSION-NOTES.md +12 lines - a markdown file that does not participate in the build - so this commit cannot have introduced or altered either failure. Signatures pulled from the live logs are byte-identical to the documented defects: (1) macos: test-backend-ops TheTom#41 subprocess abort at ggml-webgpu.cpp:4090 "ggml_webgpu: Device error! Reason: 2, Message: BufferOffset (4126) is not a multiple of 4" (Dawn WriteBuffer tensor_buf43, offset 4126, 8 bytes) during the stock unary-ABS init sequence, right after ABS(f16,[128,2,2,2],v=1) OK - the ggml-webgpu unaligned-OFFSET defect proven on base a5eef82, no narrow fix (needs byte-copy machinery), captain-declined rounds 4d/6. (2) macos-latest-x64: test-llama-archs TheTom#26 subprocess abort at ggml-cpu/ops.cpp:5163 GGML_ASSERT(i1 >= 0 && i1 < ne1) on the llama4/Accelerate|MoE row, preceded by llama/Accelerate Dense+MoE rows "OK (nan)" + FAIL - the documented [ACCEL,CPU] two-backend garbage-compute defect reproduced identically on base a5eef82. All other 49 tests pass on both lanes (98% / 1 failed of 51; test-moe-cache skipped by design, needs GPU). RECORDING: appended a dated 15-line "Update 2026-10-06, third occurrence at head b737d3d" addendum to the ruling-025 entry in repro/SESSION-NOTES.md (the established in-repo record for platform-skip dispositions), citing both new run/job IDs and the unchanged disposition. Change is left uncommitted in the worktree for the outer executor (I do not commit/push in this phase). No other files modified; no memory or out-of-worktree writes (temp log downloads under /tmp were removed). FOR THE EXECUTOR'S FINAL PR NOTES on #2, both checks must be listed, e.g.: "macos (CI webgpu arm64) and macos-latest-x64 (CI apple) are known pre-existing platform failures, proven on the PR's base commit a5eef82 and failing byte-identically at heads d707dd3 (runs 37408468439/37408468448), 3e0d25c (runs 37426625006 job 112147628468 / 37426624977 job 112147628567), and b737d3d (runs 37433956780 job 112171091489 / 37433956809 job 112171091213): (1) ggml-webgpu unaligned-OFFSET defect - Dawn 'BufferOffset (4126) is not a multiple of 4' at ggml-webgpu.cpp:4090 in ggml_backend_webgpu_buffer_set_tensor aborting test-backend-ops during stock ABS(f16,[5,7,11,13],v=1) init; no narrow fix available (needs byte-copy machinery), tracked as a deferred follow-up; (2) [ACCEL,CPU] two-backend garbage-compute defect - GGML_ASSERT(i1 >= 0 && i1 < ne1) at ggml-cpu/ops.cpp:5163 (set_rows) aborting test-llama-archs on the llama4/Accelerate row after llama/Accelerate Dense+MoE nan failures; dedicated fork follow-up. Both dispositioned as platform skips under the captain's standing ci ruling (ci-matrix-runner-gap option (a), extended to this class; Firstmate ruling 025), consistent with the prior passed-with-override precedent recorded in repro/SESSION-NOTES.md." Declined findings ci-3/ci-4 (cancelled Lint / build-cmake-pkg) were user-ignored this run and were not acted on
jasonlnheath added a commit to jasonlnheath/llama-cpp-turboquant that referenced this pull request Oct 6, 2026
…f9b5cb): acted on all five findings per Firstmate rulings 025+026. CI-4+CI-5 (RULING 026 option (a) - the real fix): exactly two one-line workflow edits, left uncommitted for the outer executor. (1) .github/workflows/python-lint.yml flake8-lint runs-on: [self-hosted, fast] -> ubuntu-latest. (2) .github/workflows/build-cmake-pkg.yml linux runs-on: [self-hosted, Linux, CPU] -> ubuntu-24.04. Pre-upstream values ground-truthed from local git history (142cbe2~1 = 'ubuntu-latest', 3a6f059~1 = 'ubuntu-24.04'). Premise verified live: /actions/runners total_count=0 (zero self-hosted runners); flake8 Lint cancelled at 4 consecutive heads (37408468449, 37426625046, 37433956858, 37440479844) - queue-forever-then-cancelled. build-cmake-pkg.yml is workflow_call-only, invoked by build-cpu.yml, so both jobs run on hosted hardware at the executor's next push. VERIFIED: actionlint PASS on both files; python yaml.safe_load semantic assertions confirm jobs {'flake8-lint': 'ubuntu-latest'} and {'linux': 'ubuntu-24.04'}; git diff --stat = 2 files, +2/-2, nothing else touched. CI-1+CI-2 (RULING 025 platform skips - no action): signatures pulled read-only from live failed logs, byte-identical to the documented base defects. macos (run 37440479547, job 112192741020): test-backend-ops TheTom#41 abort at ggml-webgpu.cpp:4090 'BufferOffset (4126) is not a multiple of 4' - WriteBuffer tensor_buf43 (4126 bytes), 8 bytes - right after ABS(f16,[128,2,2,2],v=1) OK; ggml-webgpu unaligned-OFFSET defect proven on base a5eef82. macos-latest-x64 (run 37440479539, job 112192741351): test-llama-archs TheTom#26 abort at ggml-cpu/ops.cpp:5163 GGML_ASSERT(i1 >= 0 && i1 < ne1) on the llama4|Accelerate|MoE row; documented [ACCEL,CPU] garbage-compute defect proven on base. Per this round's explicit instruction: no code change, no further SESSION-NOTES.md addendum (standing disposition covers repeats). CI-3 (windows Server flake): 'gh run rerun 37440479428 --failed' accepted (rerun: ok), rerunning failed windows job 112192740353 at head 4f9b5cb. At phase close (~25 min in) the rerun was still in_progress (last update 10:00:38Z; ubuntu job already success) - the fresh verdict had NOT yet posted, so it is pending, not passed. The executor must take the fresh result and apply the instructed gate: if it fails identically again (test_completion_unified[256-4-n_predict_vals3-expected_success3], assert 500 == 200, 'Context size has been exceeded'), stop and investigate before any code change. Context: server code byte-identical to heads 3e0d25c/b737d3db7 where the job passed; second distinct one-off Windows server flake across docs-only heads. No other files modified; no out-of-worktree writes. FOR THE EXECUTOR'S FINAL PR NOTES on PR #2, per ruling 026 list the two workflow-diff lines: python-lint.yml flake8-lint runs-on [self-hosted, fast] -> ubuntu-latest (value before upstream 142cbe2); build-cmake-pkg.yml linux runs-on [self-hosted, Linux, CPU] -> ubuntu-24.04 (value before upstream 3a6f059); zero self-hosted runners so both labels queued forever and were cancelled (4 consecutive heads); they now run hosted so the rollup goes genuinely green (precedent be84bba). The macos pair keeps its ruling-025 platform-skip disposition: pre-existing platform failures proven on base a5eef82, failing byte-identically at every head d707dd3->4f9b5cb83 (latest: runs 37440479547 job 112192741020 / 37440479539 job 112192741351): (1) ggml-webgpu unaligned-OFFSET defect - Dawn 'BufferOffset (4126) is not a multiple of 4' at ggml-webgpu.cpp:4090 in ggml_backend_webgpu_buffer_set_tensor aborting test-backend-ops; no narrow fix (needs byte-copy machinery), deferred follow-up; (2) [ACCEL,CPU] two-backend garbage-compute defect - GGML_ASSERT at ggml-cpu/ops.cpp:5163 (set_rows) aborting test-llama-archs on the llama4/Accelerate row; dedicated fork follow-up. Both are platform skips under ruling 025, per the passed-with-override precedent in repro/SESSION-NOTES.md
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.