Skip to content

perf(kv): quantize Turbo4 KV on device and decode packed rows on CUDA - #3500

Merged
inureyes merged 3 commits into
lablup:mainfrom
Jaeyeong-CHOI:perf/3272-turbo4-kv-on-device
Nov 28, 2026
Merged

inureyes merged 3 commits into
lablup:mainfrom
Jaeyeong-CHOI:perf/3272-turbo4-kv-on-device

Conversation

@Jaeyeong-CHOI

Copy link
Copy Markdown
Contributor

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

  • Dense Turbo4 and the MLA latent codec share the 4-bit packing and rescale calculation. They use perf(kv): run the Turbo3Asym quantize and dequantize on device #3497’s strict boundary-count lookup, including the lower index at a boundary and index zero for NaN. Even coordinates occupy the low nibble. The former scalar codec serves as the test reference.
  • One CUDA block per batch element and query head accumulates 32 softmax partials in FP32. Asymmetric and delegated modes read dense K. Symmetric mode decodes K and derives its scale from the stored norm in the same pass. The kernel reads cold V from packed bytes and an fp16 rescale, and reads delegated hot V in the rotated basis. The caller inverse-rotates the output row.
  • The three dense cache paths dispatch after update. The pure predicate covers switch, backend port, mode, mask, query length, head geometry and grid bounds. The prior attention route handles unsupported cases and the switch-off control. The environment reference and ADR 0002 document the decision.

GB10 measurements

Baseline 944dbfc2d, fix 3c8ef2ad1, tested tree b2690cf3f. 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.

Effective mode Gate A layer / step (16K) Gate B savings (16K / 32K)
Turbo4Asym 86.74% / 81.52% 53.68% / 44.75%
Turbo4 110.43% / 99.83% 73.34% / 76.82%
Turbo4Delegated 98.01% / 90.98% 35.88% / 49.12%

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

Mode 4,096 16,384 32,768
fp16 42.92 → 42.93 32.37 → 32.34 24.28 → 24.21
Turbo4Asym 17.22 → 34.13 8.89 → 20.22 5.55 → 12.86
Turbo4 (DirectEngine) 11.03 → 29.98 4.57 → 16.52 2.62 → 10.50
Turbo4Delegated 27.96 → 34.44 10.40 → 19.15 5.74 → 11.92
CLI turbo4 → asym 17.33 → 34.12 8.88 → 20.19 5.56 → 12.85
cargo run --locked --release --features cuda --example turbo_kv_dequant_share_bench -- \
  --model "$MODEL" --contexts 4096,16384,32768 --csv layer.csv
mlxcel-bench-decode -m "$MODEL" -p x --prompt-tokens "$CONTEXT" -n 128 --ignore-eos --kv-cache-mode "$MODE"
MLXCEL_TURBO_PACKED_ATTENTION=0 mlxcel-bench-decode -m "$MODEL" -p x --prompt-tokens 16384 -n 128 --ignore-eos --kv-cache-mode turbo4-asym

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 generate and mlxcel-server for 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

  • The standalone source guard failed on main at ffi::eval and 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.
  • Fixed-seed K/V packed bytes and fp16 norm bits matched the host reference for D=64/128/256 and T=1/4096. The Turbo4Asym cache also matched after prefill and two decode writes through KVCache::attend. Twelve of 24,582 rescale values rounded differently. Maximum relative error was 0.0008976661 (limit 0.001).
  • Over 64 production KVCache::attend decode 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.
  • For two prompts at each of 4K, 16K and 32K, all 64 generated token IDs and the decoded text agreed on 6/6 fp16 and 6/6 delegated pairs, 2/6 asymmetric pairs, and 2/6 true symmetric pairs. The stock turbo4 alias 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

  • Boundaries. Tests cover empty batch/head/token axes and visible length, zero norm, the first hot-only delegated row, all 15 exact ties and both adjacent floats, infinities, NaN, GQA and launch limits.
  • Large inputs. The index lookup makes 15 comparisons per coordinate, so cost is linear in rows and head dimension. The fixed-seed D=256, T=4096 case covers over a million coordinates. Packed attention sweeps each visible row once per query head and uses bounded CTA shared memory. The 32K decode and T=16384 quantization runs exercise both paths.
  • Shared callers. The six dense V writers cover asymmetric and symmetric updates, two hot-to-cold folds, unified-V range folding and rotating-cache asymmetric updates. Symmetric K supplies its own signs and discards the unused V rescale. MLA latent packing uses its cached device arrays. MLA query rotation and the rotated affine latent codec share the FP32 rotation, including its empty-row path.
  • Formatting. cargo fmt --all -- --check passed on the same tree as the Spark2 verification.

Spark2 verification

Command Result
cargo fmt --all -- --check Passed
cargo clippy --locked --workspace --all-targets --features cuda -- -D warnings and make clippy Both passed
cargo test --locked -p mlxcel-core --profile test-fast --features cuda --lib turbo -- --test-threads=1 --nocapture 275 passed
make test-fast-cuda FILTER=turbo 65 passed, 7 ignored
make release-cuda Passed
make verify-test-cuda with a private mode-0700 TMPDIR 17,443 passed, 5 failed, 517 ignored across 199 harness summaries, including two nested single-test subprocess summaries
cargo test --locked -p mlxcel-core --no-default-features --profile test-fast --lib <filter> -- --test-threads=1 Passed separately for turbo_packed_decode_route_declines_unsupported_inputs and attend_stores_host_turbo4_rows_after_prefill_and_decode

Only -p mlxcel --lib failed the full gate. The main library harness reported 13,105 passed, 5 failed and 254 ignored. On clean main 944dbfc2d, I reran the following five names in one test process with cargo 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_does
  • models::raon1_mini::speculative::tests::a_verify_block_equals_the_decode_chain_byte_for_byte
  • models::raon1_mini::speculative::tests::rollback_after_a_partial_accept_equals_a_fresh_decode_of_the_accepted_tokens
  • models::raon1_mini::speculative::tests::the_exactness_probe_passes_on_the_tiny_model
  • models::raon_mhc::tests::compiled_site_equals_the_eager_site_bit_for_bit

The DeepSeek-V3.2 YaRN prefill/decode regression and both Plamo2 validation tests, emit_all_reproduces_registered_goldens and registered_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.py and bash scripts/ci/check_used_by_test.sh. The Python checks ran as python3 scripts/ci/check_<name>.py. Cross-repository references took 15c341671 as the base, and the WebUI contract and evidence scripts took --self-test. The contract used an existing Python environment with referencing and passed 49 fixtures. The shell fixtures ran as bash scripts/ci/<name>_test.sh.

The clean Spark2 checkout was 3c8ef2ad115945cda1e1508560b8c1beed0b6d68, tree b2690cf3f65ecc881c95b899f4da2a3a2b883f19, before and after verification. The final fetch still placed origin/main at 944dbfc2d. git merge-tree --write-tree origin/main HEAD returned 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.

`--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.
@inureyes inureyes added status:review Under review type:performance Performance improvements priority:low Low priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) area:benchmark Benchmark harness and performance measurement (bench_*.sh, /update-benchmarks) labels Nov 28, 2026
# Conflicts:
#	docs/benchmark_results/README.md
#	src/lib/mlxcel-core/src/cache/turbo/codebook.rs
@inureyes
inureyes merged commit 4514cc8 into lablup:main Nov 28, 2026
19 checks passed
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 28, 2026
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:benchmark Benchmark harness and performance measurement (bench_*.sh, /update-benchmarks) area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) priority:low Low priority status:done Completed type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf: Turbo KV dequant-free decode attention and on-device quantize

2 participants