Skip to content

perf(kv): run the Turbo3Asym quantize and dequantize on device - #3497

Merged
inureyes merged 5 commits into
lablup:mainfrom
Jaeyeong-CHOI:perf/3274-turbo3-asym-device-codec
Nov 28, 2026
Merged

inureyes merged 5 commits into
lablup:mainfrom
Jaeyeong-CHOI:perf/3274-turbo3-asym-device-codec

Conversation

@Jaeyeong-CHOI

Copy link
Copy Markdown
Contributor

Summary

Closes #3274.

--kv-cache-mode turbo3-asym left the device in both halves of its codec. quantize_v_turbo3 evaluated the rotated coordinates and looked the centroids up on the CPU, and 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. 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:

context readback share of the decode step on main turbo3-asym decode tok/s, main branch fp16 decode tok/s, main branch
4096 76% 4.35 18.01 4.1x 44.09 43.82
16384 78% 1.25 4.75 3.8x 33.07 32.98
32768 82% 0.57 2.48 4.4x 24.49 24.44

The 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 on main and on the branch. An nsys trace at 4096 tokens shows 54.4 forced synchronizations per decode token on main and 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 to nearest_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) and pub(crate) fn unpack_3bit_on_device(packed_u8, head_dim), the device forms of pack_3bit_per_token and unpack_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_turbo3 calls boundary_indices_on_device and pack_3bit_on_device; dequantize_v_turbo3 calls unpack_3bit_on_device. Neither contains ffi::eval, array_to_raw_bytes or from_bytes any 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 a Turbo3Asym KVCache.
  • examples/turbo3_readback_share_bench.rs: the measurement example the issue asks for.
  • docs/benchmark_results/turbo3-readback-share-gb10-2026-11-27.md with CSV rows under docs/benchmark_results/data/turbo3-readback-share-gb10-2026-11-27/, a line in the benchmark index, a paragraph in docs/turbo-kv-cache.md and a CHANGELOG.md entry.

Where this differs from the issue text

  • Zero tokens return empty tensors instead of flowing through the graph. The issue lists "T=0 slices (shape [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 is noexcept, 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 with T = 0 died that way. Both functions now return the empty result directly when T == 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].
  • The unpack masks after narrowing. The issue writes (word >> shifts) & 7 and then a cast to UINT8. unpack_3bit_on_device casts word >> shifts to 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_device masks each index to 3 bits, as pack_3bit_indices does 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 every u8 input, which the test checks.
  • The boundary array is asserted to hold 1 to 255 values in boundary_indices_on_device, so the count fits the UINT8 result. The 3-bit codebook has 7 and the 4-bit one 15.
  • The host lookup's two asserts are kept in quantize_v_turbo3 (n_centroids > 0 and boundaries.len() == n_centroids - 1), because nearest_centroid_indices_with_boundaries made them on every call and that call is gone. The debug_assert on the centroid count stays a debug_assert.
  • The example reads the host segment as a reproduction, not from inside the codec. It uses only API that exists before and after this change, so one source builds on main (to get the "before" numbers) and on the branch. dequant_host_segment and quant_host_segment are built from the public host helpers. The full-call rows time dequantize_v_turbo3 and quantize_v_turbo3 as built, so they contain the host segment on main and do not on the branch.
  • Quantize rows at 2048 tokens were added to the runs (--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.
  • 28 Turbo3 layers, not 32. The issue's arithmetic assumes 32 Turbo layers for Llama 3.1 8B. The boundary policy keeps the first two and last two layers in fp16, so 28 layers hold Turbo3 V, and every per-step figure here uses 28.
  • Forced flushes per token. The issue expects "32 forced graph flushes per token". The nsys trace shows 54.4 cudaEventSynchronize calls per decode token on main (about two per Turbo3 layer, one per eval in the codec) and 0.0 on the branch. The number of cudaGraphLaunch calls 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. No cudaMemcpy is attributable to a decode token on either tree; on GB10's unified memory the readback is host time, not a device copy.
  • No batched (B>1) step was measured. With --parallel 4 and 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.
  • The branch rows of the record carry 944dbfc2-dirty as 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".
  • No Apple Silicon record. No Metal build was made; see "Verification limits".

Every other caller

grep -rnE "quantize_v_turbo3|dequantize_v_turbo3|unpack_3bit|pack_3bit|nearest_centroid_indices|TurboQuantParams3|Turbo3Asym" over src, examples and benches:

Site What it does with Turbo3Asym After this PR
KVCache::update_turbo3_asym (cache.rs) the only caller of quantize_v_turbo3 device path
KVCache::update_and_fetch, Turbo3Asym arm (cache.rs) the only caller of dequantize_v_turbo3 device path
KVCache::attend / attend_dense (cache/attend.rs) Turbo3Asym matches no Turbo4 decode predicate and falls through to update_and_fetch plus SDPA, for decode and for prefill chunks device path, through the two above
attend_batched / attend_batched_rows (cache/attend.rs) a batched step over dense caches calls KVCache::attend per row device path, per row. Known from the code only: in the server runs four concurrent requests were not batched
KVCache::trim, clone_handle, install_detached, CachePool detach and adopt (cache.rs, cache/detach.rs) slice or move v_packed and v_norms; install_detached rebuilds TurboQuantParams3 from the packed width unchanged on purpose: they never call the codec, and the stored bytes are the same. Tests added for trim-then-append and for a restored cache that keeps decoding
RotatingKVCache::update_and_fetch (cache.rs) falls back to fp16 for Turbo3Asym unchanged, no codec call
paged pool (server/batch/scheduler/paged_layout.rs, cache/paged*.rs) Turbo3Asym keeps the dense per-sequence path; the pool backs fp16 only unchanged, reaches the codec through KVCache::attend
batch KV quant (cache/batch_quant.rs) maps to Int8 and Turbo4Asym only no Turbo3 path
model-state snapshots (models/kv_snapshot.rs, models/recurrent_snapshot.rs) a populated quantized cache is refused with an error naming the mode; the mode tag 3 is Turbo3Asym unchanged. The stored layout did not change, so #3250 can carry these buffers as they are
distributed KV serde (src/distributed/kv_cache_serde) no KVCacheMode or packed-buffer handling not affected
mla/latent_pair.rs, turbo/boundary.rs, turbo/allowlist.rs, execution/*, cli/turbo_args.rs, commands/generate.rs mode resolution, advice, boundary policy, messages no codec call
TurboLatentCodec::quantize (mla/turbo_latent.rs) its own copy of the boundary-count rule for the 4-bit latent codec unchanged. It is #3272's to fold: that issue extracts the Turbo4 helper turbo_latent.rs will call, and the comment on #3272 says whichever of the two lands second calls the other's index helper. boundary_indices_on_device is tested against the 4-bit codebook as well, so #3272 can call it
quantize_into_packed (turbo/quant.rs, Turbo4) host nearest_centroid_indices_with_boundaries unchanged, #3272

The four review lessons

  1. Boundary inputs. Token counts 0, 1, 255, 256, 257 and chunks across the 256-token block edge; an update with zero tokens into an empty and into a filled cache; offset zero and a buffer that is exactly full; head dims 8, 64, 80, 96, 128, 192 and 256; index values 0, 7 and out-of-range 255; every packed byte value 0 to 255; rotated coordinates exactly on each of the seven boundaries and one float to either side; both zeros, both infinities, NaN, the finite extremes and subnormals; norms of 0, an fp16 subnormal, the largest finite fp16 and infinity; B and H above one; an empty and an oversized boundary array.
  2. Time on large inputs. The device forms are a fixed number of elementwise ops, so the cost is linear in tokens with no host loop. Tests run a 32768-token, 8-head, head_dim-128 window (33.5 M indices) through pack, unpack and the dequantizer, and a 16384-token chunk through the quantizer; the record has the times at 4096, 16384 and 32768. The transient of the index stage is tokens * head_dim * 7 bools per call.
  3. Other callers of the same helper and the same rule. The table above.
  4. 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 --all was 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-fast with MLX_ENABLE_TF32=0 MLXCEL_SDPA_DETERMINISTIC=1; measurements use the release profile with both unset. Base 944dbfc2ddd6ccab2b051dadc995e99d9d796c83, which is still origin/main. Commit 15c341671c84bae99fca9833e0f21ac7209b9435, tree e052dde274e16890aaaf09f5114f26903cdb0c59.

On the commit's tree:

  • Release rebuild of the commit (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-decode is bc8d7e9e..., mlxcel-server fe8b16a8..., the example 8955eaa2...; the main builds differ (3369d712..., 8123fb94..., c86430db...).
  • cargo fmt --all -- --check
  • cargo clippy --locked --workspace --all-targets --features cuda -- -D warnings
  • python3 scripts/ci/check_used_by.py, bash scripts/ci/check_used_by_test.sh, python3 scripts/insert_apache_header.py --check, and scripts/ci/check_env_var_docs.py, check_kernel_dtype_keys.py and its test, check_cross_repo_refs.py, check_benchmark_raw_logs.py and 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 was e052dde2 before and after.
  • New and related tests, cargo test --locked -p mlxcel-core --profile test-fast --features cuda --lib <filter> -- --test-threads=1 --nocapture: cache::turbo 197 passed, cache::turbo_tests 79 passed, cache:: (every cache test) 660 passed and 1 ignored. 27 of them are new.
  • make verify-test-cuda with a private 0700 TMPDIR: 17,433 passed, 5 failed, 517 ignored over 199 test result lines, 39 minutes, the tree e052dde2 before 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} and models::raon_mhc::tests::compiled_site_equals_the_eager_site_bit_for_bit. The same five tests, run by name from a build of unmodified 944dbfc2d in 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 warnings and the 15 scripts/ci checks 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, and dequantize_v_turbo3 equals 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 from quant3.rs before the first #[cfg(test)] line, and of the three device helpers contain no ffi::eval, array_to_raw_bytes or from_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_device equals pack_3bit_per_token byte for byte and unpack(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 four should_panic tests 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 two should_panic tests 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): a Turbo3Asym KVCache driven through KVCache::attend for a 64-token prefill and 64 single-token decode steps, 4 query heads over 2 KV heads. At every step the stored v_packed and v_norms equal 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_reference and ..._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:

mutation tests failing
greater to greater_equal in boundary_indices_on_device 6 (both boundary tests in codebook.rs, the every-boundary test and three parity tests in quant3.rs)
byte order swapped in unpack_3bit_on_device 16
second byte shifted by 9 instead of 8 in pack_3bit_on_device 16
unpack mask 3 instead of 7 16
3-bit mask removed from pack_3bit_on_device 1 (device_pack_masks_out_of_range_indices_like_the_host)
ffi::eval(&v_rot) put back into quantize_v_turbo3 1 (the source guard; every parity test passes)
array_to_raw_bytes put back into dequantize_v_turbo3 1 (the source guard)

Measurement

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 on main plus that one file and on the branch), mlxcel-bench-decode gives the end-to-end step, and the server gives reply text and B=4.

cargo run --release --features cuda --example turbo3_readback_share_bench -- \
  --model models/Meta-Llama-3.1-8B-Instruct-4bit --contexts 4096,16384,32768 --quant-tokens 1,2048,4096,16384
for mode in fp16 turbo3-asym; do
  ./target/release/mlxcel-bench-decode -m models/Meta-Llama-3.1-8B-Instruct-4bit -p x \
    --prompt-tokens <256|1024|4096|16384|32768> -n 128 --ignore-eos --kv-cache-mode "$mode"
done

Decode and prefill, B=1, median of three runs (range of decode in brackets):

context mode main decode tok/s branch decode tok/s main prefill tok/s branch prefill tok/s
256 fp16 48.24 [48.19 to 48.36] 48.30 [48.19 to 48.35] 3132.2 3137.7
256 turbo3-asym 15.87 [15.81 to 16.08] 37.02 [35.99 to 37.34] 918.7 2761.9
1024 fp16 47.05 [46.95 to 47.12] 47.04 [46.92 to 47.08] 3638.0 3629.0
1024 turbo3-asym 9.45 [9.36 to 9.51] 31.93 [31.92 to 31.94] 1272.7 3269.6
4096 fp16 44.09 [43.66 to 45.19] 43.82 [42.80 to 45.36] 3331.3 3308.2
4096 turbo3-asym 4.35 [4.33 to 4.36] 18.01 [17.83 to 18.63] 1178.8 2987.6
16384 fp16 33.07 [32.86 to 33.99] 32.98 [32.86 to 33.93] 2791.7 2769.9
16384 turbo3-asym 1.25 [1.24 to 1.25] 4.75 [4.72 to 4.76] 964.5 2352.5
32768 fp16 24.49 [24.39 to 24.68] 24.44 [24.39 to 24.53] 2226.1 2214.8
32768 turbo3-asym 0.57 [0.57 to 0.57] 2.48 [2.48 to 2.49] 758.4 1828.9

Per layer, median over the runs of the example's 20-iteration medians (three runs on the branch, four on main):

call size main branch
dequantize_v_turbo3 4096 / 16384 / 32768 visible tokens 7.9 / 27.4 / 60.9 ms 2.4 / 7.1 / 13.6 ms
host segment inside it same 6.3 / 22.2 / 51.2 ms none
quantize_v_turbo3 2048 / 4096 / 16384 new tokens 40.1 / 75.5 / 314.8 ms 2.3 / 4.3 / 19.8 ms
quantize_v_turbo3 1 new token 0.43 ms (0.21 to 0.97) 0.53 ms (0.16 to 0.72)
fp16 attention, one decode token 4096 / 16384 / 32768 0.5 / 1.0 / 1.1 ms 0.2 / 0.7 / 1.4 ms

The 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-asym decodes at 0.41x / 0.14x / 0.10x of fp16 at 4096 / 16384 / 32768 (0.10x / 0.04x / 0.02x on main). 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 between main and 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 main server 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 and turbo3-asym give 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 on main and 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 on main and 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): cudaEventSynchronize 54.4 on main, 0.0 on the branch; cudaGraphLaunch 148 and 147; graph kernel nodes 1266 and 2078.

MLX peak memory of the turbo3-asym runs went from 5.99 / 6.42 / 7.92 GB to 6.07 / 6.56 / 8.06 GB.

Verification limits

  • Metal and ROCm were not built or run. unpack_3bit_on_device narrows word >> shift from 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_bytes would fail on a backend where it does not.
  • No Apple Silicon record.
  • The example's main rows 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 (&PathBuf to &Path) and the absence of the 2048-token quantize size. The other three main runs and all branch runs use the committed source.
  • No batched decode step was measured (see "Where this differs"). The batched route reaches the codec through KVCache::attend per row by reading the code, and that is all I can say about it.
  • End to end only Llama 3.1 8B 4-bit (head_dim 128) was run. Head dims 64 and 256 are covered by the unit tests.
  • mlxcel generate was not run; mlxcel-bench-decode uses the same engine loop, and the server was run.
  • The reply-text check is nine prompts. It cannot show bit-identical logits; the bit-level claim rests on the tests (stored bytes and dequantized V identical to the host reference).
  • The A/B block shared the host with another job (a vLLM development session) that started GPU processes of its own from time to time. The first main round 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 on main) overlapped the other job and were kept, because only their text is used.
  • The watchdog stopped one of the runs that were set aside when host MemAvailable fell to 22 GiB while the other job loaded a model. No process of another job was touched.

`--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
@Jaeyeong-CHOI

Copy link
Copy Markdown
Contributor Author

Follow-up stacked on this branch: #3500 (Closes #3272) reuses the strict boundary-count lookup added here for the Turbo4 codec. It contains this commit plus one more and can be reviewed after this one.

@inureyes inureyes added status:review Under review type:performance Performance improvements priority:medium Medium 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
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.
@inureyes

Copy link
Copy Markdown
Member

Hardening review

Reviewed against #3274. The device codec is bit-identical to the host codec: the boundary count (greater(x[...,None], b) summed) follows the host's partition_point(b < v) rule including NaN, pack masks each index to 3 bits as the host does, and unpack narrows to u8 then masks with 7. The host codec stays as a #[cfg(test)] reference compared byte for byte across head dims 8 to 256 and T = 0/1/255/256/257. The host readback is gone from the hot path: KVCache::update_turbo3_asym and the update_and_fetch Turbo3Asym arm now only build lazy ops, with no eval, array_to_raw_bytes or from_bytes, and a source-guard test enforces that. The benchmark figures in the PR body recompute from the committed CSVs.

Pushed (8b2582c2)

Validation (GB10, under gpu-lock)

  • fmt clean; cargo clippy --locked --profile test-fast -p mlxcel-core --all-targets --features cuda -- -D warnings clean.
  • mlxcel_core lib cache:: (--test-threads=1, MLXCEL_SDPA_DETERMINISTIC=1): 673 passed, 0 failed, 1 ignored on the final tree.
  • Mutation: greater to greater_equal in boundary_indices_on_device fails 6 tests, matching the PR's table.
  • Real model: llama-3.1-8b-4bit, greedy, 64 tokens, release binaries from the same merged tree with and without the three codec files. Text is identical before and after for a ~3.5k-token prompt and a short prompt under both turbo3-asym and fp16 (turbo3-asym and fp16 differ from each other on the long prompt, so the comparison does react to the cache). turbo3-asym decode on a loaded box went from 2.77 to 12.38 tok/s (long) and 14.47 to 30.91 tok/s (short); fp16 unchanged.

Not run: workspace-wide clippy, make verify-test-cuda, Metal, ROCm and the server B>1 path. Note for #3500: it is stacked on this branch and will need a rebase after this merges.

@inureyes
inureyes merged commit 241a59a into lablup:main Nov 28, 2026
33 checks passed
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 28, 2026
inureyes pushed a commit that referenced this pull request Nov 28, 2026
…#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
@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:medium Medium priority status:done Completed type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf: Remove Turbo3Asym KV host readbacks in quantize and decode dequant

2 participants