Skip to content

fix: turbo4 SET_ROWS, tail-block truncation, constant coupling, stack overflow (Issue #29) - #4

Merged
TheTom merged 3 commits into
TheTom:feature/turboquant-kv-cachefrom
seanrasch:feature/turboquant-kv-cache
Mar 27, 2026
Merged

TheTom merged 3 commits into
TheTom:feature/turboquant-kv-cachefrom
seanrasch:feature/turboquant-kv-cache

Conversation

@seanrasch

Copy link
Copy Markdown

Summary

Fixes all three bugs from Issue #29, plus a bonus stack overflow fix found during testing.

  • Bug 1: kernel_set_rows_turbo hardcoded turbo3 packing for turbo4 — split into separate kernel_set_rows_turbo3 and kernel_set_rows_turbo4 kernels. turbo4 now correctly does 3-bit PolarQuant + QJL residual correction.
  • Bug 2: Integer division n_groups = nk0 / blocks_per_group silently dropped tail blocks for non-128-aligned head dims. Added ceiling division with tail-group bounds checking, and GGML_ASSERT in WHT dispatch.
  • Bug 3: TURBO_D was semantically coupled to QK_TURBO4 — replaced with TURBO_ROT_DIM (= QK_TURBO3_GROUP) and added static_assert guard.
  • Bonus: turbo_init_rotation() allocated a 64KB float G[128*128] on the stack, causing segfault on llama.cpp worker threads. Eliminated by generating directly into the static turbo_rotation[] array.

Test plan

  • C code compiles clean (gcc -fsyntax-only)
  • Metal shader validated (kernel split, host_names preserved, turbo4 has all 5 quantize steps)
  • turbo4 Python tests: 17/17 passed (turboquant_plus, separate PR)
  • Metal end-to-end (needs Apple Silicon — I don't have it)
  • Note: CPU SET_ROWS has no turbo dispatch — turbo types only work on Metal/CUDA backends

Ampere benchmark data (spiritbuun's CUDA fork, RTX 3080 Ti 12GB)

First published Ampere numbers for TurboQuant. Qwen3 8B Q4_K_M:

Cache pp512 (t/s) tg128 (t/s) vs f16
f16 4970 126.7 1.00x
q8_0 4909 125.4 0.99x
turbo3 4498 101.3 0.90x pp / 0.80x tg

Note: spiritbuun's fork needed PR #1's pool size fix (+2 in llama-kv-cache.cpp) to avoid crash on turbo cache init.

Closes #29

🤖 Generated with Claude Code

seanrasch and others added 2 commits March 26, 2026 22:13
…ling (Issue TheTom#29)

Three bugs from the block-size-32 refactor:

1. kernel_set_rows_turbo hardcoded turbo3 packing for turbo4 — split into
   separate kernel_set_rows_turbo3 and kernel_set_rows_turbo4 kernels.
   turbo4 now correctly does 3-bit PolarQuant + QJL residual correction.

2. Integer division in n_groups = nk0 / blocks_per_group silently dropped
   tail blocks for non-128-aligned head dims (e.g. dk=192). Added ceiling
   division with tail-group bounds checking in turbo3, and GGML_ASSERT in
   WHT dispatch to catch non-128-aligned tensors.

3. TURBO_D constant was semantically coupled to QK_TURBO4 — replaced with
   TURBO_ROT_DIM (= QK_TURBO3_GROUP) and added static_assert that
   QK_TURBO4 == QK_TURBO3_GROUP to guard against future drift.

Closes TheTom#29

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

turbo_init_rotation() allocated a 128x128 float array (64KB) on the stack
to generate the random Gaussian matrix, then memcpy'd it to the static
turbo_rotation[]. llama.cpp worker threads have reduced stack sizes,
causing segfault on first turbo4 quantize call.

Fix: generate directly into the static turbo_rotation[] array, eliminating
the intermediate stack allocation entirely. The Gram-Schmidt QR
decomposition already runs in-place on turbo_rotation[].

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

Copy link
Copy Markdown
Author

RTX 3080 Ti (Ampere, SM 8.6) Benchmark Results

First published Ampere numbers for TurboQuant. Tested on spiritbuun's CUDA fork with the PR #1 pool size fix applied.

Model: Qwen3 8B Q4_K_M | GPU: EVGA RTX 3080 Ti 12GB | Flash attn: on | Full offload: ngl=99

Cache pp512 (t/s) tg128 (t/s) vs f16 pp vs f16 tg Compression
f16 4970 126.7 1.00x 1.00x 1.0x
q8_0 4909 125.4 0.99x 0.99x 2.0x
turbo3 4498 101.3 0.90x 0.80x 4.9x
turbo4 2259 91.3 0.45x 0.72x 3.8x

Notes

  • turbo4 prefill hit (0.45x) matches spiritbuun's known MMA-disabled issue
  • turbo3 decode (0.80x) is notably worse than spiritbuun's 3090 results (~0.97x), suggesting Ampere pays more for the turbo3 dequant path in flash attention
  • turbo4 decode (0.72x) is more competitive relative to turbo3 on this hardware
  • spiritbuun's fork required the +2 pool size fix from PR fix: account for TurboQuant rotation tensors in KV cache context pool #1 to avoid crash on turbo cache init

TheTom added a commit that referenced this pull request Mar 27, 2026
Complete experiment log:
  #1  4-mag LUT:           15.1 at 8K (BEST, +38%)
  #2  Batched extract:     13.7 (+25%)
  #3  Inline FA block:     13.5 (I-cache pressure)
  #4  Deferred norm:       12.9 (loses ILP)
  #5  2-pair half2:        12.0 (ternary overhead)
  #6  Select chain:        11.9 (branches kill)
  #7  Bit-arithmetic:      11.6 (ALU too heavy)
  #8  FMA branchless:      11.4 (ALU still too heavy)
  #9  Named-reg ternary:   10.3 (branches worst)
  #10 Main (8-LUT):        10.95 (baseline)
  #11 Non-vec FA:          10.2 (wrong kernel)
  Ceiling:                 24.5 (no dequant)

Apple8 hardware truth:
  1 divergent constant read < 7 ALU ops (even with fma)
  Branches cost MORE than divergent constant reads
  Array indexing ALWAYS spills on Metal
  4 constant addresses is the sweet spot

The 4-mag LUT is the dequant-level ceiling on Apple Silicon.

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

TheTom commented Mar 27, 2026

Copy link
Copy Markdown
Owner

thanks for tackling all three bugs from #29 plus the stack overflow catch. the turbo4 kernel split and tail-block ceiling division look right to me. will pull this down and test locally on M5 Max this afternoon to verify no regressions on turbo3 (PPL + NIAH + speed) before merging. the Ampere numbers from @spiritbuun fork are great to have too.

@TheTom

TheTom commented Mar 27, 2026

Copy link
Copy Markdown
Owner

Test Results — M5 Max 128GB, Qwen3.5-35B-A3B Q8_0

Build: Clean compile, no warnings.

turbo3 (regression check)

  • PPL: 6.1756 ± 0.330 — identical to main branch ✅
  • Decode: no regression ✅
  • PR does not touch the turbo3 code path (separate kernel_set_rows_turbo3 now)

turbo4

  • PPL: 6.3823 ± 0.345 (4.4% above q8_0 baseline of 6.111)
  • Decode-only (-p 0 -n 128): 42.68 tok/s ✅
  • End-to-end generate: prefill FA kernels for turbo4 were missing (pre-existing, not this PR). Added non-vec prefill kernel instantiations locally to test — turbo4 runs but PPL is elevated. Needs further investigation.

Code review

  • SET_ROWS kernel split: correct, turbo4 has proper 3-bit PolarQuant + QJL packing ✅
  • Tail-block ceiling division: correct fix for non-128-aligned head dims ✅
  • TURBO_D → TURBO_ROT_DIM + static_assert: clean ✅
  • Stack overflow fix: correct, turbo_init_rotation() no longer allocates 64KB on stack ✅

Recommendation

Good to merge — turbo3 has zero regression risk and the fixes are correct. However, turbo4 needs more testing before recommending it for use. The elevated PPL and missing prefill kernels are pre-existing issues, not introduced by this PR.

Recommendation: stay on turbo3 for now. turbo4 end-to-end validation (prefill FA kernels, quality investigation) tracked separately.

@TheTom
TheTom merged commit 065ef53 into TheTom:feature/turboquant-kv-cache Mar 27, 2026
TheTom added a commit that referenced this pull request Mar 27, 2026
…che"

This reverts commit 065ef53, reversing
changes made to 7d1bd95.
@TheTom

TheTom commented Mar 27, 2026

Copy link
Copy Markdown
Owner

⚠️ REVERTED — turbo3 regression found

During extended validation, discovered that PR #4 breaks turbo3 on Metal:

State turbo3 PPL (c=512, 8ch)
Pre-merge (7d1bd95) 6.1756 ✅
Post-merge (065ef53) 181.5955 ❌
Post-revert (a52586e) 6.1756 ✅

The kernel split from the shared kernel_set_rows_turbo template into separate kernel_set_rows_turbo3 / kernel_set_rows_turbo4 functions introduced a regression in the turbo3 quantization path. The q8_0 baseline is unaffected (5.46-6.03 across all context lengths), confirming this is turbo3-specific.

Merge reverted in a52586e. The turbo4 fixes and stack overflow fix are good — the issue is specifically in the turbo3 kernel split. Likely a subtle difference in the template parameters or quantization logic when moving from the shared template to the dedicated function.

Happy to help debug the turbo3 path if you want to resubmit.

Madreag pushed a commit to Madreag/turbo3-cuda that referenced this pull request Mar 28, 2026
* FlashAttention (TheTom#13)

* Add inplace softmax

* Move rms_norm to split row approach

* Update debug for supports_op

* clean up debug statements

* neg f16xf32xip builds and runs, havent actually ran a model that uses neg kernel yet though

* neg passes backend test

* unary operators pass ggml tests

* rms_norm double declaration bug atoned

* abides by editor-config

* removed vestigial files

* fixed autoconfig

* All operators (inlcluding xielu) working

* removed unnecesarry checking if node->src[1] exists for unary operators

* responded and dealt with PR comments

* implemented REPL_Template support and removed bug in unary operators kernel

* formatted embed wgsl and ggml-webgpu.cpp

* Faster tensors (TheTom#8)

Add fast matrix and matrix/vector multiplication.

* Use map for shader replacements instead of pair of strings

* Wasm (TheTom#9)

* webgpu : fix build on emscripten

* more debugging stuff

* test-backend-ops: force single thread on wasm

* fix single-thread case for init_tensor_uniform

* use jspi

* add pthread

* test: remember to set n_thread for cpu backend

* Add buffer label and enable dawn-specific toggles to turn off some checks

* Intermediate state

* Fast working f16/f32 vec4

* Working float fast mul mat

* Clean up naming of mul_mat to match logical model, start work on q mul_mat

* Setup for subgroup matrix mat mul

* Basic working subgroup matrix

* Working subgroup matrix tiling

* Handle weirder sg matrix sizes (but still % sg matrix size)

* Working start to gemv

* working f16 accumulation with shared memory staging

* Print out available subgroup matrix configurations

* Vectorize dst stores for sg matrix shader

* Gemv working scalar

* Minor set_rows optimization (TheTom#4)

* updated optimization, fixed errors

* non vectorized version now dispatches one thread per element

* Simplify

* Change logic for set_rows pipelines

---------

Co-authored-by: Neha Abbas <[email protected]>
Co-authored-by: Neha Abbas <[email protected]>
Co-authored-by: Reese Levine <[email protected]>

* Comment on dawn toggles

* Working subgroup matrix code for (semi)generic sizes

* Remove some comments

* Cleanup code

* Update dawn version and move to portable subgroup size

* Try to fix new dawn release

* Update subgroup size comment

* Only check for subgroup matrix configs if they are supported

* Add toggles for subgroup matrix/f16 support on nvidia+vulkan

* Make row/col naming consistent

* Refactor shared memory loading

* Move sg matrix stores to correct file

* Working q4_0

* Formatting

* Work with emscripten builds

* Fix test-backend-ops emscripten for f16/quantized types

* Use emscripten memory64 to support get_memory

* Add build flags and try ci

---------

Co-authored-by: Xuan Son Nguyen <[email protected]>

* Remove extra whitespace

* Move wasm single-thread logic out of test-backend-ops for cpu backend

* Disable multiple threads for emscripten single-thread builds in ggml_graph_plan

* Refactored pipelines and workgroup calculations (TheTom#10)

* refactored pipelines

* refactored workgroup calculation

* removed commented out block of prior maps

* Clean up ceiling division pattern

---------

Co-authored-by: Neha Abbas <[email protected]>
Co-authored-by: Reese Levine <[email protected]>

* Start work on flash attention

* Shader structure set up (many bugs still)

* debugging

* Working first test

* Working with head grouping, head sizes to 128, logit softcap, mask/sinks enabled, f32

* Generalize softmax to work with multiple subgroups, f16 accumulation, mask shared memory tiling

* Start work on integrating pre-wgsl

* Separate structs/initial shader compilation library into separate files

* Work on compilation choices for flashattention

* Work on subgroup matrix/tile size portability

* subgroup size agnostic online softmax

* Cleanups, quantization types

* more cleanup

* fix wasm build

* Refactor flashattention to increase parallelism, use direct loads for KV in somce cases

* Checkpoint

* formatting

* Update to account for default kv cache padding

* formatting shader

* Add workflow for ggml-ci webgpu

* Try passing absolute path to dawn in ggml-ci

* Avoid error on device destruction, add todos for proper cleanup

* Fix unused warning

* Forgot one parameter unused

* Move some flashattn computation to f32 for correctness
aminya pushed a commit to aminya/llama-cpp-turboquant that referenced this pull request Mar 29, 2026
Add GGML_API to turbo quantize_row declarations in ggml-cpu/quants.h
to match ggml-quants.h. MSVC requires consistent __declspec linkage
when the same symbol is declared across compilation units.

Closes TheTom#4

Co-Authored-By: Claude Opus 4.6 <[email protected]>
TheTom added a commit that referenced this pull request Apr 2, 2026
Complete experiment log:
  #1  4-mag LUT:           15.1 at 8K (BEST, +38%)
  #2  Batched extract:     13.7 (+25%)
  #3  Inline FA block:     13.5 (I-cache pressure)
  #4  Deferred norm:       12.9 (loses ILP)
  #5  2-pair half2:        12.0 (ternary overhead)
  #6  Select chain:        11.9 (branches kill)
  #7  Bit-arithmetic:      11.6 (ALU too heavy)
  #8  FMA branchless:      11.4 (ALU still too heavy)
  #9  Named-reg ternary:   10.3 (branches worst)
  #10 Main (8-LUT):        10.95 (baseline)
  #11 Non-vec FA:          10.2 (wrong kernel)
  Ceiling:                 24.5 (no dequant)

Apple8 hardware truth:
  1 divergent constant read < 7 ALU ops (even with fma)
  Branches cost MORE than divergent constant reads
  Array indexing ALWAYS spills on Metal
  4 constant addresses is the sweet spot

The 4-mag LUT is the dequant-level ceiling on Apple Silicon.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: [email protected]
TheTom added a commit that referenced this pull request Apr 2, 2026
…che"

This reverts commit 065ef53, reversing
changes made to 7d1bd95.
TheTom added a commit that referenced this pull request Apr 2, 2026
Complete experiment log:
  #1  4-mag LUT:           15.1 at 8K (BEST, +38%)
  #2  Batched extract:     13.7 (+25%)
  #3  Inline FA block:     13.5 (I-cache pressure)
  #4  Deferred norm:       12.9 (loses ILP)
  #5  2-pair half2:        12.0 (ternary overhead)
  #6  Select chain:        11.9 (branches kill)
  #7  Bit-arithmetic:      11.6 (ALU too heavy)
  #8  FMA branchless:      11.4 (ALU still too heavy)
  #9  Named-reg ternary:   10.3 (branches worst)
  #10 Main (8-LUT):        10.95 (baseline)
  #11 Non-vec FA:          10.2 (wrong kernel)
  Ceiling:                 24.5 (no dequant)

Apple8 hardware truth:
  1 divergent constant read < 7 ALU ops (even with fma)
  Branches cost MORE than divergent constant reads
  Array indexing ALWAYS spills on Metal
  4 constant addresses is the sweet spot

The 4-mag LUT is the dequant-level ceiling on Apple Silicon.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: [email protected]
TheTom added a commit that referenced this pull request Apr 2, 2026
…che"

This reverts commit 065ef53, reversing
changes made to 7d1bd95.
iamwavecut pushed a commit to iamwavecut/llama-cpp-turboquant that referenced this pull request Apr 8, 2026
Complete experiment log:
  TheTom#1  4-mag LUT:           15.1 at 8K (BEST, +38%)
  TheTom#2  Batched extract:     13.7 (+25%)
  TheTom#3  Inline FA block:     13.5 (I-cache pressure)
  TheTom#4  Deferred norm:       12.9 (loses ILP)
  TheTom#5  2-pair half2:        12.0 (ternary overhead)
  TheTom#6  Select chain:        11.9 (branches kill)
  TheTom#7  Bit-arithmetic:      11.6 (ALU too heavy)
  TheTom#8  FMA branchless:      11.4 (ALU still too heavy)
  TheTom#9  Named-reg ternary:   10.3 (branches worst)
  TheTom#10 Main (8-LUT):        10.95 (baseline)
  TheTom#11 Non-vec FA:          10.2 (wrong kernel)
  Ceiling:                 24.5 (no dequant)

Apple8 hardware truth:
  1 divergent constant read < 7 ALU ops (even with fma)
  Branches cost MORE than divergent constant reads
  Array indexing ALWAYS spills on Metal
  4 constant addresses is the sweet spot

The 4-mag LUT is the dequant-level ceiling on Apple Silicon.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: [email protected]
iamwavecut pushed a commit to iamwavecut/llama-cpp-turboquant that referenced this pull request Apr 8, 2026
…-kv-cache"

This reverts commit 065ef53, reversing
changes made to 7d1bd95.
KGardevoir pushed a commit to KGardevoir/llama-cpp-turboquant that referenced this pull request Apr 14, 2026
Complete experiment log:
  #1  4-mag LUT:           15.1 at 8K (BEST, +38%)
  TheTom#2  Batched extract:     13.7 (+25%)
  TheTom#3  Inline FA block:     13.5 (I-cache pressure)
  TheTom#4  Deferred norm:       12.9 (loses ILP)
  TheTom#5  2-pair half2:        12.0 (ternary overhead)
  TheTom#6  Select chain:        11.9 (branches kill)
  TheTom#7  Bit-arithmetic:      11.6 (ALU too heavy)
  TheTom#8  FMA branchless:      11.4 (ALU still too heavy)
  TheTom#9  Named-reg ternary:   10.3 (branches worst)
  TheTom#10 Main (8-LUT):        10.95 (baseline)
  TheTom#11 Non-vec FA:          10.2 (wrong kernel)
  Ceiling:                 24.5 (no dequant)

Apple8 hardware truth:
  1 divergent constant read < 7 ALU ops (even with fma)
  Branches cost MORE than divergent constant reads
  Array indexing ALWAYS spills on Metal
  4 constant addresses is the sweet spot

The 4-mag LUT is the dequant-level ceiling on Apple Silicon.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: [email protected]
TheTom added a commit that referenced this pull request Apr 15, 2026
Complete experiment log:
  #1  4-mag LUT:           15.1 at 8K (BEST, +38%)
  #2  Batched extract:     13.7 (+25%)
  #3  Inline FA block:     13.5 (I-cache pressure)
  #4  Deferred norm:       12.9 (loses ILP)
  #5  2-pair half2:        12.0 (ternary overhead)
  #6  Select chain:        11.9 (branches kill)
  #7  Bit-arithmetic:      11.6 (ALU too heavy)
  #8  FMA branchless:      11.4 (ALU still too heavy)
  #9  Named-reg ternary:   10.3 (branches worst)
  #10 Main (8-LUT):        10.95 (baseline)
  #11 Non-vec FA:          10.2 (wrong kernel)
  Ceiling:                 24.5 (no dequant)

Apple8 hardware truth:
  1 divergent constant read < 7 ALU ops (even with fma)
  Branches cost MORE than divergent constant reads
  Array indexing ALWAYS spills on Metal
  4 constant addresses is the sweet spot

The 4-mag LUT is the dequant-level ceiling on Apple Silicon.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: [email protected]
TheTom added a commit that referenced this pull request Apr 15, 2026
…che"

This reverts commit 065ef53, reversing
changes made to 7d1bd95.
LogicDaemon pushed a commit to LogicDaemon/llama-cpp-turboquant that referenced this pull request May 27, 2026
Complete experiment log:
  TheTom#1  4-mag LUT:           15.1 at 8K (BEST, +38%)
  TheTom#2  Batched extract:     13.7 (+25%)
  TheTom#3  Inline FA block:     13.5 (I-cache pressure)
  TheTom#4  Deferred norm:       12.9 (loses ILP)
  TheTom#5  2-pair half2:        12.0 (ternary overhead)
  TheTom#6  Select chain:        11.9 (branches kill)
  TheTom#7  Bit-arithmetic:      11.6 (ALU too heavy)
  TheTom#8  FMA branchless:      11.4 (ALU still too heavy)
  TheTom#9  Named-reg ternary:   10.3 (branches worst)
  TheTom#10 Main (8-LUT):        10.95 (baseline)
  TheTom#11 Non-vec FA:          10.2 (wrong kernel)
  Ceiling:                 24.5 (no dequant)

Apple8 hardware truth:
  1 divergent constant read < 7 ALU ops (even with fma)
  Branches cost MORE than divergent constant reads
  Array indexing ALWAYS spills on Metal
  4 constant addresses is the sweet spot

The 4-mag LUT is the dequant-level ceiling on Apple Silicon.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: [email protected]
LogicDaemon pushed a commit to LogicDaemon/llama-cpp-turboquant that referenced this pull request May 27, 2026
…-kv-cache"

This reverts commit 065ef53, reversing
changes made to 7d1bd95.
wel97459 pushed a commit to wel97459/llama-cpp-turboquant that referenced this pull request Jun 4, 2026
Complete experiment log:
  TheTom#1  4-mag LUT:           15.1 at 8K (BEST, +38%)
  TheTom#2  Batched extract:     13.7 (+25%)
  TheTom#3  Inline FA block:     13.5 (I-cache pressure)
  TheTom#4  Deferred norm:       12.9 (loses ILP)
  TheTom#5  2-pair half2:        12.0 (ternary overhead)
  TheTom#6  Select chain:        11.9 (branches kill)
  TheTom#7  Bit-arithmetic:      11.6 (ALU too heavy)
  TheTom#8  FMA branchless:      11.4 (ALU still too heavy)
  TheTom#9  Named-reg ternary:   10.3 (branches worst)
  TheTom#10 Main (8-LUT):        10.95 (baseline)
  TheTom#11 Non-vec FA:          10.2 (wrong kernel)
  Ceiling:                 24.5 (no dequant)

Apple8 hardware truth:
  1 divergent constant read < 7 ALU ops (even with fma)
  Branches cost MORE than divergent constant reads
  Array indexing ALWAYS spills on Metal
  4 constant addresses is the sweet spot

The 4-mag LUT is the dequant-level ceiling on Apple Silicon.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: [email protected]
wel97459 pushed a commit to wel97459/llama-cpp-turboquant that referenced this pull request Jun 4, 2026
…-kv-cache"

This reverts commit 065ef53, reversing
changes made to 7d1bd95.
KGardevoir pushed a commit to KGardevoir/llama-cpp-turboquant that referenced this pull request Jun 16, 2026
Complete experiment log:
  #1  4-mag LUT:           15.1 at 8K (BEST, +38%)
  TheTom#2  Batched extract:     13.7 (+25%)
  TheTom#3  Inline FA block:     13.5 (I-cache pressure)
  TheTom#4  Deferred norm:       12.9 (loses ILP)
  TheTom#5  2-pair half2:        12.0 (ternary overhead)
  TheTom#6  Select chain:        11.9 (branches kill)
  TheTom#7  Bit-arithmetic:      11.6 (ALU too heavy)
  TheTom#8  FMA branchless:      11.4 (ALU still too heavy)
  TheTom#9  Named-reg ternary:   10.3 (branches worst)
  TheTom#10 Main (8-LUT):        10.95 (baseline)
  TheTom#11 Non-vec FA:          10.2 (wrong kernel)
  Ceiling:                 24.5 (no dequant)

Apple8 hardware truth:
  1 divergent constant read < 7 ALU ops (even with fma)
  Branches cost MORE than divergent constant reads
  Array indexing ALWAYS spills on Metal
  4 constant addresses is the sweet spot

The 4-mag LUT is the dequant-level ceiling on Apple Silicon.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: [email protected]
KGardevoir pushed a commit to KGardevoir/llama-cpp-turboquant that referenced this pull request Jun 16, 2026
…-kv-cache"

This reverts commit 065ef53, reversing
changes made to 7d1bd95.
aureliahazel93-commits added a commit to aureliahazel93-commits/llama-cpp-turboquant that referenced this pull request Jul 8, 2026
crusaderky pushed a commit to crusaderky/llama.cpp that referenced this pull request Aug 10, 2026
* Get started with Onyx

* Add architecture

* Skip keys handled in super()

* Loading tensors

* Shorten

* Graph

* Apply suggestion from @pcuenca

* Remove norm now embedding in transformers weights

* Add eot

* Explicit output_multiplier

* Handle post_norm_eps

* No super call; unhardcode eot.

The pattern `self._set_vocab_gpt2()` seems preferred throughout the
codebase, and it allows `set_vocab()` to be called from a different part
of the Python class hierarchy: the drafter model converter that we may
need eventually.

* Register for drafting

* DFlash: inherit rope type from the linked target.

Another option would be to store it in the gguf file itself.

* mmproj conversion

Note: some fields to be renamed after the implementation works. We are
keeping compatibility with the reference Meta gguf for testing purposes.

* "clip" header declarations

* Load mmproj

* Pre-processing

* Graph

* Go back to using delimiters.

Otherwise our generations are worse.

Transformers does not use them. We need to trace inputs to verify
whether they are equivalent.

* downsample_factor -> merge_size

* Add vision graph

lol, forgot from a previous commit

* Additional renames, align with llama.cpp / transformers

* Prefer _size instead of independent _h and _w

* Fix token layout

Co-authored-by: Young Han <[email protected]>

* onyx: bring the chat parser onto the onyx branch

common/chat.cpp on this branch has no Onyx handling, so a converted model
serves malformed chat: the assistant preamble leaks into content
("to=self<|message|>...") and tool calls fail with

    HTTP 500 "The model produced output that does not match the expected
              peg-native format"

common_chat_params_init_onyx exists on onyx-fair-patch, added there by
8bb73dd3d. It was never on this branch, so this is not a regression --
the two lines developed independently.

The code here is taken verbatim from that commit. It is the clean side of
`git merge origin/onyx-fair-patch`: chat.cpp is one of the files that
merges without conflict. The full merge is not viable -- it produces 13
conflicts, including add/add on conversion/onyx.py and src/models/onyx.cpp
where the q_norm-folding and metadata-scale approaches contradict each
other, and TheTom#4/TheTom#7 are stacked on this branch's side of that.

Verified on this branch: builds with 0 errors, converts an Onyx checkpoint,
and serving it gives "4" for "What is 2+2?" plus a correct
get_weather {"city":"Paris"} tool call, where the unported branch gives the
two failures above.

No converter or runtime changes are included, so this should not interact
with the q_norm work.

Co-authored-by: Beto de Paola <[email protected]>

* Less params, bilinear pos-emb interpolation as a graph op instead of CPU

* Map to symbolic V_MMPROJ instead of strings

* Make a couple params explicit

* Patchify via build_inp()

* No param for rope_theta

* Small cleanup

* Restore blank line

* Unpermute, to adapt to the latest transformers checkpoint

* Apply norm after token embeddings

This follows the latest transformers approach.

* Remove duplicated function

* build_vit

* onyx: use the model rope theta on sliding-window layers

* DFlash: conversion from transformers drafter

* Revert rope_type derivation from target

NOTE: this breaks compatibility with Meta's distributed DFlash GGUFs, as
the Q/K are stored in "NEOX" (rotated half) format, like in
transformers.

* Apply suggestion from @pcuenca

* Set model type

* Remove comment that will become obsolete

* Hardcode post_norm_rms_eps instead of new param

* Derive SWA+RoPE pattern from gguf array or scalar

* Fix model type <-> number of layers

* Reorder

* Rename

* Fix typo

* DFlash: seed the draft KV cache from multimodal embedding batches

`common_speculative_impl_draft_dflash::process()` returned early on any batch carrying embeddings, so an image prefill never had its target-layer features fused through the DFlash encoder and injected into the draft's KV cache. That left a hole spanning the image's positions, and the next injection at a post-image position failed to initialize its batch:

```
decoding image batch 1/1, n_tokens_batch = 256
decode: failed to initialize batch
llama_decode: failed to decode, ret = -1
process: llama_decode(ctx_dft) failed rc=-1 (n_tokens=17, offset=0)
srv decode: failed to process speculative batch
```

Every image request with `--spec-type draft-dflash` failed with HTTP 500. Text-only was unaffected, since those batches carry token ids and were let through.

Restore the earlier condition, which admits a batch that is either tokens or embeddings and skips only the degenerate neither/both cases. The rest of `process()` is already layout-agnostic -- it gathers features via `llama_get_embeddings_layer_inp()` and indexes `batch_in.pos[]` / `batch_in.seq_id[]`, none of which assume token ids -- so this is the whole fix.

Validated against `muse-glimmer-30B-bf16.gguf` + `mmproj-muse-glimmer-30B-bf16.gguf` + a DFlash draft head, on an image describe-the-shapes request:

- before: HTTP 500, `failed to process speculative batch`
- after: HTTP 200, draft acceptance 0.34012 (167 accepted / 491 generated), mean len 3.04

Output equivalence holds, which is the property that matters: at temperature 0 the drafted response is byte-identical to the same request served with no draft attached (1213/1213 chars), so the draft is drafting correctly through the image context rather than merely not crashing.

* Conversion: prefer rewrite to mapping

* Revert "Conversion: prefer rewrite to mapping"

This reverts commit a92d0ac.

* fix lint

* sliding_window metadata is not optional

* disable state save/load

* Apply suggestion from @pcuenca

---------

Co-authored-by: Young Han <[email protected]>
Co-authored-by: Beto de Paola <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: ruanrms <[email protected]>
Co-authored-by: Xuan Son Nguyen <[email protected]>
Co-authored-by: Sigbjørn Skjæret <[email protected]>
TheTom added a commit that referenced this pull request Aug 10, 2026
* Get started with Onyx

* Add architecture

* Skip keys handled in super()

* Loading tensors

* Shorten

* Graph

* Apply suggestion from @pcuenca

* Remove norm now embedding in transformers weights

* Add eot

* Explicit output_multiplier

* Handle post_norm_eps

* No super call; unhardcode eot.

The pattern `self._set_vocab_gpt2()` seems preferred throughout the
codebase, and it allows `set_vocab()` to be called from a different part
of the Python class hierarchy: the drafter model converter that we may
need eventually.

* Register for drafting

* DFlash: inherit rope type from the linked target.

Another option would be to store it in the gguf file itself.

* mmproj conversion

Note: some fields to be renamed after the implementation works. We are
keeping compatibility with the reference Meta gguf for testing purposes.

* "clip" header declarations

* Load mmproj

* Pre-processing

* Graph

* Go back to using delimiters.

Otherwise our generations are worse.

Transformers does not use them. We need to trace inputs to verify
whether they are equivalent.

* downsample_factor -> merge_size

* Add vision graph

lol, forgot from a previous commit

* Additional renames, align with llama.cpp / transformers

* Prefer _size instead of independent _h and _w

* Fix token layout



* onyx: bring the chat parser onto the onyx branch

common/chat.cpp on this branch has no Onyx handling, so a converted model
serves malformed chat: the assistant preamble leaks into content
("to=self<|message|>...") and tool calls fail with

    HTTP 500 "The model produced output that does not match the expected
              peg-native format"

common_chat_params_init_onyx exists on onyx-fair-patch, added there by
8bb73dd3d. It was never on this branch, so this is not a regression --
the two lines developed independently.

The code here is taken verbatim from that commit. It is the clean side of
`git merge origin/onyx-fair-patch`: chat.cpp is one of the files that
merges without conflict. The full merge is not viable -- it produces 13
conflicts, including add/add on conversion/onyx.py and src/models/onyx.cpp
where the q_norm-folding and metadata-scale approaches contradict each
other, and #4/#7 are stacked on this branch's side of that.

Verified on this branch: builds with 0 errors, converts an Onyx checkpoint,
and serving it gives "4" for "What is 2+2?" plus a correct
get_weather {"city":"Paris"} tool call, where the unported branch gives the
two failures above.

No converter or runtime changes are included, so this should not interact
with the q_norm work.



* Less params, bilinear pos-emb interpolation as a graph op instead of CPU

* Map to symbolic V_MMPROJ instead of strings

* Make a couple params explicit

* Patchify via build_inp()

* No param for rope_theta

* Small cleanup

* Restore blank line

* Unpermute, to adapt to the latest transformers checkpoint

* Apply norm after token embeddings

This follows the latest transformers approach.

* Remove duplicated function

* build_vit

* onyx: use the model rope theta on sliding-window layers

* DFlash: conversion from transformers drafter

* Revert rope_type derivation from target

NOTE: this breaks compatibility with Meta's distributed DFlash GGUFs, as
the Q/K are stored in "NEOX" (rotated half) format, like in
transformers.

* Apply suggestion from @pcuenca

* Set model type

* Remove comment that will become obsolete

* Hardcode post_norm_rms_eps instead of new param

* Derive SWA+RoPE pattern from gguf array or scalar

* Fix model type <-> number of layers

* Reorder

* Rename

* Fix typo

* DFlash: seed the draft KV cache from multimodal embedding batches

`common_speculative_impl_draft_dflash::process()` returned early on any batch carrying embeddings, so an image prefill never had its target-layer features fused through the DFlash encoder and injected into the draft's KV cache. That left a hole spanning the image's positions, and the next injection at a post-image position failed to initialize its batch:

```
decoding image batch 1/1, n_tokens_batch = 256
decode: failed to initialize batch
llama_decode: failed to decode, ret = -1
process: llama_decode(ctx_dft) failed rc=-1 (n_tokens=17, offset=0)
srv decode: failed to process speculative batch
```

Every image request with `--spec-type draft-dflash` failed with HTTP 500. Text-only was unaffected, since those batches carry token ids and were let through.

Restore the earlier condition, which admits a batch that is either tokens or embeddings and skips only the degenerate neither/both cases. The rest of `process()` is already layout-agnostic -- it gathers features via `llama_get_embeddings_layer_inp()` and indexes `batch_in.pos[]` / `batch_in.seq_id[]`, none of which assume token ids -- so this is the whole fix.

Validated against `muse-glimmer-30B-bf16.gguf` + `mmproj-muse-glimmer-30B-bf16.gguf` + a DFlash draft head, on an image describe-the-shapes request:

- before: HTTP 500, `failed to process speculative batch`
- after: HTTP 200, draft acceptance 0.34012 (167 accepted / 491 generated), mean len 3.04

Output equivalence holds, which is the property that matters: at temperature 0 the drafted response is byte-identical to the same request served with no draft attached (1213/1213 chars), so the draft is drafting correctly through the image context rather than merely not crashing.

* Conversion: prefer rewrite to mapping

* Revert "Conversion: prefer rewrite to mapping"

This reverts commit a92d0ac.

* fix lint

* sliding_window metadata is not optional

* disable state save/load

* Apply suggestion from @pcuenca

---------

Co-authored-by: Pedro Cuenca <[email protected]>
Co-authored-by: Young Han <[email protected]>
Co-authored-by: Beto de Paola <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: ruanrms <[email protected]>
Co-authored-by: Xuan Son Nguyen <[email protected]>
Co-authored-by: Sigbjørn Skjæret <[email protected]>
LogicDaemon pushed a commit to LogicDaemon/llama-cpp-turboquant that referenced this pull request Aug 12, 2026
* Get started with Onyx

* Add architecture

* Skip keys handled in super()

* Loading tensors

* Shorten

* Graph

* Apply suggestion from @pcuenca

* Remove norm now embedding in transformers weights

* Add eot

* Explicit output_multiplier

* Handle post_norm_eps

* No super call; unhardcode eot.

The pattern `self._set_vocab_gpt2()` seems preferred throughout the
codebase, and it allows `set_vocab()` to be called from a different part
of the Python class hierarchy: the drafter model converter that we may
need eventually.

* Register for drafting

* DFlash: inherit rope type from the linked target.

Another option would be to store it in the gguf file itself.

* mmproj conversion

Note: some fields to be renamed after the implementation works. We are
keeping compatibility with the reference Meta gguf for testing purposes.

* "clip" header declarations

* Load mmproj

* Pre-processing

* Graph

* Go back to using delimiters.

Otherwise our generations are worse.

Transformers does not use them. We need to trace inputs to verify
whether they are equivalent.

* downsample_factor -> merge_size

* Add vision graph

lol, forgot from a previous commit

* Additional renames, align with llama.cpp / transformers

* Prefer _size instead of independent _h and _w

* Fix token layout

Co-authored-by: Young Han <[email protected]>

* onyx: bring the chat parser onto the onyx branch

common/chat.cpp on this branch has no Onyx handling, so a converted model
serves malformed chat: the assistant preamble leaks into content
("to=self<|message|>...") and tool calls fail with

    HTTP 500 "The model produced output that does not match the expected
              peg-native format"

common_chat_params_init_onyx exists on onyx-fair-patch, added there by
8bb73dd3d. It was never on this branch, so this is not a regression --
the two lines developed independently.

The code here is taken verbatim from that commit. It is the clean side of
`git merge origin/onyx-fair-patch`: chat.cpp is one of the files that
merges without conflict. The full merge is not viable -- it produces 13
conflicts, including add/add on conversion/onyx.py and src/models/onyx.cpp
where the q_norm-folding and metadata-scale approaches contradict each
other, and TheTom#4/TheTom#7 are stacked on this branch's side of that.

Verified on this branch: builds with 0 errors, converts an Onyx checkpoint,
and serving it gives "4" for "What is 2+2?" plus a correct
get_weather {"city":"Paris"} tool call, where the unported branch gives the
two failures above.

No converter or runtime changes are included, so this should not interact
with the q_norm work.

Co-authored-by: Beto de Paola <[email protected]>

* Less params, bilinear pos-emb interpolation as a graph op instead of CPU

* Map to symbolic V_MMPROJ instead of strings

* Make a couple params explicit

* Patchify via build_inp()

* No param for rope_theta

* Small cleanup

* Restore blank line

* Unpermute, to adapt to the latest transformers checkpoint

* Apply norm after token embeddings

This follows the latest transformers approach.

* Remove duplicated function

* build_vit

* onyx: use the model rope theta on sliding-window layers

* DFlash: conversion from transformers drafter

* Revert rope_type derivation from target

NOTE: this breaks compatibility with Meta's distributed DFlash GGUFs, as
the Q/K are stored in "NEOX" (rotated half) format, like in
transformers.

* Apply suggestion from @pcuenca

* Set model type

* Remove comment that will become obsolete

* Hardcode post_norm_rms_eps instead of new param

* Derive SWA+RoPE pattern from gguf array or scalar

* Fix model type <-> number of layers

* Reorder

* Rename

* Fix typo

* DFlash: seed the draft KV cache from multimodal embedding batches

`common_speculative_impl_draft_dflash::process()` returned early on any batch carrying embeddings, so an image prefill never had its target-layer features fused through the DFlash encoder and injected into the draft's KV cache. That left a hole spanning the image's positions, and the next injection at a post-image position failed to initialize its batch:

```
decoding image batch 1/1, n_tokens_batch = 256
decode: failed to initialize batch
llama_decode: failed to decode, ret = -1
process: llama_decode(ctx_dft) failed rc=-1 (n_tokens=17, offset=0)
srv decode: failed to process speculative batch
```

Every image request with `--spec-type draft-dflash` failed with HTTP 500. Text-only was unaffected, since those batches carry token ids and were let through.

Restore the earlier condition, which admits a batch that is either tokens or embeddings and skips only the degenerate neither/both cases. The rest of `process()` is already layout-agnostic -- it gathers features via `llama_get_embeddings_layer_inp()` and indexes `batch_in.pos[]` / `batch_in.seq_id[]`, none of which assume token ids -- so this is the whole fix.

Validated against `muse-glimmer-30B-bf16.gguf` + `mmproj-muse-glimmer-30B-bf16.gguf` + a DFlash draft head, on an image describe-the-shapes request:

- before: HTTP 500, `failed to process speculative batch`
- after: HTTP 200, draft acceptance 0.34012 (167 accepted / 491 generated), mean len 3.04

Output equivalence holds, which is the property that matters: at temperature 0 the drafted response is byte-identical to the same request served with no draft attached (1213/1213 chars), so the draft is drafting correctly through the image context rather than merely not crashing.

* Conversion: prefer rewrite to mapping

* Revert "Conversion: prefer rewrite to mapping"

This reverts commit a92d0ac.

* fix lint

* sliding_window metadata is not optional

* disable state save/load

* Apply suggestion from @pcuenca

---------

Co-authored-by: Young Han <[email protected]>
Co-authored-by: Beto de Paola <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: ruanrms <[email protected]>
Co-authored-by: Xuan Son Nguyen <[email protected]>
Co-authored-by: Sigbjørn Skjæret <[email protected]>
crusaderky pushed a commit to crusaderky/llama.cpp that referenced this pull request Aug 12, 2026
* Get started with Onyx

* Add architecture

* Skip keys handled in super()

* Loading tensors

* Shorten

* Graph

* Apply suggestion from @pcuenca

* Remove norm now embedding in transformers weights

* Add eot

* Explicit output_multiplier

* Handle post_norm_eps

* No super call; unhardcode eot.

The pattern `self._set_vocab_gpt2()` seems preferred throughout the
codebase, and it allows `set_vocab()` to be called from a different part
of the Python class hierarchy: the drafter model converter that we may
need eventually.

* Register for drafting

* DFlash: inherit rope type from the linked target.

Another option would be to store it in the gguf file itself.

* mmproj conversion

Note: some fields to be renamed after the implementation works. We are
keeping compatibility with the reference Meta gguf for testing purposes.

* "clip" header declarations

* Load mmproj

* Pre-processing

* Graph

* Go back to using delimiters.

Otherwise our generations are worse.

Transformers does not use them. We need to trace inputs to verify
whether they are equivalent.

* downsample_factor -> merge_size

* Add vision graph

lol, forgot from a previous commit

* Additional renames, align with llama.cpp / transformers

* Prefer _size instead of independent _h and _w

* Fix token layout

Co-authored-by: Young Han <[email protected]>

* onyx: bring the chat parser onto the onyx branch

common/chat.cpp on this branch has no Onyx handling, so a converted model
serves malformed chat: the assistant preamble leaks into content
("to=self<|message|>...") and tool calls fail with

    HTTP 500 "The model produced output that does not match the expected
              peg-native format"

common_chat_params_init_onyx exists on onyx-fair-patch, added there by
8bb73dd3d. It was never on this branch, so this is not a regression --
the two lines developed independently.

The code here is taken verbatim from that commit. It is the clean side of
`git merge origin/onyx-fair-patch`: chat.cpp is one of the files that
merges without conflict. The full merge is not viable -- it produces 13
conflicts, including add/add on conversion/onyx.py and src/models/onyx.cpp
where the q_norm-folding and metadata-scale approaches contradict each
other, and TheTom#4/TheTom#7 are stacked on this branch's side of that.

Verified on this branch: builds with 0 errors, converts an Onyx checkpoint,
and serving it gives "4" for "What is 2+2?" plus a correct
get_weather {"city":"Paris"} tool call, where the unported branch gives the
two failures above.

No converter or runtime changes are included, so this should not interact
with the q_norm work.

Co-authored-by: Beto de Paola <[email protected]>

* Less params, bilinear pos-emb interpolation as a graph op instead of CPU

* Map to symbolic V_MMPROJ instead of strings

* Make a couple params explicit

* Patchify via build_inp()

* No param for rope_theta

* Small cleanup

* Restore blank line

* Unpermute, to adapt to the latest transformers checkpoint

* Apply norm after token embeddings

This follows the latest transformers approach.

* Remove duplicated function

* build_vit

* onyx: use the model rope theta on sliding-window layers

* DFlash: conversion from transformers drafter

* Revert rope_type derivation from target

NOTE: this breaks compatibility with Meta's distributed DFlash GGUFs, as
the Q/K are stored in "NEOX" (rotated half) format, like in
transformers.

* Apply suggestion from @pcuenca

* Set model type

* Remove comment that will become obsolete

* Hardcode post_norm_rms_eps instead of new param

* Derive SWA+RoPE pattern from gguf array or scalar

* Fix model type <-> number of layers

* Reorder

* Rename

* Fix typo

* DFlash: seed the draft KV cache from multimodal embedding batches

`common_speculative_impl_draft_dflash::process()` returned early on any batch carrying embeddings, so an image prefill never had its target-layer features fused through the DFlash encoder and injected into the draft's KV cache. That left a hole spanning the image's positions, and the next injection at a post-image position failed to initialize its batch:

```
decoding image batch 1/1, n_tokens_batch = 256
decode: failed to initialize batch
llama_decode: failed to decode, ret = -1
process: llama_decode(ctx_dft) failed rc=-1 (n_tokens=17, offset=0)
srv decode: failed to process speculative batch
```

Every image request with `--spec-type draft-dflash` failed with HTTP 500. Text-only was unaffected, since those batches carry token ids and were let through.

Restore the earlier condition, which admits a batch that is either tokens or embeddings and skips only the degenerate neither/both cases. The rest of `process()` is already layout-agnostic -- it gathers features via `llama_get_embeddings_layer_inp()` and indexes `batch_in.pos[]` / `batch_in.seq_id[]`, none of which assume token ids -- so this is the whole fix.

Validated against `muse-glimmer-30B-bf16.gguf` + `mmproj-muse-glimmer-30B-bf16.gguf` + a DFlash draft head, on an image describe-the-shapes request:

- before: HTTP 500, `failed to process speculative batch`
- after: HTTP 200, draft acceptance 0.34012 (167 accepted / 491 generated), mean len 3.04

Output equivalence holds, which is the property that matters: at temperature 0 the drafted response is byte-identical to the same request served with no draft attached (1213/1213 chars), so the draft is drafting correctly through the image context rather than merely not crashing.

* Conversion: prefer rewrite to mapping

* Revert "Conversion: prefer rewrite to mapping"

This reverts commit a92d0ac.

* fix lint

* sliding_window metadata is not optional

* disable state save/load

* Apply suggestion from @pcuenca

---------

Co-authored-by: Young Han <[email protected]>
Co-authored-by: Beto de Paola <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: ruanrms <[email protected]>
Co-authored-by: Xuan Son Nguyen <[email protected]>
Co-authored-by: Sigbjørn Skjæret <[email protected]>
Madreag added a commit to Madreag/turbo3-cuda that referenced this pull request Aug 15, 2026
proxy v6.3: slot restore always attempted (A1 slots-dir bug), truncated
streams now deliver error frame + [DONE]/error event to CLIENT on both paths
(A3), passthrough allowlisted — /slots and raw completion endpoints blocked
(A4), swap shielded + owner=None during transition (TheTom#11), robust tripwire
classifier (TheTom#12), literal think-tags after content start stay content +
finish() flushes tag residue (TheTom#10), Anthropic images translated not dropped
(TheTom#14), Anthropic heartbeat pings (TheTom#4), mid-stream upstream death caught (TheTom#9),
retry guarded post-prepare (TheTom#8), partial-artifact persist only on abort (TheTom#6),
persistent trace handle + capture freshness/prune (TheTom#7,TheTom#17), generic blob
stripper (TheTom#16), hop-by-hop headers stripped (ggml-org#20), non-dict bodies 400 (TheTom#15),
read_task awaited (TheTom#19).

scripts: stop.sh verified kills (poll→SIGKILL, net only for survivors, port
check); start-long-38.sh double-start guard, log rotation, health-timeout
aborts before proxy launch, --api-key-file (key off cmdline), --metrics,
--swa-full dropped (dead flag), corrected comments+rollback; status.sh
probes ports+health. keys.json 600; stale systemd units + qwen36-era slot
sentinel archived to attic/.

test_proxy.py: runner moved to EOF (was silently skipping 5 tests — A6),
script-mode fixture shim, +7 regression tests → 49/49.

Claude-Session: https://claude.ai/code/session_01XTXkWYoiB8SvYyQ8VduRat
LogicDaemon added a commit to LogicDaemon/llama-cpp-turboquant that referenced this pull request Sep 6, 2026
commit bfe452a6d315b776c2e06f7f11c45bd6cd9766b4
Author: LogicDaemon <[email protected]>
Date:   Sat Sep 5 13:29:03 2026 +0400

    Squashed commit of the following:

    commit 10f8aff
    Author: thecodacus <[email protected]>
    Date:   Tue Aug 25 23:39:14 2026 +0530

        perf: lower default --cpu-tp-margin to 512 MiB

        Measured on a 12GB RTX 3060 with a dense 27B Q4_K_M: tightening the margin
        raises both decode and prefill, since every MiB reclaimed moves weights off
        the CPU leg. 1024 -> 640 -> 384 MiB gave 7.4 -> 7.8 -> 8.1 t/s decode and
        14.4 -> 15.2 -> 16.5 t/s prefill. 512 keeps headroom for larger contexts;
        raise it if the GPU runs out of memory.

    commit e406c8c
    Author: thecodacus <[email protected]>
    Date:   Tue Aug 25 22:08:09 2026 +0530

        feat: add --cpu-tp to use the CPU as a tensor-parallel device

        llama.cpp's tensor-parallel meta device already dispatches each member
        backend asynchronously before synchronising, but the CPU is excluded from
        the device list. Adding it lets the GPU and CPU compute row-slices of every
        weight matrix concurrently instead of running one after the other.

        The GPU share is sized from the measured free VRAM (minus --cpu-tp-margin)
        so VRAM is saturated, and the CPU takes only the remainder. The CPU is
        appended last so the GPU subgraph is already in flight when the CPU
        backend blocks on its own.

    commit d927e7d
    Author: Anirban Kar <[email protected]>
    Date:   Tue Aug 25 15:58:16 2026 +0530

        docs: add MoE expert cache usage and tuning guide to README (TheTom#8)

        * docs: add MoE expert cache usage and tuning guide to README

        * docs: document async CPU split overlap and VRAM headroom rule

    commit 0ac3d9b
    Author: Anirban Kar <[email protected]>
    Date:   Sun Aug 23 04:08:21 2026 +0530

        feat: overlap CPU cold-expert and GPU hot-expert computation in the MoE cache (TheTom#9)

        * feat: overlap CPU cold-expert chain with GPU hot chain (GGML_SCHED_ASYNC_CPU)

        The dual-path MoE cache ran its two chains serially: the scheduler
        blocks on CPU splits, and the cold chain's input copies drain the whole
        CUDA stream. Three changes make them concurrent, gated behind
        GGML_SCHED_ASYNC_CPU=1:

        - sched: CPU splits execute on a persistent worker thread; the main
          loop keeps launching later splits and joins lazily at the first split
          that is CPU or reads a CPU-resident input
        - graph: cold chain is built before the hot chain so the hot split
          follows it and carries no cross-backend inputs (launches while the
          worker computes)
        - graph: the merge add is pinned to CPU so it does not pull the hot
          chain into a split that waits on the cold result

        * feat: GGML_SCHED_ASYNC_CPU=2 diagnostic mode (worker without graph restructure)

        * fix: mark expert cache pack buffer as weights

        Without the weights usage flag the scheduler's assignment pass does not
        pin the pack tensors to their backend, so a CPU-assigned consumer (the
        pinned merge in async mode) propagates backward and pulls the hot
        matmuls onto the CPU, copying pack weights over PCIe every layer.

        * feat: make async CPU splits the default, expose --sched-async-cpu flag

        Replaces the GGML_SCHED_ASYNC_CPU env var: the overlap is now on by
        default and controlled through llama_context_params.sched_async_cpu.
        - ggml: ggml_backend_sched_set_async_cpu() setter, env read removed
        - llama: context param + cparams plumbing, graph gate reads cparams
        - common: --sched-async-cpu / --no-sched-async-cpu (server, cli)
        - llama-bench: sched_async_cpu test dimension (--sched-async-cpu 0,1
          benches both in one run, column shown as 'sac' when non-default)

        * fix: restrict CPU-pinned merge to decode-size batches

        For prefill batches the CPU merge and its per-layer activation copies
        cost more than the overlap hides (pp256 regressed 307 -> 257 t/s).
        Decode and MTP verify batches (n_tokens <= 8) keep the overlap.

    commit 8e5bc28
    Author: Anirban Kar <[email protected]>
    Date:   Sat Jul 25 03:54:47 2026 +0530

        feat: wire MoE expert cache into laguna graph (TheTom#6)

    commit ac743f8
    Author: Anirban Kar <[email protected]>
    Date:   Sat Jul 25 00:41:02 2026 +0530

        feat: MoE expert cache — keep hot routed experts resident in VRAM (TheTom#5)

        * feat: llama-moe-trace tool + expert-cache policy simulator

        Phase 0 of the MoE expert-cache work: capture routed expert ids
        (ffn_moe_topk) per layer per decode step via the scheduler eval
        callback — backend-agnostic, so CPU-offloaded expert layers are
        traced too. Companion simulate.py replays traces against cache
        policies (static top-S, LRU, LFU-decay, periodic re-election) and
        prints hit-rate vs VRAM-budget curves plus routing-skew stats to
        decide whether expert caching is worth building at all.

        * fix: moe-trace — common_init_from_params returns ptr with accessors

        * fix: moe-trace — include arg.h for common_params_parse

        * fix: moe-trace — take output path from MOE_TRACE_OUT env, -o not in this arg set

        * fix: moe-trace — topk tensor is a strided view; copy full byte range and index by nb

        Sizing the host buffer as n_used*n_tokens under-allocated: ffn_moe_topk
        is a view over the argsort output, so nb[1] spans n_expert ids per row
        and ggml_backend_tensor_get writes the whole strided range (heap
        corruption, malloc corrupted-top-size abort mid-prefill).

        * feat: moe-trace simulator v2 — model upload bytes/token and miss/upload cost per policy

        * feat: mul_mat_id tolerates id=-1 (skip) on CPU and CUDA fallback path

        Groundwork for the hot/cold expert-pack split: an id of -1 means the
        routed expert is not owned by this pack. The op contributes a zeroed
        output row for that slot so hot-pack and cold-pack results merge
        additively. CUDA fast paths (mmvq_id/mmq_id/mmf_id) still assert
        non-negative ids and are handled next.

        * feat: id=-1 skip support in CUDA mul_mat_id fast paths + tests

        mmid.cu gains a generic kernel that zeroes the dst rows of (token,
        slot) pairs whose expert id is -1; mmq and mmf launch it after the
        shared mm_ids_helper (which already drops unmatched ids from its
        compact mapping), and mmvq launches it before its kernels, which now
        early-return instead of using a negative id as a channel index (out
        of bounds read otherwise). test-backend-ops gains skip_ids variants
        of MUL_MAT_ID covering the mmvq/mmq/mmf/fallback dispatch corners.

        * fix: skip_ids MUL_MAT_ID test cases were inside an #if 0 block

        * fix: mm_ids_helper compact map corruption when ids contain -1

        Negative ids inflated nex_prev for every expert, opening a phantom
        region at the head of the compact arrays that nothing wrote; the mmq
        quantize preprocessing iterates the flat range and read garbage row
        indices (illegal memory access). Skipped ids now occupy no compact
        position, ids_src1 is sentinel-filled, and the quantize gather/scatter
        kernels skip negative entries.

        * fix: mmvf id=-1 skip guard (float mul_mat_id vec path)

        Same treatment as mmvq: kernels early-return on a negative expert id
        instead of using it as a channel index, and the host launcher
        pre-zeroes the dst rows of skipped slots. Fixes wrong results (and a
        latent out-of-bounds channel read) for f16/f32 MUL_MAT_ID with -1 ids
        at small batch sizes.

        * fix: zero-init ids_dst before mm_ids_helper — garbage tail entries in the
        compact map caused pool-layout-dependent illegal memory accesses when ids
        contain -1 (tile-padded reads consumed uninitialized row indices)

        * feat: route MUL_MAT_ID with skip-capable ids away from mmq/mmf

        Ops whose ids may contain -1 announce it via op_params[0]; the CUDA
        dispatch then uses only the paths with verified skip support (mmvq
        for small batches, the general gather/scatter path otherwise).
        Large-batch mmq with sparse ids shows a pool-layout-dependent fault
        that resists isolation (all indexing audits pass; sanitizer and
        cuda-gdb unusable on the target driver); since the expert-pack
        design only decodes through packs, the safe route costs nothing in
        practice. mmq/mmf guards from earlier commits remain as hardening.

        * fix: op_params write in test — ggml_set_op_params_i32 is internal-only

        * feat: MoE expert cache loader — hot-pack build from routing profile

        init_moe_expert_cache() runs post-load: reads a moe-trace profile
        (GGML_MOE_CACHE_PROFILE) and slot count (GGML_MOE_CACHE_SLOTS), and for
        each CPU-resident MoE layer builds GPU-resident hot packs of the top-S
        experts plus i32 remap tables (hot: global->slot or -1; cold: global id
        or -1). Graph wiring (build_moe_ffn dual path) is the next commit; these
        tensors are unused until then, so this is behavior-neutral.

        * feat: MoE expert cache graph wiring — dual hot/cold mul_mat_id in build_moe_ffn

        When a layer carries hot packs, routed ids are remapped through
        moe_map_hot/cold (get_rows) and each expert projection runs as two
        skip-flagged mul_mat_id ops — hot pack on GPU, original tensors for
        cold — whose zero-padded outputs sum to the exact single-tensor
        result. Engaged for qwen35moe (separate gate/up/down, no expert
        scales); layers with merged gate_up, scales, or no packs use the
        unchanged path.

        * fix: flatten routed ids before map get_rows (batched-gather shape rule)

        * fix: topk ids are a strided view - cont before flatten for map lookup

        * fix: sched expert-copy path skips id=-1 (hot/cold expert split)

        * fix: restructure MoE pack dual path into full FFN chains per residency side

        Per-projection hot/cold interleave let the scheduler's split minimizer
        assign hot up/down matmuls to CPU, copying the GPU pack weights over
        PCIe every layer. Building one unbroken gate-up-swiglu-down chain per
        side keeps the hot pack on GPU; skipped (-1) rows stay zero through
        swiglu so a single add of the two chain outputs is exact.

        * feat: wire MoE expert cache into deepseek2 graph (GLM-4.7-Flash)

        * feat: add --moe-cache-profile and --moe-cache-slots flags

        Plumbed through llama_model_params; env vars remain as fallback so
        existing deployments keep working. Flags allow per-model settings in
        multi-model serving.

        * docs: fix moe-trace usage comment (output path is MOE_TRACE_OUT env)

    commit cd72c28
    Author: Anirban Kar <[email protected]>
    Date:   Fri Jul 24 17:53:41 2026 +0530

        fix: restore closing brace lost in dequantize.cuh merge resolution

    commit 34f893e
    Merge: 40f2036 8f5ab83
    Author: Anirban Kar <[email protected]>
    Date:   Fri Jul 24 17:52:26 2026 +0530

        merge: sync upstream master into perf

    commit 8f5ab83
    Author: Matt Thompson <[email protected]>
    Date:   Fri Jul 24 03:54:47 2026 -0700

        cohere2 moe template parser: enforce JSON schema for text responses if a response schema is provided (ggml-org#26018)

    commit 0cea362
    Author: Xuan-Son Nguyen <[email protected]>
    Date:   Fri Jul 24 08:02:23 2026 +0200

        vendor: update subprocess.h (ggml-org#26061)

    commit 40f2036
    Author: Anirban Kar <[email protected]>
    Date:   Sun Jul 19 04:34:24 2026 +0530

        feat: fused turbo MMA flash-attention decode (turbo4/3/2, GQA tensor-core path) (TheTom#4)

        * feat(fattn): fused turbo4 MMA decode path (opt-in) — based on the spiritbuun fork MMA approach, adapted to graph-rotated Q

        Port buun's fused turbo4 tensor-core (MMA) flash-attention DECODE kernel into
        the turbo fork as an OPT-IN path (GGML_TURBO_MMA_FUSED=1, default OFF), routing
        turbo4-K==turbo4-V, D in {128,256}, decode (Q->ne[1]<=4) onto the GQA-packed MMA
        path so KV is read once per head-group instead of once per query head.

        How it works:
        - fattn-mma-f16.cuh: add flash_attn_ext_turbo4_load_tile (dequant turbo4 blocks
          -> SRAM in the f16 row-major half2 layout) seeded with OUR Lloyd-Max centroids
          (turbo-quant.cuh:297, NOT buun's -0.2415xx table). Thread type_K/type_V through
          iter/process_tile/global flash_attn_ext_f16 (defaults F16 -> existing f16/q8 MMA
          byte-identical). For turbo: force nstages=0 (the cp.async multi-stage path would
          read raw turbo bytes as half2), pass RAW byte pitch nb11/nb21 (not /sizeof(half2)),
          and dequantize K/V in the load tiles. sizeof(block_turbo4_0)-driven pointer math
          (66B block, no rnorm) — never assumes a fixed offset.
        - fattn-mma-turbo.cuh + 14 instance files (7 reachable ncols pairs x D in {128,256}):
          host launcher reusing the f16 device kernel with type_K/type_V=TURBO4_0 and
          need_f16_K/V=false so launch_fattn does NOT pre-convert KV to f16.
        - fattn.cu: switch_ncols2 -> per-ncols2 dispatchers (only the 7 compiled instances),
          env latch, and the gate (Q untouched — our fork already rotates Q at the graph
          level, so NO inline FWHT / src swap, which would double-rotate Q).

        Results (Qwen3.6-35B-A3B turbo4, GQA8, D=256, 5090):
          depth   MMA      VEC+PDL   buun
          8192    213.8    188.5     200    (+6.9% vs buun)
          16384   207.6    171.7     193    (+7.5% vs buun)
          32768   191.3    141.1     187    (+2.3% vs buun)
        MMA holds flat at depth where VEC collapses; the gap vs VEC grows with KV length.

        Quality: Mean KLD vs f16 base = 0.008396 (== VEC baseline). The MMA path is NOT
        strictly token-identical to VEC — MMA and VEC accumulate the P*V (VKQ) reduction in
        f16 with different reduction trees, so a near-tie greedy token can flip (~1/25 on a
        hard tie; same irreducible f16-order effect that exists between base f16-MMA and
        f16-VEC, and within the VEC-vs-base "same-top-p" 96.3% noise floor). Because strict
        token-identity does not hold, the gate DEFAULTS OFF and ships as opt-in; VEC remains
        the untouched default/kill-switch.

        (cherry picked from commit 5450669510a5cd0a356a863923b057f2552c6fbb)
        (cherry picked from commit b3e51cf)

        * turbo4 MMA decode: default ON (GQA-packed tensor-core path, quality-neutral; GGML_TURBO_MMA_FUSED=0 kill-switch)

        (cherry picked from commit 726234b538194c644be4066e1413b91f9edf12e7)
        (cherry picked from commit 38dc665)

        * fattn: extend fused MMA decode to turbo3 + turbo2 (parity on turbo4; extends the MMA path to turbo3/2)

        The GQA-packed tensor-core decode path was turbo4-only; turbo3/turbo2 fell back to
        VEC and collapsed at depth (turbo3 tg32 224->124 from d2048->d32768), losing to
        spiritbuun there. Added flash_attn_ext_turbo3_load_tile (3-bit split index: 2 low
        bits from qs + 1 high bit from signs) and flash_attn_ext_turbo2_load_tile (plain
        2-bit), type-dispatched both the K and V MMA load sites, and routed the gate by
        K->type. is_turbo_kv already matches any non-f16 KV, so the kernel needed only the
        per-type tile loaders + instances (14 instance files now emit all three types).

        Correctness: MMA decode is bit-exact to VEC (Mean KLD @2048 chunks=8:
        turbo3 0.020278==0.020278, turbo2 0.041490==0.041490, turbo4 0.009296 unchanged).

        Decode tg32 (qwen3.6-35B-A3B, RTX 5090), MMA now flat at depth:
          turbo3  2k/8k/16k/32k = 224/225/217/203  (buun 193/193/183/178; was VEC 224/187/160/124)
          turbo2  2k/8k/16k/32k = 228/224/217/203  (buun 213/210/204/200; was VEC 229/218/203/183)

        turbo3/turbo2 now hold flat at depth (neither fork had them on the MMA path before). GGML_TURBO_MMA_FUSED=0 restores VEC.

        (cherry picked from commit 57ad5edd53a7fced0b99fecb99326132cbdb65d0)
        (cherry picked from commit 4e223ee)

        * fix(fattn): gate turbo2 fused-MMA decode to head_dim 128

        Tester @everson isolated a turbo2-only decode regression on RTX 5060 Ti
        (Gemma-12B, head_dim 256): turbo2/turbo2 -2.46% at 8K to -1.17% at 200K,
        fully restored by GGML_TURBO_MMA_FUSED=0 at every depth, while turbo3 was
        neutral and turbo4 exact parity. At 2-bit KV the fused path's GQA-pack
        saving is tiny while its dequant/no-pipeline overhead is unchanged, so on
        head_dim 256 it is neutral on high-bandwidth GPUs (Ornith-35B and a dense
        Gemma-4-12B on RTX 5090, both within noise) and only costs on
        bandwidth-limited cards.

        turbo2 fused remains a large depth win on dense head_dim 128 (Llama-3.1-8B
        on RTX 5090: +7% at 8K, +24% at 32K, +69% at 131K), so this gates turbo2
        fused to head_dim 128 only; head_dim 256 turbo2 falls through to VEC, which
        is the exact baseline path GGML_TURBO_MMA_FUSED=0 restored. turbo3 and
        turbo4 fused are unchanged at both head dims.

        Also corrects the stale "default OFF" gate comments to match the
        default-ON code.

        (cherry picked from commit 539ce5d)

        ---------

        Co-authored-by: TheTom <[email protected]>

    commit 4cd54c6
    Author: Anirban Kar <[email protected]>
    Date:   Sun Jul 19 04:14:41 2026 +0530

        fix: allow mixed turbo/q8_0 KV cache types in CUDA flash-attention selection (TheTom#3)

        * fix: allow mixed turbo/q8_0 KV cache types in CUDA flash-attention selection

        Without GGML_CUDA_FA_ALL_QUANTS (the default), kernel selection
        rejected any K/V type mismatch. A turbo KV setup is almost always
        mixed (ctk q8_0 + ctv turbo2/3), so the flash-attention probe failed,
        FA was auto-disabled, and context creation either refused the
        quantized V cache outright or fell back to the non-FA path whose
        KQ buffer (~8.7 GiB at 64k ctx, ubatch 1024) OOMs at load.

        Allow exactly the mixed pairs that have FA template instances
        compiled in: turbo2/3/4 against each other, q8_0, and f16. Also gate
        turbo head-dim geometry (multiples of 64; 128 for turbo4) so shapes
        without a compiled instance report unsupported instead of asserting
        at dispatch.

        Forcing -fa on masked the bug (the probe is skipped); server
        deployments use fa auto and hit it on every load.

        * feat: accept turbo2/3/4 cache type names in llama-bench

        The common arg parser already accepts them for llama-completion and
        llama-server; llama-bench has its own name table and rejected -ctk/-ctv
        turbo values.

    commit 9338207
    Author: Anirban Kar <[email protected]>
    Date:   Sun Jul 19 01:59:58 2026 +0530

        CUDA: add Q2_0 support (TheTom#2)

        Co-authored-by: Pasha Khosravi <[email protected]>

    commit 170322f
    Author: Anirban Kar <[email protected]>
    Date:   Sat Jul 18 15:27:13 2026 +0530

        feat: TurboQuant KV-cache quantization — all backends (TheTom#1)

        * feat: TurboQuant KV-cache quantization — core types + CPU backend

        Port of the TurboQuant codec (arXiv 2504.19874, reference:
        TheTom/llama-cpp-turboquant) onto this fork's base: WHT-rotated polar
        quantization for the KV cache.

        - new types TURBO2_0/TURBO3_0/TURBO4_0 (KV, 2/3/4-bit blocks of 128)
          and TQ3_1S/TQ4_1S (WHT-rotated Lloyd-Max weight formats), renumbered
          for this tree's type table
        - GGML_OP_TURBO_WHT + ggml_turbo_wht() builder (forward/inverse
          Walsh-Hadamard rotation with sign arrays, InnerQ scale hook)
        - ggml-turbo-quant.c codec core, rotation data tables, CPU op +
          vec_dot paths, type traits, quantize-chunk wiring
        - CUDA/Metal/Vulkan kernel sources imported (wired in follow-ups)
        - verified: test-turbo-quant round-trip on CPU (cosine 0.986-0.996)

        * feat: turbo KV cache — graph wiring and CLI types

        - pre-rotate Q (forward WHT) at every cache-backed attention site when
          K is a turbo type; no-op otherwise
        - inverse WHT on attention output in both FA and non-FA paths of
          build_attn_mha (group size derived from K, contiguity enforced)
        - register turbo2/3/4 as --cache-type-k/--cache-type-v values
        Core scope: no InnerQ scaling, no head-dim padding — turbo KV requires
        128-aligned (or 64-group) head dims

        * feat: turbo KV cache — Metal backend (WHT kernel + FA dispatch)

        Wire the TurboQuant Metal backend host side and kernels on top of the
        CPU core already on this branch.

        Metal kernels (ggml-metal.metal):
        - Inlined turbo-wht.h (WHT sign arrays incl. half4 variants + FWHT
          butterfly + rotate fwd/inverse) and the turbo2/3/4 centroids.
        - quantize/dequantize_turbo2_0/3_0/4_0 (+_t4) and full-block cache.
        - kernel_turbo_wht (O(d log d) Walsh-Hadamard rotation op) and
          kernel_turbo4_dequant_f16 bulk prefill dequant.
        - kernel_set_rows_turbo/2/4 cache-quantize kernels + instantiations.
        - flash_attn_ext / flash_attn_ext_vec instantiations for symmetric and
          asymmetric turbo2/3/4 and q8_0<->turbo pairs.
        - TurboFlash two-pass kernels (p1/p2), default-disabled via env.

        Host side:
        - ggml-metal-device.cpp: get_pipeline_turbo_wht; flash-attn pipeline
          base names now encode both K and V types (k%s_v%s) so asymmetric K/V
          pairs resolve unambiguously. All existing FA kernel host_names in the
          shader renamed to match.
        - ggml-metal-device.m: TurboQuant compile-time env prep (4-mag LUT auto
          select, sparse-V, profile mode); supports_op accepts turbo K types and
          asymmetric turbo/q8_0 FA pairs; GGML_OP_TURBO_WHT.
        - ggml-metal-ops.cpp: GGML_OP_TURBO_WHT encode case + impl; asymmetric
          K/V assert relaxation; TurboFlash gating (use_turbo_flash, extra_tmp
          sizing, force-nonvec) + two-pass dispatch; +128 float FA smem for the
          turbo block cache.
        - ggml-metal-impl.h / -device.h / -ops.h: kargs (turbo_wht,
          turbo_flash_p1/p2), FC offsets, pipeline/op declarations.

        Adaptations vs the reference tree (older upstream vintage):
        - Reference intertwines separate TQ3_1S/TQ4_1S weight-quant work; only
          the turbo KV-cache lines are ported here.
        - set_rows_turbo dispatch selection is not wired: our upstream refactored
          get_pipeline_set_rows/kernel_set_rows_q32 to a different signature, and
          it is out of scope for this KV port. supports_op therefore does not
          claim CPY/SET_ROWS turbo support, so cache writes fall back to CPU;
          the set_rows_turbo shader kernels are present for when dispatch lands.
        - No InnerQ scale tensors touched (graph passes nullptr scale).

        * feat: turbo KV cache — CUDA backend (set-rows quantize, fattn vec dispatch, dequant)

        Port the TurboQuant CUDA backend from the reference implementation, adapted
        to this newer upstream vintage:

        - set-rows.cu: k_set_rows_turbo2/3/4 kernels (WHT rotation + norm-corrected
          PolarQuant KV write, InnerQ calibration hooks) + dispatch. turbo4 rnorm
          write dropped (field removed from block_turbo4_0 on this branch).
        - dequantize.cuh: dequantize_turbo2/3/4_0 and dequantize_tq3_1s/tq4_1s
          device functions.
        - convert.cu: turbo + TQ dequant cases in the fp16/fp32 contiguous and
          non-contiguous dispatch tables; warp-cooperative TQ4_1S dequant kernel.
        - fattn-common.cuh: vec_dot_fattn_vec_KQ_turbo2/3/4_0, dequantize_V_turbo*
          and get_vec_dot_KQ / get_dequantize_V dispatch entries.
        - fattn-vec.cuh: turbo K types take the float-Q path (Q_q8_1 off), turbo V
          uses the ne=4 quantized dequant path; extern decls for the 21 compiled
          K/V type combinations. Reference-side perf extras (shared-mem centroid
          LUT, sparse-V skip, nthreads tuning) intentionally not ported.
        - fattn.cu: turbo types accepted in kv_type_supported, vec kernel cases
          registered. Decode goes through the VEC kernel; prefill converts KV to
          f16 via the ported nc dequant path.
        - fattn-mma-turbo.cuh: reduced to a stub launcher. No typed MMA kernel
          exists in the reference either; the pre-existing template instances now
          compile against the stub and the dispatcher never selects this path.
        - ggml-cuda.cu: GGML_OP_TURBO_WHT dispatch + supports_op, SET_ROWS turbo
          gates (head_dim % 64, turbo4 % 128).
        - CMakeLists.txt: turbo fattn-vec instances added to the non-FA_ALL_QUANTS
          build.

        Verified on RTX 3060 (sm_86) with Bonsai-27B-Q1_0, partial offload, fa on:
        coherent generation for turbo2/3/4; perplexity over 4 chunks:
        f16 KV 7.9486 +/- 0.73, turbo3 KV 8.0261 +/- 0.74 (CUDA) vs 8.0279 (CPU-only).

        * feat: turbo KV cache — Vulkan backend (set-rows quantize, turbo3 FA dispatch, WHT op)

        - register turbo_wht.comp and set_rows turbo2/3/4 quantize variants in
          vulkan-shaders-gen; add dedicated DATA_A_TURBO3_0 flash-attn SPIR-V
          (scalar + coopmat1) with turbo3-only K/V bindings
        - copy_to_quant: 128-thread per-block set_rows path (normalize, randomized
          WHT, Lloyd-Max centroid quantize, subgroup pack), shared WHT tables
          across the three turbo widths
        - flash_attn_dequant: turbo2/3/4 centroid dequant macros wired into the
          FaTypeK/FaTypeV runtime switch (ids 43/44/45); f16 K/V aliases guarded
          out under DATA_A_TURBO3_0
        - ggml-vulkan: GGML_OP_TURBO_WHT pipeline + dispatch, turbo set_rows
          pipelines (required subgroup size 32), FA pipeline selection for
          turbo3, supports_op gates (128-elem blocks, turbo3 K/V symmetry,
          scalar/coopmat1 only — cm2 falls back to scalar)

        * fix: extern initialization warning and C linkage for wht group size

        CI builds with -Werror: defining the GGML_API-decorated global with an
        initializer warns on every platform. Plain definition in the C TU; the
        C++ consumer now declares it extern "C" (it previously referenced a
        mangled symbol).

        * feat: turbo2/turbo4 FA dequant for Vulkan

        - generalize the dedicated turbo flash-attn SPIR-V path from turbo3-only
          to all three tiers: DATA_A_TURBO_KV umbrella define in types.glsl gates
          out the f16/q4/q5/q8 K/V binding aliases in flash_attn.comp,
          flash_attn_cm1.comp and flash_attn_dequant.glsl for any turbo tier
        - flash_attn_dequant: per-compilation dequantize4 for DATA_A_TURBO2_0
          (2-bit centroids, fp16 norm + 32B idx) and DATA_A_TURBO4_0 (4-bit
          nibble idx, fp16 norm + fp16 aux + 64B) alongside the turbo3 one
        - vulkan-shaders-gen: register flash_attn_f32_f16_turbo{2,4}_0 scalar +
          coopmat1 variants via a per-tier loop
        - ggml-vulkan: FA pipeline selection picks the matching turbo SPIR-V for
          turbo2/turbo4 k_type (scalar + cm1), supports_op requires symmetric
          K/V per tier (turbo2/turbo2, turbo3/turbo3, turbo4/turbo4)

        * fix: bump RPC proto patch version for GGML_OP_TURBO_WHT

        * fix: export WHT group size via GGML_API for Windows shared builds

        * fix: HIP/MUSA portability for turbo kernels

        - map cudaMemcpyToSymbol/FromSymbol and __ballot_sync in vendor headers
        - pass explicit width to __shfl*_sync (HIP macros take 4 args)
        - drop unused warp_id locals flagged by nvcc -Werror

        * fix: drop SYCL turbo fattn-vec instances (no turbo dequant support in SYCL fattn)

        * fix: size vec_dot buffer by vec_dot_type and handle turbo/tq types in quantize test

        - tmp_q2 overflowed for types with vec_dot_type F32 (4 bytes per element)
        - skip turbo KV types: they quantize in the rotated domain, round trip
          does not reproduce the input by design
        - tq3_1s uses the 3-bit and lowbit thresholds

        * fix: add turbo fattn-vec instances to HIP and MUSA source lists

        * fix: add turbo fattn vec kernels to HIP VGPR ignore list

        The gfx908 build of the ncols=2 turbo3 vec kernels lands at 259 total
        VGPRs, slightly over the 256 gate. Register them like the other known
        high-pressure fattn kernels.

    commit 0888217
    Merge: 5e7f627 7d56da7
    Author: Anirban Kar <[email protected]>
    Date:   Fri Jul 17 20:02:48 2026 +0530

        chore: sync perf with upstream master

    commit 5e7f627
    Author: Anirban Kar <[email protected]>
    Date:   Wed Jul 8 23:56:46 2026 +0530

        docs(readme): add usage + benchmark instructions for the MoE-offload optimizations

    commit 5f83fbb
    Author: thecodacus <[email protected]>
    Date:   Thu Jul 2 12:42:55 2026 +0000

        ggml : size prefetch slots per layer and fix fallback use-after-free

        Profiling showed the 2-slot rotation stalls ~5.5ms per layer waiting for
        the down_exps upload: 3 tensors per MoE layer need 3 slots for a full
        layer of lookahead. Default is now 3 (one layer), configurable via the
        env var value, degrading to however many slots fit on OOM.

        Also fixes a use-after-free: on a failed slot regrow the repointed
        staging tensors kept dangling pointers into freed device memory, which
        graph reuse carried into later evals. Staging repoints are now restored
        right after kernel launch, slots are sized once from the graph max, and
        allocation happens before freeing.

        Qwen3.6-35B-A3B pp2048 on RTX 3060: 1643 -> 1880 t/s (mainline: 1143).

    commit 1163cb3
    Author: thecodacus <[email protected]>
    Date:   Thu Jul 2 12:16:39 2026 +0000

        ggml : overlap offloaded expert weight uploads with compute

        At large batch sizes virtually every expert is used, so the per-layer
        routing-ids readback that mainline waits on buys nothing while forcing a
        full device sync per expert tensor (3x per MoE layer). Above a batch
        threshold, upload the full expert tensors through a second backend
        instance on the same device (own stream) with two event-ordered staging
        slots, so uploads for tensor N+1 overlap compute of tensor N.

        Qwen3.6-35B-A3B pp2048 on RTX 3060 (-ncmoe 26, ub 2048): 1383 -> 1663 t/s.
        Generation output verified token-identical; decode path unaffected.
        Opt-in via GGML_SCHED_PREFETCH_EXPERTS=1.

    commit 20f5994
    Author: thecodacus <[email protected]>
    Date:   Thu Jul 2 09:44:53 2026 +0000

        llama : pin mmap-backed CPU weights for faster H2D uploads

        Wire the existing GGML_CUDA_REGISTER_HOST path back up: after model load,
        cudaHostRegister the mmap pages backing weights kept in system memory.
        Recovers pageable-copy losses when MoE experts are streamed to the GPU
        during prefill (n-cpu-moe): Qwen3.6-35B-A3B pp2048 1144 -> 1385 t/s on
        RTX 3060. Opt-in via GGML_CUDA_REGISTER_HOST=1, unchanged otherwise.
LogicDaemon added a commit to LogicDaemon/llama-cpp-turboquant that referenced this pull request Sep 7, 2026
commit 10f8aff
Author: thecodacus <[email protected]>
Date:   Tue Aug 25 23:39:14 2026 +0530

    perf: lower default --cpu-tp-margin to 512 MiB

    Measured on a 12GB RTX 3060 with a dense 27B Q4_K_M: tightening the margin
    raises both decode and prefill, since every MiB reclaimed moves weights off
    the CPU leg. 1024 -> 640 -> 384 MiB gave 7.4 -> 7.8 -> 8.1 t/s decode and
    14.4 -> 15.2 -> 16.5 t/s prefill. 512 keeps headroom for larger contexts;
    raise it if the GPU runs out of memory.

commit e406c8c
Author: thecodacus <[email protected]>
Date:   Tue Aug 25 22:08:09 2026 +0530

    feat: add --cpu-tp to use the CPU as a tensor-parallel device

    llama.cpp's tensor-parallel meta device already dispatches each member
    backend asynchronously before synchronising, but the CPU is excluded from
    the device list. Adding it lets the GPU and CPU compute row-slices of every
    weight matrix concurrently instead of running one after the other.

    The GPU share is sized from the measured free VRAM (minus --cpu-tp-margin)
    so VRAM is saturated, and the CPU takes only the remainder. The CPU is
    appended last so the GPU subgraph is already in flight when the CPU
    backend blocks on its own.

commit d927e7d
Author: Anirban Kar <[email protected]>
Date:   Tue Aug 25 15:58:16 2026 +0530

    docs: add MoE expert cache usage and tuning guide to README (TheTom#8)

    * docs: add MoE expert cache usage and tuning guide to README

    * docs: document async CPU split overlap and VRAM headroom rule

commit 0ac3d9b
Author: Anirban Kar <[email protected]>
Date:   Sun Aug 23 04:08:21 2026 +0530

    feat: overlap CPU cold-expert and GPU hot-expert computation in the MoE cache (TheTom#9)

    * feat: overlap CPU cold-expert chain with GPU hot chain (GGML_SCHED_ASYNC_CPU)

    The dual-path MoE cache ran its two chains serially: the scheduler
    blocks on CPU splits, and the cold chain's input copies drain the whole
    CUDA stream. Three changes make them concurrent, gated behind
    GGML_SCHED_ASYNC_CPU=1:

    - sched: CPU splits execute on a persistent worker thread; the main
      loop keeps launching later splits and joins lazily at the first split
      that is CPU or reads a CPU-resident input
    - graph: cold chain is built before the hot chain so the hot split
      follows it and carries no cross-backend inputs (launches while the
      worker computes)
    - graph: the merge add is pinned to CPU so it does not pull the hot
      chain into a split that waits on the cold result

    * feat: GGML_SCHED_ASYNC_CPU=2 diagnostic mode (worker without graph restructure)

    * fix: mark expert cache pack buffer as weights

    Without the weights usage flag the scheduler's assignment pass does not
    pin the pack tensors to their backend, so a CPU-assigned consumer (the
    pinned merge in async mode) propagates backward and pulls the hot
    matmuls onto the CPU, copying pack weights over PCIe every layer.

    * feat: make async CPU splits the default, expose --sched-async-cpu flag

    Replaces the GGML_SCHED_ASYNC_CPU env var: the overlap is now on by
    default and controlled through llama_context_params.sched_async_cpu.
    - ggml: ggml_backend_sched_set_async_cpu() setter, env read removed
    - llama: context param + cparams plumbing, graph gate reads cparams
    - common: --sched-async-cpu / --no-sched-async-cpu (server, cli)
    - llama-bench: sched_async_cpu test dimension (--sched-async-cpu 0,1
      benches both in one run, column shown as 'sac' when non-default)

    * fix: restrict CPU-pinned merge to decode-size batches

    For prefill batches the CPU merge and its per-layer activation copies
    cost more than the overlap hides (pp256 regressed 307 -> 257 t/s).
    Decode and MTP verify batches (n_tokens <= 8) keep the overlap.

commit 8e5bc28
Author: Anirban Kar <[email protected]>
Date:   Sat Jul 25 03:54:47 2026 +0530

    feat: wire MoE expert cache into laguna graph (TheTom#6)

commit ac743f8
Author: Anirban Kar <[email protected]>
Date:   Sat Jul 25 00:41:02 2026 +0530

    feat: MoE expert cache — keep hot routed experts resident in VRAM (TheTom#5)

    * feat: llama-moe-trace tool + expert-cache policy simulator

    Phase 0 of the MoE expert-cache work: capture routed expert ids
    (ffn_moe_topk) per layer per decode step via the scheduler eval
    callback — backend-agnostic, so CPU-offloaded expert layers are
    traced too. Companion simulate.py replays traces against cache
    policies (static top-S, LRU, LFU-decay, periodic re-election) and
    prints hit-rate vs VRAM-budget curves plus routing-skew stats to
    decide whether expert caching is worth building at all.

    * fix: moe-trace — common_init_from_params returns ptr with accessors

    * fix: moe-trace — include arg.h for common_params_parse

    * fix: moe-trace — take output path from MOE_TRACE_OUT env, -o not in this arg set

    * fix: moe-trace — topk tensor is a strided view; copy full byte range and index by nb

    Sizing the host buffer as n_used*n_tokens under-allocated: ffn_moe_topk
    is a view over the argsort output, so nb[1] spans n_expert ids per row
    and ggml_backend_tensor_get writes the whole strided range (heap
    corruption, malloc corrupted-top-size abort mid-prefill).

    * feat: moe-trace simulator v2 — model upload bytes/token and miss/upload cost per policy

    * feat: mul_mat_id tolerates id=-1 (skip) on CPU and CUDA fallback path

    Groundwork for the hot/cold expert-pack split: an id of -1 means the
    routed expert is not owned by this pack. The op contributes a zeroed
    output row for that slot so hot-pack and cold-pack results merge
    additively. CUDA fast paths (mmvq_id/mmq_id/mmf_id) still assert
    non-negative ids and are handled next.

    * feat: id=-1 skip support in CUDA mul_mat_id fast paths + tests

    mmid.cu gains a generic kernel that zeroes the dst rows of (token,
    slot) pairs whose expert id is -1; mmq and mmf launch it after the
    shared mm_ids_helper (which already drops unmatched ids from its
    compact mapping), and mmvq launches it before its kernels, which now
    early-return instead of using a negative id as a channel index (out
    of bounds read otherwise). test-backend-ops gains skip_ids variants
    of MUL_MAT_ID covering the mmvq/mmq/mmf/fallback dispatch corners.

    * fix: skip_ids MUL_MAT_ID test cases were inside an #if 0 block

    * fix: mm_ids_helper compact map corruption when ids contain -1

    Negative ids inflated nex_prev for every expert, opening a phantom
    region at the head of the compact arrays that nothing wrote; the mmq
    quantize preprocessing iterates the flat range and read garbage row
    indices (illegal memory access). Skipped ids now occupy no compact
    position, ids_src1 is sentinel-filled, and the quantize gather/scatter
    kernels skip negative entries.

    * fix: mmvf id=-1 skip guard (float mul_mat_id vec path)

    Same treatment as mmvq: kernels early-return on a negative expert id
    instead of using it as a channel index, and the host launcher
    pre-zeroes the dst rows of skipped slots. Fixes wrong results (and a
    latent out-of-bounds channel read) for f16/f32 MUL_MAT_ID with -1 ids
    at small batch sizes.

    * fix: zero-init ids_dst before mm_ids_helper — garbage tail entries in the
    compact map caused pool-layout-dependent illegal memory accesses when ids
    contain -1 (tile-padded reads consumed uninitialized row indices)

    * feat: route MUL_MAT_ID with skip-capable ids away from mmq/mmf

    Ops whose ids may contain -1 announce it via op_params[0]; the CUDA
    dispatch then uses only the paths with verified skip support (mmvq
    for small batches, the general gather/scatter path otherwise).
    Large-batch mmq with sparse ids shows a pool-layout-dependent fault
    that resists isolation (all indexing audits pass; sanitizer and
    cuda-gdb unusable on the target driver); since the expert-pack
    design only decodes through packs, the safe route costs nothing in
    practice. mmq/mmf guards from earlier commits remain as hardening.

    * fix: op_params write in test — ggml_set_op_params_i32 is internal-only

    * feat: MoE expert cache loader — hot-pack build from routing profile

    init_moe_expert_cache() runs post-load: reads a moe-trace profile
    (GGML_MOE_CACHE_PROFILE) and slot count (GGML_MOE_CACHE_SLOTS), and for
    each CPU-resident MoE layer builds GPU-resident hot packs of the top-S
    experts plus i32 remap tables (hot: global->slot or -1; cold: global id
    or -1). Graph wiring (build_moe_ffn dual path) is the next commit; these
    tensors are unused until then, so this is behavior-neutral.

    * feat: MoE expert cache graph wiring — dual hot/cold mul_mat_id in build_moe_ffn

    When a layer carries hot packs, routed ids are remapped through
    moe_map_hot/cold (get_rows) and each expert projection runs as two
    skip-flagged mul_mat_id ops — hot pack on GPU, original tensors for
    cold — whose zero-padded outputs sum to the exact single-tensor
    result. Engaged for qwen35moe (separate gate/up/down, no expert
    scales); layers with merged gate_up, scales, or no packs use the
    unchanged path.

    * fix: flatten routed ids before map get_rows (batched-gather shape rule)

    * fix: topk ids are a strided view - cont before flatten for map lookup

    * fix: sched expert-copy path skips id=-1 (hot/cold expert split)

    * fix: restructure MoE pack dual path into full FFN chains per residency side

    Per-projection hot/cold interleave let the scheduler's split minimizer
    assign hot up/down matmuls to CPU, copying the GPU pack weights over
    PCIe every layer. Building one unbroken gate-up-swiglu-down chain per
    side keeps the hot pack on GPU; skipped (-1) rows stay zero through
    swiglu so a single add of the two chain outputs is exact.

    * feat: wire MoE expert cache into deepseek2 graph (GLM-4.7-Flash)

    * feat: add --moe-cache-profile and --moe-cache-slots flags

    Plumbed through llama_model_params; env vars remain as fallback so
    existing deployments keep working. Flags allow per-model settings in
    multi-model serving.

    * docs: fix moe-trace usage comment (output path is MOE_TRACE_OUT env)

commit cd72c28
Author: Anirban Kar <[email protected]>
Date:   Fri Jul 24 17:53:41 2026 +0530

    fix: restore closing brace lost in dequantize.cuh merge resolution

commit 34f893e
Merge: 40f2036 8f5ab83
Author: Anirban Kar <[email protected]>
Date:   Fri Jul 24 17:52:26 2026 +0530

    merge: sync upstream master into perf

commit 8f5ab83
Author: Matt Thompson <[email protected]>
Date:   Fri Jul 24 03:54:47 2026 -0700

    cohere2 moe template parser: enforce JSON schema for text responses if a response schema is provided (ggml-org#26018)

commit 0cea362
Author: Xuan-Son Nguyen <[email protected]>
Date:   Fri Jul 24 08:02:23 2026 +0200

    vendor: update subprocess.h (ggml-org#26061)

commit 40f2036
Author: Anirban Kar <[email protected]>
Date:   Sun Jul 19 04:34:24 2026 +0530

    feat: fused turbo MMA flash-attention decode (turbo4/3/2, GQA tensor-core path) (TheTom#4)

    * feat(fattn): fused turbo4 MMA decode path (opt-in) — based on the spiritbuun fork MMA approach, adapted to graph-rotated Q

    Port buun's fused turbo4 tensor-core (MMA) flash-attention DECODE kernel into
    the turbo fork as an OPT-IN path (GGML_TURBO_MMA_FUSED=1, default OFF), routing
    turbo4-K==turbo4-V, D in {128,256}, decode (Q->ne[1]<=4) onto the GQA-packed MMA
    path so KV is read once per head-group instead of once per query head.

    How it works:
    - fattn-mma-f16.cuh: add flash_attn_ext_turbo4_load_tile (dequant turbo4 blocks
      -> SRAM in the f16 row-major half2 layout) seeded with OUR Lloyd-Max centroids
      (turbo-quant.cuh:297, NOT buun's -0.2415xx table). Thread type_K/type_V through
      iter/process_tile/global flash_attn_ext_f16 (defaults F16 -> existing f16/q8 MMA
      byte-identical). For turbo: force nstages=0 (the cp.async multi-stage path would
      read raw turbo bytes as half2), pass RAW byte pitch nb11/nb21 (not /sizeof(half2)),
      and dequantize K/V in the load tiles. sizeof(block_turbo4_0)-driven pointer math
      (66B block, no rnorm) — never assumes a fixed offset.
    - fattn-mma-turbo.cuh + 14 instance files (7 reachable ncols pairs x D in {128,256}):
      host launcher reusing the f16 device kernel with type_K/type_V=TURBO4_0 and
      need_f16_K/V=false so launch_fattn does NOT pre-convert KV to f16.
    - fattn.cu: switch_ncols2 -> per-ncols2 dispatchers (only the 7 compiled instances),
      env latch, and the gate (Q untouched — our fork already rotates Q at the graph
      level, so NO inline FWHT / src swap, which would double-rotate Q).

    Results (Qwen3.6-35B-A3B turbo4, GQA8, D=256, 5090):
      depth   MMA      VEC+PDL   buun
      8192    213.8    188.5     200    (+6.9% vs buun)
      16384   207.6    171.7     193    (+7.5% vs buun)
      32768   191.3    141.1     187    (+2.3% vs buun)
    MMA holds flat at depth where VEC collapses; the gap vs VEC grows with KV length.

    Quality: Mean KLD vs f16 base = 0.008396 (== VEC baseline). The MMA path is NOT
    strictly token-identical to VEC — MMA and VEC accumulate the P*V (VKQ) reduction in
    f16 with different reduction trees, so a near-tie greedy token can flip (~1/25 on a
    hard tie; same irreducible f16-order effect that exists between base f16-MMA and
    f16-VEC, and within the VEC-vs-base "same-top-p" 96.3% noise floor). Because strict
    token-identity does not hold, the gate DEFAULTS OFF and ships as opt-in; VEC remains
    the untouched default/kill-switch.

    (cherry picked from commit 5450669510a5cd0a356a863923b057f2552c6fbb)
    (cherry picked from commit b3e51cf)

    * turbo4 MMA decode: default ON (GQA-packed tensor-core path, quality-neutral; GGML_TURBO_MMA_FUSED=0 kill-switch)

    (cherry picked from commit 726234b538194c644be4066e1413b91f9edf12e7)
    (cherry picked from commit 38dc665)

    * fattn: extend fused MMA decode to turbo3 + turbo2 (parity on turbo4; extends the MMA path to turbo3/2)

    The GQA-packed tensor-core decode path was turbo4-only; turbo3/turbo2 fell back to
    VEC and collapsed at depth (turbo3 tg32 224->124 from d2048->d32768), losing to
    spiritbuun there. Added flash_attn_ext_turbo3_load_tile (3-bit split index: 2 low
    bits from qs + 1 high bit from signs) and flash_attn_ext_turbo2_load_tile (plain
    2-bit), type-dispatched both the K and V MMA load sites, and routed the gate by
    K->type. is_turbo_kv already matches any non-f16 KV, so the kernel needed only the
    per-type tile loaders + instances (14 instance files now emit all three types).

    Correctness: MMA decode is bit-exact to VEC (Mean KLD @2048 chunks=8:
    turbo3 0.020278==0.020278, turbo2 0.041490==0.041490, turbo4 0.009296 unchanged).

    Decode tg32 (qwen3.6-35B-A3B, RTX 5090), MMA now flat at depth:
      turbo3  2k/8k/16k/32k = 224/225/217/203  (buun 193/193/183/178; was VEC 224/187/160/124)
      turbo2  2k/8k/16k/32k = 228/224/217/203  (buun 213/210/204/200; was VEC 229/218/203/183)

    turbo3/turbo2 now hold flat at depth (neither fork had them on the MMA path before). GGML_TURBO_MMA_FUSED=0 restores VEC.

    (cherry picked from commit 57ad5edd53a7fced0b99fecb99326132cbdb65d0)
    (cherry picked from commit 4e223ee)

    * fix(fattn): gate turbo2 fused-MMA decode to head_dim 128

    Tester @everson isolated a turbo2-only decode regression on RTX 5060 Ti
    (Gemma-12B, head_dim 256): turbo2/turbo2 -2.46% at 8K to -1.17% at 200K,
    fully restored by GGML_TURBO_MMA_FUSED=0 at every depth, while turbo3 was
    neutral and turbo4 exact parity. At 2-bit KV the fused path's GQA-pack
    saving is tiny while its dequant/no-pipeline overhead is unchanged, so on
    head_dim 256 it is neutral on high-bandwidth GPUs (Ornith-35B and a dense
    Gemma-4-12B on RTX 5090, both within noise) and only costs on
    bandwidth-limited cards.

    turbo2 fused remains a large depth win on dense head_dim 128 (Llama-3.1-8B
    on RTX 5090: +7% at 8K, +24% at 32K, +69% at 131K), so this gates turbo2
    fused to head_dim 128 only; head_dim 256 turbo2 falls through to VEC, which
    is the exact baseline path GGML_TURBO_MMA_FUSED=0 restored. turbo3 and
    turbo4 fused are unchanged at both head dims.

    Also corrects the stale "default OFF" gate comments to match the
    default-ON code.

    (cherry picked from commit 539ce5d)

    ---------

    Co-authored-by: TheTom <[email protected]>

commit 4cd54c6
Author: Anirban Kar <[email protected]>
Date:   Sun Jul 19 04:14:41 2026 +0530

    fix: allow mixed turbo/q8_0 KV cache types in CUDA flash-attention selection (TheTom#3)

    * fix: allow mixed turbo/q8_0 KV cache types in CUDA flash-attention selection

    Without GGML_CUDA_FA_ALL_QUANTS (the default), kernel selection
    rejected any K/V type mismatch. A turbo KV setup is almost always
    mixed (ctk q8_0 + ctv turbo2/3), so the flash-attention probe failed,
    FA was auto-disabled, and context creation either refused the
    quantized V cache outright or fell back to the non-FA path whose
    KQ buffer (~8.7 GiB at 64k ctx, ubatch 1024) OOMs at load.

    Allow exactly the mixed pairs that have FA template instances
    compiled in: turbo2/3/4 against each other, q8_0, and f16. Also gate
    turbo head-dim geometry (multiples of 64; 128 for turbo4) so shapes
    without a compiled instance report unsupported instead of asserting
    at dispatch.

    Forcing -fa on masked the bug (the probe is skipped); server
    deployments use fa auto and hit it on every load.

    * feat: accept turbo2/3/4 cache type names in llama-bench

    The common arg parser already accepts them for llama-completion and
    llama-server; llama-bench has its own name table and rejected -ctk/-ctv
    turbo values.

commit 9338207
Author: Anirban Kar <[email protected]>
Date:   Sun Jul 19 01:59:58 2026 +0530

    CUDA: add Q2_0 support (TheTom#2)

    Co-authored-by: Pasha Khosravi <[email protected]>

commit 170322f
Author: Anirban Kar <[email protected]>
Date:   Sat Jul 18 15:27:13 2026 +0530

    feat: TurboQuant KV-cache quantization — all backends (TheTom#1)

    * feat: TurboQuant KV-cache quantization — core types + CPU backend

    Port of the TurboQuant codec (arXiv 2504.19874, reference:
    TheTom/llama-cpp-turboquant) onto this fork's base: WHT-rotated polar
    quantization for the KV cache.

    - new types TURBO2_0/TURBO3_0/TURBO4_0 (KV, 2/3/4-bit blocks of 128)
      and TQ3_1S/TQ4_1S (WHT-rotated Lloyd-Max weight formats), renumbered
      for this tree's type table
    - GGML_OP_TURBO_WHT + ggml_turbo_wht() builder (forward/inverse
      Walsh-Hadamard rotation with sign arrays, InnerQ scale hook)
    - ggml-turbo-quant.c codec core, rotation data tables, CPU op +
      vec_dot paths, type traits, quantize-chunk wiring
    - CUDA/Metal/Vulkan kernel sources imported (wired in follow-ups)
    - verified: test-turbo-quant round-trip on CPU (cosine 0.986-0.996)

    * feat: turbo KV cache — graph wiring and CLI types

    - pre-rotate Q (forward WHT) at every cache-backed attention site when
      K is a turbo type; no-op otherwise
    - inverse WHT on attention output in both FA and non-FA paths of
      build_attn_mha (group size derived from K, contiguity enforced)
    - register turbo2/3/4 as --cache-type-k/--cache-type-v values
    Core scope: no InnerQ scaling, no head-dim padding — turbo KV requires
    128-aligned (or 64-group) head dims

    * feat: turbo KV cache — Metal backend (WHT kernel + FA dispatch)

    Wire the TurboQuant Metal backend host side and kernels on top of the
    CPU core already on this branch.

    Metal kernels (ggml-metal.metal):
    - Inlined turbo-wht.h (WHT sign arrays incl. half4 variants + FWHT
      butterfly + rotate fwd/inverse) and the turbo2/3/4 centroids.
    - quantize/dequantize_turbo2_0/3_0/4_0 (+_t4) and full-block cache.
    - kernel_turbo_wht (O(d log d) Walsh-Hadamard rotation op) and
      kernel_turbo4_dequant_f16 bulk prefill dequant.
    - kernel_set_rows_turbo/2/4 cache-quantize kernels + instantiations.
    - flash_attn_ext / flash_attn_ext_vec instantiations for symmetric and
      asymmetric turbo2/3/4 and q8_0<->turbo pairs.
    - TurboFlash two-pass kernels (p1/p2), default-disabled via env.

    Host side:
    - ggml-metal-device.cpp: get_pipeline_turbo_wht; flash-attn pipeline
      base names now encode both K and V types (k%s_v%s) so asymmetric K/V
      pairs resolve unambiguously. All existing FA kernel host_names in the
      shader renamed to match.
    - ggml-metal-device.m: TurboQuant compile-time env prep (4-mag LUT auto
      select, sparse-V, profile mode); supports_op accepts turbo K types and
      asymmetric turbo/q8_0 FA pairs; GGML_OP_TURBO_WHT.
    - ggml-metal-ops.cpp: GGML_OP_TURBO_WHT encode case + impl; asymmetric
      K/V assert relaxation; TurboFlash gating (use_turbo_flash, extra_tmp
      sizing, force-nonvec) + two-pass dispatch; +128 float FA smem for the
      turbo block cache.
    - ggml-metal-impl.h / -device.h / -ops.h: kargs (turbo_wht,
      turbo_flash_p1/p2), FC offsets, pipeline/op declarations.

    Adaptations vs the reference tree (older upstream vintage):
    - Reference intertwines separate TQ3_1S/TQ4_1S weight-quant work; only
      the turbo KV-cache lines are ported here.
    - set_rows_turbo dispatch selection is not wired: our upstream refactored
      get_pipeline_set_rows/kernel_set_rows_q32 to a different signature, and
      it is out of scope for this KV port. supports_op therefore does not
      claim CPY/SET_ROWS turbo support, so cache writes fall back to CPU;
      the set_rows_turbo shader kernels are present for when dispatch lands.
    - No InnerQ scale tensors touched (graph passes nullptr scale).

    * feat: turbo KV cache — CUDA backend (set-rows quantize, fattn vec dispatch, dequant)

    Port the TurboQuant CUDA backend from the reference implementation, adapted
    to this newer upstream vintage:

    - set-rows.cu: k_set_rows_turbo2/3/4 kernels (WHT rotation + norm-corrected
      PolarQuant KV write, InnerQ calibration hooks) + dispatch. turbo4 rnorm
      write dropped (field removed from block_turbo4_0 on this branch).
    - dequantize.cuh: dequantize_turbo2/3/4_0 and dequantize_tq3_1s/tq4_1s
      device functions.
    - convert.cu: turbo + TQ dequant cases in the fp16/fp32 contiguous and
      non-contiguous dispatch tables; warp-cooperative TQ4_1S dequant kernel.
    - fattn-common.cuh: vec_dot_fattn_vec_KQ_turbo2/3/4_0, dequantize_V_turbo*
      and get_vec_dot_KQ / get_dequantize_V dispatch entries.
    - fattn-vec.cuh: turbo K types take the float-Q path (Q_q8_1 off), turbo V
      uses the ne=4 quantized dequant path; extern decls for the 21 compiled
      K/V type combinations. Reference-side perf extras (shared-mem centroid
      LUT, sparse-V skip, nthreads tuning) intentionally not ported.
    - fattn.cu: turbo types accepted in kv_type_supported, vec kernel cases
      registered. Decode goes through the VEC kernel; prefill converts KV to
      f16 via the ported nc dequant path.
    - fattn-mma-turbo.cuh: reduced to a stub launcher. No typed MMA kernel
      exists in the reference either; the pre-existing template instances now
      compile against the stub and the dispatcher never selects this path.
    - ggml-cuda.cu: GGML_OP_TURBO_WHT dispatch + supports_op, SET_ROWS turbo
      gates (head_dim % 64, turbo4 % 128).
    - CMakeLists.txt: turbo fattn-vec instances added to the non-FA_ALL_QUANTS
      build.

    Verified on RTX 3060 (sm_86) with Bonsai-27B-Q1_0, partial offload, fa on:
    coherent generation for turbo2/3/4; perplexity over 4 chunks:
    f16 KV 7.9486 +/- 0.73, turbo3 KV 8.0261 +/- 0.74 (CUDA) vs 8.0279 (CPU-only).

    * feat: turbo KV cache — Vulkan backend (set-rows quantize, turbo3 FA dispatch, WHT op)

    - register turbo_wht.comp and set_rows turbo2/3/4 quantize variants in
      vulkan-shaders-gen; add dedicated DATA_A_TURBO3_0 flash-attn SPIR-V
      (scalar + coopmat1) with turbo3-only K/V bindings
    - copy_to_quant: 128-thread per-block set_rows path (normalize, randomized
      WHT, Lloyd-Max centroid quantize, subgroup pack), shared WHT tables
      across the three turbo widths
    - flash_attn_dequant: turbo2/3/4 centroid dequant macros wired into the
      FaTypeK/FaTypeV runtime switch (ids 43/44/45); f16 K/V aliases guarded
      out under DATA_A_TURBO3_0
    - ggml-vulkan: GGML_OP_TURBO_WHT pipeline + dispatch, turbo set_rows
      pipelines (required subgroup size 32), FA pipeline selection for
      turbo3, supports_op gates (128-elem blocks, turbo3 K/V symmetry,
      scalar/coopmat1 only — cm2 falls back to scalar)

    * fix: extern initialization warning and C linkage for wht group size

    CI builds with -Werror: defining the GGML_API-decorated global with an
    initializer warns on every platform. Plain definition in the C TU; the
    C++ consumer now declares it extern "C" (it previously referenced a
    mangled symbol).

    * feat: turbo2/turbo4 FA dequant for Vulkan

    - generalize the dedicated turbo flash-attn SPIR-V path from turbo3-only
      to all three tiers: DATA_A_TURBO_KV umbrella define in types.glsl gates
      out the f16/q4/q5/q8 K/V binding aliases in flash_attn.comp,
      flash_attn_cm1.comp and flash_attn_dequant.glsl for any turbo tier
    - flash_attn_dequant: per-compilation dequantize4 for DATA_A_TURBO2_0
      (2-bit centroids, fp16 norm + 32B idx) and DATA_A_TURBO4_0 (4-bit
      nibble idx, fp16 norm + fp16 aux + 64B) alongside the turbo3 one
    - vulkan-shaders-gen: register flash_attn_f32_f16_turbo{2,4}_0 scalar +
      coopmat1 variants via a per-tier loop
    - ggml-vulkan: FA pipeline selection picks the matching turbo SPIR-V for
      turbo2/turbo4 k_type (scalar + cm1), supports_op requires symmetric
      K/V per tier (turbo2/turbo2, turbo3/turbo3, turbo4/turbo4)

    * fix: bump RPC proto patch version for GGML_OP_TURBO_WHT

    * fix: export WHT group size via GGML_API for Windows shared builds

    * fix: HIP/MUSA portability for turbo kernels

    - map cudaMemcpyToSymbol/FromSymbol and __ballot_sync in vendor headers
    - pass explicit width to __shfl*_sync (HIP macros take 4 args)
    - drop unused warp_id locals flagged by nvcc -Werror

    * fix: drop SYCL turbo fattn-vec instances (no turbo dequant support in SYCL fattn)

    * fix: size vec_dot buffer by vec_dot_type and handle turbo/tq types in quantize test

    - tmp_q2 overflowed for types with vec_dot_type F32 (4 bytes per element)
    - skip turbo KV types: they quantize in the rotated domain, round trip
      does not reproduce the input by design
    - tq3_1s uses the 3-bit and lowbit thresholds

    * fix: add turbo fattn-vec instances to HIP and MUSA source lists

    * fix: add turbo fattn vec kernels to HIP VGPR ignore list

    The gfx908 build of the ncols=2 turbo3 vec kernels lands at 259 total
    VGPRs, slightly over the 256 gate. Register them like the other known
    high-pressure fattn kernels.

commit 0888217
Merge: 5e7f627 7d56da7
Author: Anirban Kar <[email protected]>
Date:   Fri Jul 17 20:02:48 2026 +0530

    chore: sync perf with upstream master

commit 5e7f627
Author: Anirban Kar <[email protected]>
Date:   Wed Jul 8 23:56:46 2026 +0530

    docs(readme): add usage + benchmark instructions for the MoE-offload optimizations

commit 5f83fbb
Author: thecodacus <[email protected]>
Date:   Thu Jul 2 12:42:55 2026 +0000

    ggml : size prefetch slots per layer and fix fallback use-after-free

    Profiling showed the 2-slot rotation stalls ~5.5ms per layer waiting for
    the down_exps upload: 3 tensors per MoE layer need 3 slots for a full
    layer of lookahead. Default is now 3 (one layer), configurable via the
    env var value, degrading to however many slots fit on OOM.

    Also fixes a use-after-free: on a failed slot regrow the repointed
    staging tensors kept dangling pointers into freed device memory, which
    graph reuse carried into later evals. Staging repoints are now restored
    right after kernel launch, slots are sized once from the graph max, and
    allocation happens before freeing.

    Qwen3.6-35B-A3B pp2048 on RTX 3060: 1643 -> 1880 t/s (mainline: 1143).

commit 1163cb3
Author: thecodacus <[email protected]>
Date:   Thu Jul 2 12:16:39 2026 +0000

    ggml : overlap offloaded expert weight uploads with compute

    At large batch sizes virtually every expert is used, so the per-layer
    routing-ids readback that mainline waits on buys nothing while forcing a
    full device sync per expert tensor (3x per MoE layer). Above a batch
    threshold, upload the full expert tensors through a second backend
    instance on the same device (own stream) with two event-ordered staging
    slots, so uploads for tensor N+1 overlap compute of tensor N.

    Qwen3.6-35B-A3B pp2048 on RTX 3060 (-ncmoe 26, ub 2048): 1383 -> 1663 t/s.
    Generation output verified token-identical; decode path unaffected.
    Opt-in via GGML_SCHED_PREFETCH_EXPERTS=1.

commit 20f5994
Author: thecodacus <[email protected]>
Date:   Thu Jul 2 09:44:53 2026 +0000

    llama : pin mmap-backed CPU weights for faster H2D uploads

    Wire the existing GGML_CUDA_REGISTER_HOST path back up: after model load,
    cudaHostRegister the mmap pages backing weights kept in system memory.
    Recovers pageable-copy losses when MoE experts are streamed to the GPU
    during prefill (n-cpu-moe): Qwen3.6-35B-A3B pp2048 1144 -> 1385 t/s on
    RTX 3060. Opt-in via GGML_CUDA_REGISTER_HOST=1, unchanged otherwise.
LogicDaemon added a commit to LogicDaemon/llama-cpp-turboquant that referenced this pull request Sep 15, 2026
commit 10f8aff
Author: thecodacus <[email protected]>
Date:   Tue Aug 25 23:39:14 2026 +0530

    perf: lower default --cpu-tp-margin to 512 MiB

    Measured on a 12GB RTX 3060 with a dense 27B Q4_K_M: tightening the margin
    raises both decode and prefill, since every MiB reclaimed moves weights off
    the CPU leg. 1024 -> 640 -> 384 MiB gave 7.4 -> 7.8 -> 8.1 t/s decode and
    14.4 -> 15.2 -> 16.5 t/s prefill. 512 keeps headroom for larger contexts;
    raise it if the GPU runs out of memory.

commit e406c8c
Author: thecodacus <[email protected]>
Date:   Tue Aug 25 22:08:09 2026 +0530

    feat: add --cpu-tp to use the CPU as a tensor-parallel device

    llama.cpp's tensor-parallel meta device already dispatches each member
    backend asynchronously before synchronising, but the CPU is excluded from
    the device list. Adding it lets the GPU and CPU compute row-slices of every
    weight matrix concurrently instead of running one after the other.

    The GPU share is sized from the measured free VRAM (minus --cpu-tp-margin)
    so VRAM is saturated, and the CPU takes only the remainder. The CPU is
    appended last so the GPU subgraph is already in flight when the CPU
    backend blocks on its own.

commit d927e7d
Author: Anirban Kar <[email protected]>
Date:   Tue Aug 25 15:58:16 2026 +0530

    docs: add MoE expert cache usage and tuning guide to README (TheTom#8)

    * docs: add MoE expert cache usage and tuning guide to README

    * docs: document async CPU split overlap and VRAM headroom rule

commit 0ac3d9b
Author: Anirban Kar <[email protected]>
Date:   Sun Aug 23 04:08:21 2026 +0530

    feat: overlap CPU cold-expert and GPU hot-expert computation in the MoE cache (TheTom#9)

    * feat: overlap CPU cold-expert chain with GPU hot chain (GGML_SCHED_ASYNC_CPU)

    The dual-path MoE cache ran its two chains serially: the scheduler
    blocks on CPU splits, and the cold chain's input copies drain the whole
    CUDA stream. Three changes make them concurrent, gated behind
    GGML_SCHED_ASYNC_CPU=1:

    - sched: CPU splits execute on a persistent worker thread; the main
      loop keeps launching later splits and joins lazily at the first split
      that is CPU or reads a CPU-resident input
    - graph: cold chain is built before the hot chain so the hot split
      follows it and carries no cross-backend inputs (launches while the
      worker computes)
    - graph: the merge add is pinned to CPU so it does not pull the hot
      chain into a split that waits on the cold result

    * feat: GGML_SCHED_ASYNC_CPU=2 diagnostic mode (worker without graph restructure)

    * fix: mark expert cache pack buffer as weights

    Without the weights usage flag the scheduler's assignment pass does not
    pin the pack tensors to their backend, so a CPU-assigned consumer (the
    pinned merge in async mode) propagates backward and pulls the hot
    matmuls onto the CPU, copying pack weights over PCIe every layer.

    * feat: make async CPU splits the default, expose --sched-async-cpu flag

    Replaces the GGML_SCHED_ASYNC_CPU env var: the overlap is now on by
    default and controlled through llama_context_params.sched_async_cpu.
    - ggml: ggml_backend_sched_set_async_cpu() setter, env read removed
    - llama: context param + cparams plumbing, graph gate reads cparams
    - common: --sched-async-cpu / --no-sched-async-cpu (server, cli)
    - llama-bench: sched_async_cpu test dimension (--sched-async-cpu 0,1
      benches both in one run, column shown as 'sac' when non-default)

    * fix: restrict CPU-pinned merge to decode-size batches

    For prefill batches the CPU merge and its per-layer activation copies
    cost more than the overlap hides (pp256 regressed 307 -> 257 t/s).
    Decode and MTP verify batches (n_tokens <= 8) keep the overlap.

commit 8e5bc28
Author: Anirban Kar <[email protected]>
Date:   Sat Jul 25 03:54:47 2026 +0530

    feat: wire MoE expert cache into laguna graph (TheTom#6)

commit ac743f8
Author: Anirban Kar <[email protected]>
Date:   Sat Jul 25 00:41:02 2026 +0530

    feat: MoE expert cache — keep hot routed experts resident in VRAM (TheTom#5)

    * feat: llama-moe-trace tool + expert-cache policy simulator

    Phase 0 of the MoE expert-cache work: capture routed expert ids
    (ffn_moe_topk) per layer per decode step via the scheduler eval
    callback — backend-agnostic, so CPU-offloaded expert layers are
    traced too. Companion simulate.py replays traces against cache
    policies (static top-S, LRU, LFU-decay, periodic re-election) and
    prints hit-rate vs VRAM-budget curves plus routing-skew stats to
    decide whether expert caching is worth building at all.

    * fix: moe-trace — common_init_from_params returns ptr with accessors

    * fix: moe-trace — include arg.h for common_params_parse

    * fix: moe-trace — take output path from MOE_TRACE_OUT env, -o not in this arg set

    * fix: moe-trace — topk tensor is a strided view; copy full byte range and index by nb

    Sizing the host buffer as n_used*n_tokens under-allocated: ffn_moe_topk
    is a view over the argsort output, so nb[1] spans n_expert ids per row
    and ggml_backend_tensor_get writes the whole strided range (heap
    corruption, malloc corrupted-top-size abort mid-prefill).

    * feat: moe-trace simulator v2 — model upload bytes/token and miss/upload cost per policy

    * feat: mul_mat_id tolerates id=-1 (skip) on CPU and CUDA fallback path

    Groundwork for the hot/cold expert-pack split: an id of -1 means the
    routed expert is not owned by this pack. The op contributes a zeroed
    output row for that slot so hot-pack and cold-pack results merge
    additively. CUDA fast paths (mmvq_id/mmq_id/mmf_id) still assert
    non-negative ids and are handled next.

    * feat: id=-1 skip support in CUDA mul_mat_id fast paths + tests

    mmid.cu gains a generic kernel that zeroes the dst rows of (token,
    slot) pairs whose expert id is -1; mmq and mmf launch it after the
    shared mm_ids_helper (which already drops unmatched ids from its
    compact mapping), and mmvq launches it before its kernels, which now
    early-return instead of using a negative id as a channel index (out
    of bounds read otherwise). test-backend-ops gains skip_ids variants
    of MUL_MAT_ID covering the mmvq/mmq/mmf/fallback dispatch corners.

    * fix: skip_ids MUL_MAT_ID test cases were inside an #if 0 block

    * fix: mm_ids_helper compact map corruption when ids contain -1

    Negative ids inflated nex_prev for every expert, opening a phantom
    region at the head of the compact arrays that nothing wrote; the mmq
    quantize preprocessing iterates the flat range and read garbage row
    indices (illegal memory access). Skipped ids now occupy no compact
    position, ids_src1 is sentinel-filled, and the quantize gather/scatter
    kernels skip negative entries.

    * fix: mmvf id=-1 skip guard (float mul_mat_id vec path)

    Same treatment as mmvq: kernels early-return on a negative expert id
    instead of using it as a channel index, and the host launcher
    pre-zeroes the dst rows of skipped slots. Fixes wrong results (and a
    latent out-of-bounds channel read) for f16/f32 MUL_MAT_ID with -1 ids
    at small batch sizes.

    * fix: zero-init ids_dst before mm_ids_helper — garbage tail entries in the
    compact map caused pool-layout-dependent illegal memory accesses when ids
    contain -1 (tile-padded reads consumed uninitialized row indices)

    * feat: route MUL_MAT_ID with skip-capable ids away from mmq/mmf

    Ops whose ids may contain -1 announce it via op_params[0]; the CUDA
    dispatch then uses only the paths with verified skip support (mmvq
    for small batches, the general gather/scatter path otherwise).
    Large-batch mmq with sparse ids shows a pool-layout-dependent fault
    that resists isolation (all indexing audits pass; sanitizer and
    cuda-gdb unusable on the target driver); since the expert-pack
    design only decodes through packs, the safe route costs nothing in
    practice. mmq/mmf guards from earlier commits remain as hardening.

    * fix: op_params write in test — ggml_set_op_params_i32 is internal-only

    * feat: MoE expert cache loader — hot-pack build from routing profile

    init_moe_expert_cache() runs post-load: reads a moe-trace profile
    (GGML_MOE_CACHE_PROFILE) and slot count (GGML_MOE_CACHE_SLOTS), and for
    each CPU-resident MoE layer builds GPU-resident hot packs of the top-S
    experts plus i32 remap tables (hot: global->slot or -1; cold: global id
    or -1). Graph wiring (build_moe_ffn dual path) is the next commit; these
    tensors are unused until then, so this is behavior-neutral.

    * feat: MoE expert cache graph wiring — dual hot/cold mul_mat_id in build_moe_ffn

    When a layer carries hot packs, routed ids are remapped through
    moe_map_hot/cold (get_rows) and each expert projection runs as two
    skip-flagged mul_mat_id ops — hot pack on GPU, original tensors for
    cold — whose zero-padded outputs sum to the exact single-tensor
    result. Engaged for qwen35moe (separate gate/up/down, no expert
    scales); layers with merged gate_up, scales, or no packs use the
    unchanged path.

    * fix: flatten routed ids before map get_rows (batched-gather shape rule)

    * fix: topk ids are a strided view - cont before flatten for map lookup

    * fix: sched expert-copy path skips id=-1 (hot/cold expert split)

    * fix: restructure MoE pack dual path into full FFN chains per residency side

    Per-projection hot/cold interleave let the scheduler's split minimizer
    assign hot up/down matmuls to CPU, copying the GPU pack weights over
    PCIe every layer. Building one unbroken gate-up-swiglu-down chain per
    side keeps the hot pack on GPU; skipped (-1) rows stay zero through
    swiglu so a single add of the two chain outputs is exact.

    * feat: wire MoE expert cache into deepseek2 graph (GLM-4.7-Flash)

    * feat: add --moe-cache-profile and --moe-cache-slots flags

    Plumbed through llama_model_params; env vars remain as fallback so
    existing deployments keep working. Flags allow per-model settings in
    multi-model serving.

    * docs: fix moe-trace usage comment (output path is MOE_TRACE_OUT env)

commit cd72c28
Author: Anirban Kar <[email protected]>
Date:   Fri Jul 24 17:53:41 2026 +0530

    fix: restore closing brace lost in dequantize.cuh merge resolution

commit 34f893e
Merge: 40f2036 8f5ab83
Author: Anirban Kar <[email protected]>
Date:   Fri Jul 24 17:52:26 2026 +0530

    merge: sync upstream master into perf

commit 8f5ab83
Author: Matt Thompson <[email protected]>
Date:   Fri Jul 24 03:54:47 2026 -0700

    cohere2 moe template parser: enforce JSON schema for text responses if a response schema is provided (ggml-org#26018)

commit 0cea362
Author: Xuan-Son Nguyen <[email protected]>
Date:   Fri Jul 24 08:02:23 2026 +0200

    vendor: update subprocess.h (ggml-org#26061)

commit 40f2036
Author: Anirban Kar <[email protected]>
Date:   Sun Jul 19 04:34:24 2026 +0530

    feat: fused turbo MMA flash-attention decode (turbo4/3/2, GQA tensor-core path) (TheTom#4)

    * feat(fattn): fused turbo4 MMA decode path (opt-in) — based on the spiritbuun fork MMA approach, adapted to graph-rotated Q

    Port buun's fused turbo4 tensor-core (MMA) flash-attention DECODE kernel into
    the turbo fork as an OPT-IN path (GGML_TURBO_MMA_FUSED=1, default OFF), routing
    turbo4-K==turbo4-V, D in {128,256}, decode (Q->ne[1]<=4) onto the GQA-packed MMA
    path so KV is read once per head-group instead of once per query head.

    How it works:
    - fattn-mma-f16.cuh: add flash_attn_ext_turbo4_load_tile (dequant turbo4 blocks
      -> SRAM in the f16 row-major half2 layout) seeded with OUR Lloyd-Max centroids
      (turbo-quant.cuh:297, NOT buun's -0.2415xx table). Thread type_K/type_V through
      iter/process_tile/global flash_attn_ext_f16 (defaults F16 -> existing f16/q8 MMA
      byte-identical). For turbo: force nstages=0 (the cp.async multi-stage path would
      read raw turbo bytes as half2), pass RAW byte pitch nb11/nb21 (not /sizeof(half2)),
      and dequantize K/V in the load tiles. sizeof(block_turbo4_0)-driven pointer math
      (66B block, no rnorm) — never assumes a fixed offset.
    - fattn-mma-turbo.cuh + 14 instance files (7 reachable ncols pairs x D in {128,256}):
      host launcher reusing the f16 device kernel with type_K/type_V=TURBO4_0 and
      need_f16_K/V=false so launch_fattn does NOT pre-convert KV to f16.
    - fattn.cu: switch_ncols2 -> per-ncols2 dispatchers (only the 7 compiled instances),
      env latch, and the gate (Q untouched — our fork already rotates Q at the graph
      level, so NO inline FWHT / src swap, which would double-rotate Q).

    Results (Qwen3.6-35B-A3B turbo4, GQA8, D=256, 5090):
      depth   MMA      VEC+PDL   buun
      8192    213.8    188.5     200    (+6.9% vs buun)
      16384   207.6    171.7     193    (+7.5% vs buun)
      32768   191.3    141.1     187    (+2.3% vs buun)
    MMA holds flat at depth where VEC collapses; the gap vs VEC grows with KV length.

    Quality: Mean KLD vs f16 base = 0.008396 (== VEC baseline). The MMA path is NOT
    strictly token-identical to VEC — MMA and VEC accumulate the P*V (VKQ) reduction in
    f16 with different reduction trees, so a near-tie greedy token can flip (~1/25 on a
    hard tie; same irreducible f16-order effect that exists between base f16-MMA and
    f16-VEC, and within the VEC-vs-base "same-top-p" 96.3% noise floor). Because strict
    token-identity does not hold, the gate DEFAULTS OFF and ships as opt-in; VEC remains
    the untouched default/kill-switch.

    (cherry picked from commit 5450669510a5cd0a356a863923b057f2552c6fbb)
    (cherry picked from commit b3e51cf)

    * turbo4 MMA decode: default ON (GQA-packed tensor-core path, quality-neutral; GGML_TURBO_MMA_FUSED=0 kill-switch)

    (cherry picked from commit 726234b538194c644be4066e1413b91f9edf12e7)
    (cherry picked from commit 38dc665)

    * fattn: extend fused MMA decode to turbo3 + turbo2 (parity on turbo4; extends the MMA path to turbo3/2)

    The GQA-packed tensor-core decode path was turbo4-only; turbo3/turbo2 fell back to
    VEC and collapsed at depth (turbo3 tg32 224->124 from d2048->d32768), losing to
    spiritbuun there. Added flash_attn_ext_turbo3_load_tile (3-bit split index: 2 low
    bits from qs + 1 high bit from signs) and flash_attn_ext_turbo2_load_tile (plain
    2-bit), type-dispatched both the K and V MMA load sites, and routed the gate by
    K->type. is_turbo_kv already matches any non-f16 KV, so the kernel needed only the
    per-type tile loaders + instances (14 instance files now emit all three types).

    Correctness: MMA decode is bit-exact to VEC (Mean KLD @2048 chunks=8:
    turbo3 0.020278==0.020278, turbo2 0.041490==0.041490, turbo4 0.009296 unchanged).

    Decode tg32 (qwen3.6-35B-A3B, RTX 5090), MMA now flat at depth:
      turbo3  2k/8k/16k/32k = 224/225/217/203  (buun 193/193/183/178; was VEC 224/187/160/124)
      turbo2  2k/8k/16k/32k = 228/224/217/203  (buun 213/210/204/200; was VEC 229/218/203/183)

    turbo3/turbo2 now hold flat at depth (neither fork had them on the MMA path before). GGML_TURBO_MMA_FUSED=0 restores VEC.

    (cherry picked from commit 57ad5edd53a7fced0b99fecb99326132cbdb65d0)
    (cherry picked from commit 4e223ee)

    * fix(fattn): gate turbo2 fused-MMA decode to head_dim 128

    Tester @everson isolated a turbo2-only decode regression on RTX 5060 Ti
    (Gemma-12B, head_dim 256): turbo2/turbo2 -2.46% at 8K to -1.17% at 200K,
    fully restored by GGML_TURBO_MMA_FUSED=0 at every depth, while turbo3 was
    neutral and turbo4 exact parity. At 2-bit KV the fused path's GQA-pack
    saving is tiny while its dequant/no-pipeline overhead is unchanged, so on
    head_dim 256 it is neutral on high-bandwidth GPUs (Ornith-35B and a dense
    Gemma-4-12B on RTX 5090, both within noise) and only costs on
    bandwidth-limited cards.

    turbo2 fused remains a large depth win on dense head_dim 128 (Llama-3.1-8B
    on RTX 5090: +7% at 8K, +24% at 32K, +69% at 131K), so this gates turbo2
    fused to head_dim 128 only; head_dim 256 turbo2 falls through to VEC, which
    is the exact baseline path GGML_TURBO_MMA_FUSED=0 restored. turbo3 and
    turbo4 fused are unchanged at both head dims.

    Also corrects the stale "default OFF" gate comments to match the
    default-ON code.

    (cherry picked from commit 539ce5d)

    ---------

    Co-authored-by: TheTom <[email protected]>

commit 4cd54c6
Author: Anirban Kar <[email protected]>
Date:   Sun Jul 19 04:14:41 2026 +0530

    fix: allow mixed turbo/q8_0 KV cache types in CUDA flash-attention selection (TheTom#3)

    * fix: allow mixed turbo/q8_0 KV cache types in CUDA flash-attention selection

    Without GGML_CUDA_FA_ALL_QUANTS (the default), kernel selection
    rejected any K/V type mismatch. A turbo KV setup is almost always
    mixed (ctk q8_0 + ctv turbo2/3), so the flash-attention probe failed,
    FA was auto-disabled, and context creation either refused the
    quantized V cache outright or fell back to the non-FA path whose
    KQ buffer (~8.7 GiB at 64k ctx, ubatch 1024) OOMs at load.

    Allow exactly the mixed pairs that have FA template instances
    compiled in: turbo2/3/4 against each other, q8_0, and f16. Also gate
    turbo head-dim geometry (multiples of 64; 128 for turbo4) so shapes
    without a compiled instance report unsupported instead of asserting
    at dispatch.

    Forcing -fa on masked the bug (the probe is skipped); server
    deployments use fa auto and hit it on every load.

    * feat: accept turbo2/3/4 cache type names in llama-bench

    The common arg parser already accepts them for llama-completion and
    llama-server; llama-bench has its own name table and rejected -ctk/-ctv
    turbo values.

commit 9338207
Author: Anirban Kar <[email protected]>
Date:   Sun Jul 19 01:59:58 2026 +0530

    CUDA: add Q2_0 support (TheTom#2)

    Co-authored-by: Pasha Khosravi <[email protected]>

commit 170322f
Author: Anirban Kar <[email protected]>
Date:   Sat Jul 18 15:27:13 2026 +0530

    feat: TurboQuant KV-cache quantization — all backends (TheTom#1)

    * feat: TurboQuant KV-cache quantization — core types + CPU backend

    Port of the TurboQuant codec (arXiv 2504.19874, reference:
    TheTom/llama-cpp-turboquant) onto this fork's base: WHT-rotated polar
    quantization for the KV cache.

    - new types TURBO2_0/TURBO3_0/TURBO4_0 (KV, 2/3/4-bit blocks of 128)
      and TQ3_1S/TQ4_1S (WHT-rotated Lloyd-Max weight formats), renumbered
      for this tree's type table
    - GGML_OP_TURBO_WHT + ggml_turbo_wht() builder (forward/inverse
      Walsh-Hadamard rotation with sign arrays, InnerQ scale hook)
    - ggml-turbo-quant.c codec core, rotation data tables, CPU op +
      vec_dot paths, type traits, quantize-chunk wiring
    - CUDA/Metal/Vulkan kernel sources imported (wired in follow-ups)
    - verified: test-turbo-quant round-trip on CPU (cosine 0.986-0.996)

    * feat: turbo KV cache — graph wiring and CLI types

    - pre-rotate Q (forward WHT) at every cache-backed attention site when
      K is a turbo type; no-op otherwise
    - inverse WHT on attention output in both FA and non-FA paths of
      build_attn_mha (group size derived from K, contiguity enforced)
    - register turbo2/3/4 as --cache-type-k/--cache-type-v values
    Core scope: no InnerQ scaling, no head-dim padding — turbo KV requires
    128-aligned (or 64-group) head dims

    * feat: turbo KV cache — Metal backend (WHT kernel + FA dispatch)

    Wire the TurboQuant Metal backend host side and kernels on top of the
    CPU core already on this branch.

    Metal kernels (ggml-metal.metal):
    - Inlined turbo-wht.h (WHT sign arrays incl. half4 variants + FWHT
      butterfly + rotate fwd/inverse) and the turbo2/3/4 centroids.
    - quantize/dequantize_turbo2_0/3_0/4_0 (+_t4) and full-block cache.
    - kernel_turbo_wht (O(d log d) Walsh-Hadamard rotation op) and
      kernel_turbo4_dequant_f16 bulk prefill dequant.
    - kernel_set_rows_turbo/2/4 cache-quantize kernels + instantiations.
    - flash_attn_ext / flash_attn_ext_vec instantiations for symmetric and
      asymmetric turbo2/3/4 and q8_0<->turbo pairs.
    - TurboFlash two-pass kernels (p1/p2), default-disabled via env.

    Host side:
    - ggml-metal-device.cpp: get_pipeline_turbo_wht; flash-attn pipeline
      base names now encode both K and V types (k%s_v%s) so asymmetric K/V
      pairs resolve unambiguously. All existing FA kernel host_names in the
      shader renamed to match.
    - ggml-metal-device.m: TurboQuant compile-time env prep (4-mag LUT auto
      select, sparse-V, profile mode); supports_op accepts turbo K types and
      asymmetric turbo/q8_0 FA pairs; GGML_OP_TURBO_WHT.
    - ggml-metal-ops.cpp: GGML_OP_TURBO_WHT encode case + impl; asymmetric
      K/V assert relaxation; TurboFlash gating (use_turbo_flash, extra_tmp
      sizing, force-nonvec) + two-pass dispatch; +128 float FA smem for the
      turbo block cache.
    - ggml-metal-impl.h / -device.h / -ops.h: kargs (turbo_wht,
      turbo_flash_p1/p2), FC offsets, pipeline/op declarations.

    Adaptations vs the reference tree (older upstream vintage):
    - Reference intertwines separate TQ3_1S/TQ4_1S weight-quant work; only
      the turbo KV-cache lines are ported here.
    - set_rows_turbo dispatch selection is not wired: our upstream refactored
      get_pipeline_set_rows/kernel_set_rows_q32 to a different signature, and
      it is out of scope for this KV port. supports_op therefore does not
      claim CPY/SET_ROWS turbo support, so cache writes fall back to CPU;
      the set_rows_turbo shader kernels are present for when dispatch lands.
    - No InnerQ scale tensors touched (graph passes nullptr scale).

    * feat: turbo KV cache — CUDA backend (set-rows quantize, fattn vec dispatch, dequant)

    Port the TurboQuant CUDA backend from the reference implementation, adapted
    to this newer upstream vintage:

    - set-rows.cu: k_set_rows_turbo2/3/4 kernels (WHT rotation + norm-corrected
      PolarQuant KV write, InnerQ calibration hooks) + dispatch. turbo4 rnorm
      write dropped (field removed from block_turbo4_0 on this branch).
    - dequantize.cuh: dequantize_turbo2/3/4_0 and dequantize_tq3_1s/tq4_1s
      device functions.
    - convert.cu: turbo + TQ dequant cases in the fp16/fp32 contiguous and
      non-contiguous dispatch tables; warp-cooperative TQ4_1S dequant kernel.
    - fattn-common.cuh: vec_dot_fattn_vec_KQ_turbo2/3/4_0, dequantize_V_turbo*
      and get_vec_dot_KQ / get_dequantize_V dispatch entries.
    - fattn-vec.cuh: turbo K types take the float-Q path (Q_q8_1 off), turbo V
      uses the ne=4 quantized dequant path; extern decls for the 21 compiled
      K/V type combinations. Reference-side perf extras (shared-mem centroid
      LUT, sparse-V skip, nthreads tuning) intentionally not ported.
    - fattn.cu: turbo types accepted in kv_type_supported, vec kernel cases
      registered. Decode goes through the VEC kernel; prefill converts KV to
      f16 via the ported nc dequant path.
    - fattn-mma-turbo.cuh: reduced to a stub launcher. No typed MMA kernel
      exists in the reference either; the pre-existing template instances now
      compile against the stub and the dispatcher never selects this path.
    - ggml-cuda.cu: GGML_OP_TURBO_WHT dispatch + supports_op, SET_ROWS turbo
      gates (head_dim % 64, turbo4 % 128).
    - CMakeLists.txt: turbo fattn-vec instances added to the non-FA_ALL_QUANTS
      build.

    Verified on RTX 3060 (sm_86) with Bonsai-27B-Q1_0, partial offload, fa on:
    coherent generation for turbo2/3/4; perplexity over 4 chunks:
    f16 KV 7.9486 +/- 0.73, turbo3 KV 8.0261 +/- 0.74 (CUDA) vs 8.0279 (CPU-only).

    * feat: turbo KV cache — Vulkan backend (set-rows quantize, turbo3 FA dispatch, WHT op)

    - register turbo_wht.comp and set_rows turbo2/3/4 quantize variants in
      vulkan-shaders-gen; add dedicated DATA_A_TURBO3_0 flash-attn SPIR-V
      (scalar + coopmat1) with turbo3-only K/V bindings
    - copy_to_quant: 128-thread per-block set_rows path (normalize, randomized
      WHT, Lloyd-Max centroid quantize, subgroup pack), shared WHT tables
      across the three turbo widths
    - flash_attn_dequant: turbo2/3/4 centroid dequant macros wired into the
      FaTypeK/FaTypeV runtime switch (ids 43/44/45); f16 K/V aliases guarded
      out under DATA_A_TURBO3_0
    - ggml-vulkan: GGML_OP_TURBO_WHT pipeline + dispatch, turbo set_rows
      pipelines (required subgroup size 32), FA pipeline selection for
      turbo3, supports_op gates (128-elem blocks, turbo3 K/V symmetry,
      scalar/coopmat1 only — cm2 falls back to scalar)

    * fix: extern initialization warning and C linkage for wht group size

    CI builds with -Werror: defining the GGML_API-decorated global with an
    initializer warns on every platform. Plain definition in the C TU; the
    C++ consumer now declares it extern "C" (it previously referenced a
    mangled symbol).

    * feat: turbo2/turbo4 FA dequant for Vulkan

    - generalize the dedicated turbo flash-attn SPIR-V path from turbo3-only
      to all three tiers: DATA_A_TURBO_KV umbrella define in types.glsl gates
      out the f16/q4/q5/q8 K/V binding aliases in flash_attn.comp,
      flash_attn_cm1.comp and flash_attn_dequant.glsl for any turbo tier
    - flash_attn_dequant: per-compilation dequantize4 for DATA_A_TURBO2_0
      (2-bit centroids, fp16 norm + 32B idx) and DATA_A_TURBO4_0 (4-bit
      nibble idx, fp16 norm + fp16 aux + 64B) alongside the turbo3 one
    - vulkan-shaders-gen: register flash_attn_f32_f16_turbo{2,4}_0 scalar +
      coopmat1 variants via a per-tier loop
    - ggml-vulkan: FA pipeline selection picks the matching turbo SPIR-V for
      turbo2/turbo4 k_type (scalar + cm1), supports_op requires symmetric
      K/V per tier (turbo2/turbo2, turbo3/turbo3, turbo4/turbo4)

    * fix: bump RPC proto patch version for GGML_OP_TURBO_WHT

    * fix: export WHT group size via GGML_API for Windows shared builds

    * fix: HIP/MUSA portability for turbo kernels

    - map cudaMemcpyToSymbol/FromSymbol and __ballot_sync in vendor headers
    - pass explicit width to __shfl*_sync (HIP macros take 4 args)
    - drop unused warp_id locals flagged by nvcc -Werror

    * fix: drop SYCL turbo fattn-vec instances (no turbo dequant support in SYCL fattn)

    * fix: size vec_dot buffer by vec_dot_type and handle turbo/tq types in quantize test

    - tmp_q2 overflowed for types with vec_dot_type F32 (4 bytes per element)
    - skip turbo KV types: they quantize in the rotated domain, round trip
      does not reproduce the input by design
    - tq3_1s uses the 3-bit and lowbit thresholds

    * fix: add turbo fattn-vec instances to HIP and MUSA source lists

    * fix: add turbo fattn vec kernels to HIP VGPR ignore list

    The gfx908 build of the ncols=2 turbo3 vec kernels lands at 259 total
    VGPRs, slightly over the 256 gate. Register them like the other known
    high-pressure fattn kernels.

commit 0888217
Merge: 5e7f627 7d56da7
Author: Anirban Kar <[email protected]>
Date:   Fri Jul 17 20:02:48 2026 +0530

    chore: sync perf with upstream master

commit 5e7f627
Author: Anirban Kar <[email protected]>
Date:   Wed Jul 8 23:56:46 2026 +0530

    docs(readme): add usage + benchmark instructions for the MoE-offload optimizations

commit 5f83fbb
Author: thecodacus <[email protected]>
Date:   Thu Jul 2 12:42:55 2026 +0000

    ggml : size prefetch slots per layer and fix fallback use-after-free

    Profiling showed the 2-slot rotation stalls ~5.5ms per layer waiting for
    the down_exps upload: 3 tensors per MoE layer need 3 slots for a full
    layer of lookahead. Default is now 3 (one layer), configurable via the
    env var value, degrading to however many slots fit on OOM.

    Also fixes a use-after-free: on a failed slot regrow the repointed
    staging tensors kept dangling pointers into freed device memory, which
    graph reuse carried into later evals. Staging repoints are now restored
    right after kernel launch, slots are sized once from the graph max, and
    allocation happens before freeing.

    Qwen3.6-35B-A3B pp2048 on RTX 3060: 1643 -> 1880 t/s (mainline: 1143).

commit 1163cb3
Author: thecodacus <[email protected]>
Date:   Thu Jul 2 12:16:39 2026 +0000

    ggml : overlap offloaded expert weight uploads with compute

    At large batch sizes virtually every expert is used, so the per-layer
    routing-ids readback that mainline waits on buys nothing while forcing a
    full device sync per expert tensor (3x per MoE layer). Above a batch
    threshold, upload the full expert tensors through a second backend
    instance on the same device (own stream) with two event-ordered staging
    slots, so uploads for tensor N+1 overlap compute of tensor N.

    Qwen3.6-35B-A3B pp2048 on RTX 3060 (-ncmoe 26, ub 2048): 1383 -> 1663 t/s.
    Generation output verified token-identical; decode path unaffected.
    Opt-in via GGML_SCHED_PREFETCH_EXPERTS=1.

commit 20f5994
Author: thecodacus <[email protected]>
Date:   Thu Jul 2 09:44:53 2026 +0000

    llama : pin mmap-backed CPU weights for faster H2D uploads

    Wire the existing GGML_CUDA_REGISTER_HOST path back up: after model load,
    cudaHostRegister the mmap pages backing weights kept in system memory.
    Recovers pageable-copy losses when MoE experts are streamed to the GPU
    during prefill (n-cpu-moe): Qwen3.6-35B-A3B pp2048 1144 -> 1385 t/s on
    RTX 3060. Opt-in via GGML_CUDA_REGISTER_HOST=1, unchanged otherwise.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants