Repository navigation
perf(kv): quantize Turbo4 KV on device and decode packed rows on CUDA - #3500
Merged
inureyes merged 3 commits intoNov 28, 2026
Merged
Conversation
`--kv-cache-mode turbo3-asym` (fp16 K, 3-bit PolarQuant V) left the device in both halves of its codec. `quantize_v_turbo3` evaluated the rotated coordinates and looked the centroids up on the CPU. `dequantize_v_turbo3` evaluated the whole visible packed window, unpacked it on one CPU thread and uploaded the indices again, once per Turbo3 layer per decode step and once per layer per prefill chunk. Issue lablup#3274 asks for the share of that cost on GB10 first and for device ops second. Measured on GB10 with Llama 3.1 8B 4-bit (28 Turbo3 layers) at `944dbfc2d`: the dequantizer's host segment was 6.3 / 22.2 / 51.2 ms per layer at 4096 / 16384 / 32768 visible tokens, which is 76% / 78% / 82% of the decode step, and the mode decoded at 4.35 / 1.25 / 0.57 tok/s against 44.1 / 33.1 / 24.5 for fp16. Both host segments are now device ops. `boundary_indices_on_device` (codebook.rs) counts the boundaries strictly below each rotated coordinate, the rule the host lookup implements and the one piece shared with lablup#3272. `pack_3bit_on_device` and `unpack_3bit_on_device` (pack3.rs) express the 24-bit group layout with shifts, ORs and masks over a UINT32 lane. Neither `quantize_v_turbo3` nor `dequantize_v_turbo3` evaluates the graph or copies tensor data to the host any more. The float ops are untouched and in the same order, and the stored `v_packed` and `v_norms` are byte for byte what the host codec wrote, so detached caches and the layout lablup#3250 will snapshot are unaffected. The earlier bodies are kept as a `#[cfg(test)]` host reference. A zero-token input, which aborted inside MLX's Hadamard transform before this change as well, now returns empty tensors. - Decode on GB10, B=1, three runs per cell: 4.35 to 18.01 tok/s at 4096 tokens, 1.25 to 4.75 at 16384, 0.57 to 2.48 at 32768 (4.1x / 3.8x / 4.4x), and 15.87 to 37.02 at 256. The end-to-end drop of the decode step (76% / 74% / 77%) matches the share the stage timers gave. Prefill is 2.4x to 3.0x faster. fp16 is within 0.6% on both trees. Nine greedy replies from the server (two prose prompts per context for `turbo3-asym`, one for fp16) are identical between the trees. Four concurrent server requests were served one after another on both trees, so no batched step was timed. - What remains is the device dequantize of the visible window: the mode decodes at 0.41x / 0.14x / 0.10x of fp16 (was 0.10x / 0.04x / 0.02x). A dequant-free Turbo3 attention route is left to a follow-up, as the issue says. - Tests hold the device codec to the host reference bit for bit: packed bytes, norms and dequantized V at head dims 64, 128 and 256 with an all-zero token and coordinates exactly on every boundary; a `Turbo3Asym` cache through `KVCache::attend` for a 64-token prefill and 64 decode steps; update chunks of 0, 1 and across the 256-token block edge; trim and detach/adopt. A source guard fails if either function gains an `eval`, an `array_to_raw_bytes` or a `from_bytes` again. - An nsys trace at 4096 tokens shows 54.4 forced synchronizations per decode token on `main` and none on the branch; graph launches per token are unchanged (148 and 147), because the graph byte budget already cuts the step that often. - `examples/turbo3_readback_share_bench.rs` times the host segments against the device work and builds on both sides of this change. The record is `docs/benchmark_results/turbo3-readback-share-gb10-2026-11-27.md`. Not run on Metal or ROCm. Closes lablup#3274
Use the shared boundary-count lookup for dense and latent Turbo4 rows. Pack the indices and derive the fp16 rescale on device, avoiding the two host transfers per cache write. On GB10 the packed attention prototype passed both the per-layer share and latency gates. Decode unmasked single-token queries directly from the cold buffers and retain dequant-first SDPA as a switchable fallback. Record the GB10 timings, route traces and numerical comparisons.
This was referenced Nov 28, 2026
# Conflicts: # docs/benchmark_results/README.md # src/lib/mlxcel-core/src/cache/turbo/codebook.rs
4 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Closes #3272.
Depends on #3497.
Keep Turbo4 K/V quantization on device and decode unmasked single-token queries directly from the packed CUDA cache. At 16,384 tokens on GB10, the layer benchmark and end-to-end decode cleared both gates in each of the three Turbo modes. Asymmetric decode improved from 8.89 to 20.22 tok/s on Meta-Llama-3.1-8B-Instruct-4bit.
What changed
GB10 measurements
Baseline
944dbfc2d, fix3c8ef2ad1, tested treeb2690cf3f. The checkpoint has 32 layers, 28 Turbo layers, 32 query heads, eight KV heads and head dimension 128. Gate A uses the isolated dequant time divided by the full reference call, then the same isolated time multiplied by 28 and divided by the decode step. Each graph is separately evaluated and synchronized. These attribution estimates can exceed 100%. Gate B uses the 32-warp prototype, including rotations, relative to the full reference call.Median decode tok/s on main → fix, three independent processes per cell, generating 128 tokens. The measurement record includes min–max for every cell, the synchronized layer timings, and the raw CSVs. GB10 benchmark record
The one switch-off asymmetric run at 16K gave 10.99 tok/s on the fix. Nsight Systems counted 196 packed launches on and zero off on both
mlxcel generateandmlxcel-serverfor each requested Turbo mode on Llama (eight generated tokens). The true symmetric engine diagnostic also counted 196 / 0.The instrumented main quantizer executed two blocking evaluations and two host byte reads per call. The median combined fraction was 31.43%, 68.08% and 64.95% at T=1, 4096 and 16384. The ranges of the three process medians were 19.87–48.65%, 67.99–68.40% and 64.94–65.02%, respectively. All 180 fix calls recorded zero evaluations and zero reads inside the codec. Uninstrumented median time was 624.2 → 767.0 µs, 73.32 → 6.42 ms and 327.62 → 18.15 ms respectively. The one-token ranges overlapped.
Correctness
ffi::evaland passed on the fix. Main exited 134 when the Hadamard transform received an FP16 tensor of shape [1,1,0,64]. Dense and MLA empty-row tests passed on the fix.KVCache::attend. Twelve of 24,582 rescale values rounded differently. Maximum relative error was 0.0008976661 (limit 0.001).KVCache::attenddecode steps at B=2 and GQA 4:2, maximum RMS was 0.0002128040 for asym (D=64), 0.0002252933 for symmetric (D=128), and 0.0002054454 for delegated (D=256). The limit is 0.005. Each cache executed the packed call 64 times. A neutral additive mask selected reference SDPA on the comparison cache.turbo4alias agreed on 2/6. With packed attention disabled, 3/6 asymmetric pairs agreed and the four previously divergent true symmetric pairs still differed. The issue's tolerance applies to attention RMS. The CSV records each output hash and first divergence.Maintainer review checks
cargo fmt --all -- --checkpassed on the same tree as the Spark2 verification.Spark2 verification
cargo fmt --all -- --checkcargo clippy --locked --workspace --all-targets --features cuda -- -D warningsandmake clippycargo test --locked -p mlxcel-core --profile test-fast --features cuda --lib turbo -- --test-threads=1 --nocapturemake test-fast-cuda FILTER=turbomake release-cudamake verify-test-cudawith a private mode-0700TMPDIRcargo test --locked -p mlxcel-core --no-default-features --profile test-fast --lib <filter> -- --test-threads=1turbo_packed_decode_route_declines_unsupported_inputsandattend_stores_host_turbo4_rows_after_prefill_and_decodeOnly
-p mlxcel --libfailed the full gate. The main library harness reported 13,105 passed, 5 failed and 254 ignored. On clean main944dbfc2d, I reran the following five names in one test process withcargo test --locked --profile test-fast --features cuda --workspace --lib --no-fail-fast -- --test-threads=1 --exact <names>. Each failed at the same position with the same assertion values on both revisions.models::raon1_mini::speculative::tests::a_steered_verify_block_applies_the_alpha_exactly_as_decode_doesmodels::raon1_mini::speculative::tests::a_verify_block_equals_the_decode_chain_byte_for_bytemodels::raon1_mini::speculative::tests::rollback_after_a_partial_accept_equals_a_fresh_decode_of_the_accepted_tokensmodels::raon1_mini::speculative::tests::the_exactness_probe_passes_on_the_tiny_modelmodels::raon_mhc::tests::compiled_site_equals_the_eager_site_bit_for_bitThe DeepSeek-V3.2 YaRN prefill/decode regression and both Plamo2 validation tests,
emit_all_reproduces_registered_goldensandregistered_fixtures_are_byte_exact, passed in the full gate.All 28 repository CI checker and fixture invocations passed, including
python3 scripts/ci/check_used_by.pyandbash scripts/ci/check_used_by_test.sh. The Python checks ran aspython3 scripts/ci/check_<name>.py. Cross-repository references took15c341671as the base, and the WebUI contract and evidence scripts took--self-test. The contract used an existing Python environment withreferencingand passed 49 fixtures. The shell fixtures ran asbash scripts/ci/<name>_test.sh.The clean Spark2 checkout was
3c8ef2ad115945cda1e1508560b8c1beed0b6d68, treeb2690cf3f65ecc881c95b899f4da2a3a2b883f19, before and after verification. The final fetch still placedorigin/mainat944dbfc2d.git merge-tree --write-tree origin/main HEADreturned that same tested tree.Verification limits
The stock Llama resolver selects asymmetric Turbo4 for a symmetric request. The true symmetric diagnostic passes that mode directly to the same engine. Qwen3.5-4B accepted symmetric mode but its full-attention layers use
update_and_fetch. Both stock entry points recorded zero packed launches on and off. Extending that family or changing the allowlist exceeds the issue's scope. Before the first delegated fold, attention uses native FP16. The additional empty-input rotation avoids MLX’s positive-size Hadamard precondition.The checked-in example times the quantizer and a copy-only control. A scratch example with GNU linker wrappers measured actual internal evaluations and transfers on the baseline and fix. Per-mode timing represents one GB10 and one Llama checkpoint. Apple Silicon and HIP hardware were unavailable.