Repository navigation
perf(kv): run the Turbo3Asym quantize and dequantize on device - #3497
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
# Conflicts: # docs/benchmark_results/README.md
The entry was written before v0.9.0-beta.3 was cut and landed in the released section after merging main. It belongs under Unreleased, Changed.
Hardening reviewReviewed against #3274. The device codec is bit-identical to the host codec: the boundary count ( Pushed (
|
…#3500) Turbo4 K/V quantization stays on the device, and unmasked single-token decode queries read the packed CUDA cache directly through a new fused attention kernel (one block per batch element and query head, FP32 softmax partials) instead of dequantizing the cold rows first. Dense Turbo4 and the MLA latent codec share the 4-bit packing and #3497's boundary-count lookup, with the former scalar codec kept as the test reference. Merged on the maintainer's instruction without a fresh local CUDA run: the branch was brought onto main by merging main into it, with the resulting tree set equal to a clean cherry-pick of the PR's own commit onto current main (the stacked #3497 commit is already on main as `241a59a3`), so main..head is exactly the PR's 28-file change. The upcoming MLX pin change in #3517 would force the same rebuild and revalidation again. Closes #3272
Summary
Closes #3274.
--kv-cache-mode turbo3-asymleft the device in both halves of its codec.quantize_v_turbo3evaluated the rotated coordinates and looked the centroids up on the CPU, anddequantize_v_turbo3evaluated the whole visible packed window, unpacked it on one CPU thread and uploaded the indices again, once per Turbo3 layer per decode step. This PR measures that cost on GB10 and then moves the index, pack and unpack steps to device ops. The stored bytes are unchanged.GB10, Llama 3.1 8B 4-bit (28 Turbo3 layers), B=1, median of three runs per cell:
mainmainmainThe share is 28 times the dequantizer's host segment (6.3 / 22.2 / 51.2 ms per layer) over the decode step (229.9 / 800.0 / 1754.4 ms). The decode step itself dropped by 76% / 74% / 77% end to end, so the two measurements agree. On the branch the codec has no host segment. Prefill of the same runs is 2.5x / 2.4x / 2.4x faster. Nine greedy 64-token replies from the server (two prose prompts per context for
turbo3-asym, one per context for fp16) are character for character the same onmainand on the branch. An nsys trace at 4096 tokens shows 54.4 forced synchronizations per decode token onmainand none on the branch.What changed
src/lib/mlxcel-core/src/cache/turbo/codebook.rs:pub(crate) fn boundary_indices_on_device(x, boundaries), next tonearest_centroid_indices_with_boundaries.astype(sum_axis(greater(expand_dims(x, -1), boundaries), -1, false), UINT8): the index of a value is the number of boundaries strictly below it. This is the one rule shared with perf: Turbo KV dequant-free decode attention and on-device quantize #3272.src/lib/mlxcel-core/src/cache/turbo/pack3.rs:pub(crate) fn pack_3bit_on_device(idx_u8, head_dim)andpub(crate) fn unpack_3bit_on_device(packed_u8, head_dim), the device forms ofpack_3bit_per_tokenandunpack_3bit_per_token. The host functions stay and are the reference in the tests. The module docs no longer say the device form is deferred.src/lib/mlxcel-core/src/cache/turbo/quant3.rs:quantize_v_turbo3callsboundary_indices_on_deviceandpack_3bit_on_device;dequantize_v_turbo3callsunpack_3bit_on_device. Neither containsffi::eval,array_to_raw_bytesorfrom_bytesany more. The float ops (norm, rotation, centroid gather, norm correction, inverse rotation, rescale) are untouched and in the same order. The earlier bodies are kept verbatim in#[cfg(test)] mod host_reference. No env kill switch, as the issue decides.src/lib/mlxcel-core/src/cache/turbo_tests.rs: real-path and boundary tests on aTurbo3AsymKVCache.examples/turbo3_readback_share_bench.rs: the measurement example the issue asks for.docs/benchmark_results/turbo3-readback-share-gb10-2026-11-27.mdwith CSV rows underdocs/benchmark_results/data/turbo3-readback-share-gb10-2026-11-27/, a line in the benchmark index, a paragraph indocs/turbo-kv-cache.mdand aCHANGELOG.mdentry.Where this differs from the issue text
[B, H, 0, ...]must flow through without error)" as an edge case. They cannot flow through: MLX's Hadamard transform throws[hadamard_transform] Does not support empty arrays., and the bridge call isnoexcept, so the process aborts with SIGABRT. The pre-change body does the same (the transform runs before the readback); a scratch test that called the kept host reference withT = 0died that way. Both functions now return the empty result directly whenT == 0, after the shape and sign-length asserts. This is the one behaviour change: an input that aborted now returns[B, H, 0, D*3/8],[B, H, 0, 1]and[B, H, 0, D].(word >> shifts) & 7and then a cast to UINT8.unpack_3bit_on_devicecastsword >> shiftsto UINT8 first and masks the bytes, which is the same value (the mask reads the low three bits) and drops one UINT32[B, H, T, D/8, 8]intermediate. In a scratch timing of four graph shapes at the Llama 3.1 8B layer shape the difference between them was inside the spread at 4096 tokens and about 10% at 16384 and 32768 (medians 5.0 ms against 5.7 ms at 32768); all four were about 9 times faster than the host segment. The scratch test is not in the commit.pack_3bit_on_devicemasks each index to 3 bits, aspack_3bit_indicesdoes on the host. The issue's op list has no mask. Without it an out-of-range index would OR into its neighbour's bits where the host drops the high bits; with it the two agree on everyu8input, which the test checks.boundary_indices_on_device, so the count fits the UINT8 result. The 3-bit codebook has 7 and the 4-bit one 15.quantize_v_turbo3(n_centroids > 0andboundaries.len() == n_centroids - 1), becausenearest_centroid_indices_with_boundariesmade them on every call and that call is gone. Thedebug_asserton the centroid count stays adebug_assert.main(to get the "before" numbers) and on the branch.dequant_host_segmentandquant_host_segmentare built from the public host helpers. The full-call rows timedequantize_v_turbo3andquantize_v_turbo3as built, so they contain the host segment onmainand do not on the branch.--quant-tokens 1,2048,4096,16384), because 2048 is the default prefill chunk and so the size the quantizer actually sees during a long prefill. The example's defaults are the issue's 1, 4096 and 16384.cudaEventSynchronizecalls per decode token onmain(about two per Turbo3 layer, one perevalin the codec) and 0.0 on the branch. The number ofcudaGraphLaunchcalls per token did not change (148 and 147): the graph byte budget already cuts the step's graph that often at a 4096-token context. NocudaMemcpyis attributable to a decode token on either tree; on GB10's unified memory the readback is host time, not a device copy.--parallel 4and four concurrent requests the server handled them one after another on both trees, for fp16 as well (the first tokens are a full request apart), so there is no B=4 decode step to report. The table is in the record. I did not look into why that server did not batch them.944dbfc2-dirtyas their commit, because they were measured on the code of this commit before the commit (which contains the record) existed. The commit's rebuild is compared with the measured binaries under "Verification".Every other caller
grep -rnE "quantize_v_turbo3|dequantize_v_turbo3|unpack_3bit|pack_3bit|nearest_centroid_indices|TurboQuantParams3|Turbo3Asym"oversrc,examplesandbenches:KVCache::update_turbo3_asym(cache.rs)quantize_v_turbo3KVCache::update_and_fetch,Turbo3Asymarm (cache.rs)dequantize_v_turbo3KVCache::attend/attend_dense(cache/attend.rs)update_and_fetchplus SDPA, for decode and for prefill chunksattend_batched/attend_batched_rows(cache/attend.rs)KVCache::attendper rowKVCache::trim,clone_handle,install_detached,CachePooldetach and adopt (cache.rs,cache/detach.rs)v_packedandv_norms;install_detachedrebuildsTurboQuantParams3from the packed widthRotatingKVCache::update_and_fetch(cache.rs)server/batch/scheduler/paged_layout.rs,cache/paged*.rs)KVCache::attendcache/batch_quant.rs)Int8andTurbo4Asymonlymodels/kv_snapshot.rs,models/recurrent_snapshot.rs)3isTurbo3Asymsrc/distributed/kv_cache_serde)KVCacheModeor packed-buffer handlingmla/latent_pair.rs,turbo/boundary.rs,turbo/allowlist.rs,execution/*,cli/turbo_args.rs,commands/generate.rsTurboLatentCodec::quantize(mla/turbo_latent.rs)turbo_latent.rswill call, and the comment on #3272 says whichever of the two lands second calls the other's index helper.boundary_indices_on_deviceis tested against the 4-bit codebook as well, so #3272 can call itquantize_into_packed(turbo/quant.rs, Turbo4)nearest_centroid_indices_with_boundariesThe four review lessons
tokens * head_dim * 7bools per call.cargo fmt --all -- --check. The Mac this was edited on has no cargo, so the first fmt run on Spark2 failed on line wrapping in three files;cargo fmt --allwas run there and the result brought back. The check then passed on the code tree and is run again on the commit's tree (see "Verification").Verification
Spark2: NVIDIA GB10, driver 580.178.04, CUDA 13.0.88, Linux 7.0.0-1019-nvidia aarch64, rustc 1.97.1 (the pinned toolchain),
--features cuda. Tests use--profile test-fastwithMLX_ENABLE_TF32=0 MLXCEL_SDPA_DETERMINISTIC=1; measurements use the release profile with both unset. Base944dbfc2ddd6ccab2b051dadc995e99d9d796c83, which is stillorigin/main. Commit15c341671c84bae99fca9833e0f21ac7209b9435, treee052dde274e16890aaaf09f5114f26903cdb0c59.On the commit's tree:
cargo build --locked --release --features cuda --bin mlxcel-bench-decode --bin mlxcel --bin mlxcel-server, and--example turbo3_readback_share_bench): all four binaries are byte-identical (cmp, same sha256) to the ones the branch rows were measured with, which were built from the work-in-progress tree.mlxcel-bench-decodeisbc8d7e9e...,mlxcel-serverfe8b16a8..., the example8955eaa2...; themainbuilds differ (3369d712...,8123fb94...,c86430db...).cargo fmt --all -- --checkcargo clippy --locked --workspace --all-targets --features cuda -- -D warningspython3 scripts/ci/check_used_by.py,bash scripts/ci/check_used_by_test.sh,python3 scripts/insert_apache_header.py --check, andscripts/ci/check_env_var_docs.py,check_kernel_dtype_keys.pyand its test,check_cross_repo_refs.py,check_benchmark_raw_logs.pyand its test,check_benchmark_csv_schema.py,check_kernel_port_dispatch.py,check_native_env_writes.py,check_binary_assets.py,check_windows_reserved_paths.py,check_crate_versions.py: all exit 0. The tree wase052dde2before and after.cargo test --locked -p mlxcel-core --profile test-fast --features cuda --lib <filter> -- --test-threads=1 --nocapture:cache::turbo197 passed,cache::turbo_tests79 passed,cache::(every cache test) 660 passed and 1 ignored. 27 of them are new.make verify-test-cudawith a private 0700TMPDIR: 17,433 passed, 5 failed, 517 ignored over 199test resultlines, 39 minutes, the treee052dde2before and after. The five failures are all in the root crate's lib target and none is in code this PR touches:models::raon1_mini::speculative::tests::{a_steered_verify_block_applies_the_alpha_exactly_as_decode_does, a_verify_block_equals_the_decode_chain_byte_for_byte, rollback_after_a_partial_accept_equals_a_fresh_decode_of_the_accepted_tokens, the_exactness_probe_passes_on_the_tiny_model}andmodels::raon_mhc::tests::compiled_site_equals_the_eager_site_bit_for_bit. The same five tests, run by name from a build of unmodified944dbfc2din the same profile (cargo test --locked --profile test-fast --features cuda --lib -- --test-threads=1 --exact <the five names>), fail there too: 0 passed, 5 failed, at the same five panic locations (raon1_mini_speculative_tests.rs:116,:116,:155,:204,raon_mhc_tests.rs:273) and with the same assertion messages. They are the Raon failures the earlier round-7 PRs reported (fix: Raon-1 mini correctness and validation follow-ups #3457 / fix(models): keep Raon DFlash2 verify blocks byte-exact on CUDA #3476 for the four speculative ones). The box is left unchecked because the gate's exit status is non-zero.Earlier, on the work-in-progress tree
067bcd09fa35f11e4073158470d2a052363d7fe2(the same code, tests and example; the commit adds only the record, its CSVs and three doc edits):cargo fmt --all -- --check, clippy with-D warningsand the 15scripts/cichecks all exited 0, and the four test filters passed (19 / 26 / 14 / 23).Tests
New in
cache/turbo/quant3.rs:device_codec_is_bit_identical_to_the_host_reference(the issue's parity criterion):TurboQuantParams3::new(d, seed)at D = 64, 128, 256, T = 1 and T = 4096, B = 1, H = 2, fp16 input with an all-zero token, a two-hot token whose rotated coordinates are exactly 0 for half the lanes (the codebook's middle boundary is exactly 0.0, which the test asserts), a one-hot token, a constant token and tokens at the smallest and largest fp16 scales. Packed bytes and norms equal the host reference's, anddequantize_v_turbo3equals the host reference dequantizer, compared as raw bytes with no tolerance.coordinates_on_every_boundary_take_the_lower_index: builds a codebook whose seven boundaries are seven of a token's own rotated coordinates, so each of them is hit bit for bit, and checks the lower index is taken on the device as on the host.device_codec_matches_host_reference_with_batch_and_heads(B up to 4, H up to 8),device_dequant_matches_host_reference_on_arbitrary_stored_bytes(pseudo-random packed bytes no quantizer produced, norms 0, subnormal, largest finite fp16, infinity),zero_tokens_flow_through_the_device_codec,device_codec_matches_host_reference_at_measured_scale(16384-token quantize, 32768-token dequantize at 8 heads and head_dim 128).codec_bodies_have_no_eval_and_no_host_readback(the source guard): the bodies of the two functions, cut fromquant3.rsbefore the first#[cfg(test)]line, and of the three device helpers contain noffi::eval,array_to_raw_bytesorfrom_bytes.New in
cache/turbo/pack3.rs:device_pack_matches_host_and_round_trips(head dims 8, 64, 80, 96, 128, 192, 256;pack_3bit_on_deviceequalspack_3bit_per_tokenbyte for byte andunpack(pack(idx)) == idx),device_unpack_matches_host_on_arbitrary_bytes,device_pack_extreme_patterns_match_host,device_pack_masks_out_of_range_indices_like_the_host,device_forms_accept_zero_tokens,device_forms_match_host_at_a_32k_window, and fourshould_panictests for a wrong head dim, a wrong packed width, a non-4-D input and a head dim that is not a multiple of 8.New in
cache/turbo/codebook.rs:device_boundary_indices_match_host_at_the_edges(3-bit and 4-bit codebooks at D = 64, 128, 256),device_boundary_indices_match_host_on_a_sweep,device_boundary_indices_keep_shape_and_accept_empty_input, and twoshould_panictests for an empty and an oversized boundary array.New in
cache/turbo_tests.rs:turbo3_asym_attend_matches_host_reference_over_prefill_and_decode(the issue's real-path criterion): aTurbo3AsymKVCachedriven throughKVCache::attendfor a 64-token prefill and 64 single-token decode steps, 4 query heads over 2 KV heads. At every step the storedv_packedandv_normsequal what the host quantizer produces for the same sequence, and the attention output equals attention over the host-dequantized window, as raw bytes.turbo3_asym_boundary_chunks_match_host_referenceand..._at_the_largest_head_dim: update sequences[0],[0, 1, 0, 5, 0],[1],[1, 1, 1],[256],[256, 1],[250, 12],[3, 253, 1],[255, 1, 1],[300, 300, 1]at head_dim 64, a subset at 256, and[250, 12, 1]at 128 with 8 heads.turbo3_asym_trim_then_append_matches_host_reference,turbo3_asym_restored_cache_keeps_matching_host_reference.Before and after: the device helpers do not exist on
main, so the new tests cannot be built there. On the first work-in-progress tree the two zero-token tests died with[hadamard_transform] Does not support empty arrays.(SIGABRT), which is what led to the early return. Seven mutations of the final code were each caught:greatertogreater_equalinboundary_indices_on_deviceunpack_3bit_on_devicepack_3bit_on_devicepack_3bit_on_devicedevice_pack_masks_out_of_range_indices_like_the_host)ffi::eval(&v_rot)put back intoquantize_v_turbo3array_to_raw_bytesput back intodequantize_v_turbo3Measurement
Full method, every table and the rows are in
docs/benchmark_results/turbo3-readback-share-gb10-2026-11-27.md. In short: the example gives per-layer stage times on both trees (the same source builds onmainplus that one file and on the branch),mlxcel-bench-decodegives the end-to-end step, and the server gives reply text and B=4.Decode and prefill, B=1, median of three runs (range of decode in brackets):
maindecode tok/smainprefill tok/sPer layer, median over the runs of the example's 20-iteration medians (three runs on the branch, four on
main):maindequantize_v_turbo3quantize_v_turbo3quantize_v_turbo3The one-token quantize is a few dozen small graph nodes now where it was a forced evaluation and a 1024-float host loop; the ranges overlap, and end to end the short contexts, where that call weighs most, are 2.3x (256 tokens) and 3.4x (1024) faster.
By the per-call estimate the two host segments were about 67% of a 32768-token prefill on
main(16 chunks of 2048 tokens: 448 quantize calls at 37.3 ms and 448 dequantize calls whose host segment grows to 51.2 ms); the measured prefill went from 43.2 s to 17.9 s.What is left is the device dequantize of the visible window. On the branch
turbo3-asymdecodes at 0.41x / 0.14x / 0.10x of fp16 at 4096 / 16384 / 32768 (0.10x / 0.04x / 0.02x onmain). The issue leaves a dequant-free Turbo3 attention route to a follow-up, and the record has the rows for that decision.Reply text: server at
--parallel 1, prompts built from the repository's docs plus a one-line summarization request, 64 tokens, greedy.turbo3-asym, two prompts per context (3974 / 16430 / 33970 and 4044 / 16372 / 31915 prompt tokens): all six replies are identical betweenmainand the branch, compared as strings (the record lists their sha256). A first attempt with word-list prompts was dropped because it returned the same reply for different prompts, which proves little.The null arm (a second
mainserver at 4096 and 16384) gives the same four replies, and the fp16 control (one prompt per context) is identical between the trees as well: nine pairs compared, nine identical. fp16 andturbo3-asymgive different replies for the 4096- and 32768-token prompts, so the comparison does react to what the cache holds.Four concurrent requests (
--parallel 4, 4096-token prompts, 96 tokens each): the server handled them one after another on both trees, with first tokens at 3.8 / 30.0 / 56.2 / 82.3 s onmainand 1.4 / 9.0 / 16.4 / 23.6 s on the branch (three runs each, all alike), and the fp16 control behaved the same way. No batched step ran, so there is no B=4 decode rate; the cell took 108 s onmainand 32 s on the branch end to end.nsys, per decode token at 4096 tokens (difference of a 96-token and a 32-token run, divided by 64):
cudaEventSynchronize54.4 onmain, 0.0 on the branch;cudaGraphLaunch148 and 147; graph kernel nodes 1266 and 2078.MLX peak memory of the
turbo3-asymruns went from 5.99 / 6.42 / 7.92 GB to 6.07 / 6.56 / 8.06 GB.Verification limits
unpack_3bit_on_devicenarrowsword >> shiftfrom UINT32 to UINT8 before masking and so relies on the narrowing cast keeping the low byte, which holds on CUDA (the parity tests pass);device_unpack_matches_host_on_arbitrary_byteswould fail on a backend where it does not.mainrows come from four runs. The first one, taken before any fix code existed, used a build of the example at an earlier revision of its source, which differs from the committed one in formatting, one parameter type (&PathBufto&Path) and the absence of the 2048-token quantize size. The other threemainruns and all branch runs use the committed source.KVCache::attendper row by reading the code, and that is all I can say about it.mlxcel generatewas not run;mlxcel-bench-decodeuses the same engine loop, and the server was run.mainround ran with no other GPU process. For the rest, a sampler logged other jobs' GPU processes every 3 s, and a run during which one started, stopped or used more CPU than 2 s or 2% of the run (3 s or 5% for the B=4 server runs, after a sleeping process of the other job turned out to idle at about 2% of a core) was set aside and repeated; five runs taken in the minutes before the sampler existed were set aside as well. The reply-text runs are the exception: two of them (both onmain) overlapped the other job and were kept, because only their text is used.MemAvailablefell to 22 GiB while the other job loaded a model. No process of another job was touched.