Skip to content

qwen38: a q8_0 KV cache, set by --cache-type-k and the default on a checkpoint folder - #956

Merged
juliankang4 merged 2 commits into
midagedev:mainfrom
juliankang4:dgx-spark-q38-fp4l-q8-kv
Oct 29, 2026
Merged

juliankang4 merged 2 commits into
midagedev:mainfrom
juliankang4:dgx-spark-q38-fp4l-q8-kv

Conversation

@juliankang4

@juliankang4 juliankang4 commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

Qwen3.8 FP4-Local의 KV 캐시를 q8_0으로 저장해 DGX Spark에서 KV 메모리를 줄이고, --cache-type-k로 고를 수 있게 합니다.

What and why

The Qwen3.8 seat kept its KV cache in f16 only. This PR adds a q8_0 cache for it, picked by --cache-type-k f16|q8_0 (or BLOOMERY_QWEN3_KV). A checkpoint folder such as the FP4-Local folder defaults to q8_0, and a GGUF file stays on f16. --cache-type-v is refused by name.

On the FP4-Local folder the attention store shrinks from 967,921,280 B to 773,279,360 B at 16,896 positions. Greedy output on a 5-token and a 12,123-token prompt is the same text as f16.

What changes, one item for each commit:

  • gpu: the selected-key flashes (decode gqa_flash_seg_mma_256_p12_sel_q8, prompt gqa_prefill_flash_256_p12_sel_q8 and _p12_sel_gated_q8) and the MTP draft's dense flashes (gqa_flash_seg_mma_256_p4_q8, gqa_prefill_flash_256_p4_gated_q8) read a q8_0 cache. The existing kernels take the key source as a type (F16Kv or Q8Kv), so the f16 and q8_0 paths share one walk. The host side takes the cache as one CachePlanes value, with one length rule and one alignment check. A q8_0 cache on a scalar segment is refused by name.
  • qwen38: one owner, KvPlanes, holds the planes, the format, the zeroed state, the saved spans and the gated prompt flash. The plan bytes, the MTP store and the checkpoint spans take the format. The seat reads --cache-type-k, then BLOOMERY_QWEN3_KV, then the folder default, and setup prints cache=. The lever's unset value is now "no value" so the folder default can apply. generate_qwen3moe no longer refuses BLOOMERY_QWEN3_KV=q8_0 on Qwen3.8. gate_qwen4exp_e2e gains a (kv) clause. docs/serving.md and docs/contrib/dgx-spark.md state the default.
  • tools: the five new _q8 entries are pinned in the PTX shape tables with spill 0 and local 0, measured on the card. The gpu unsafe pin goes from 2812 to 2823 with a PIN(2026-10-29) line naming the 11 new blocks, which stage the q8_0 key rows the way the existing q8_0 prefill stage does.

Release notes: Added: Qwen3.8 can keep its KV cache in q8_0 with --cache-type-k q8_0, and does so by default on a checkpoint folder such as FP4-Local.

Code shape

The review reads these first. A box left unticked needs one line of why.

  • No second copy. The f16 and q8_0 selected flashes share one key walk (KeyWalk::row) and one macro body over KvSrc; the cache format has one owner (KvPlanes) and one length rule (q8_plane_lens).
  • Model code holds only architecture facts. The shared owners gained no per-model branch, flag or trait method; the format reaches them as a value.
  • Dead code is gone. stage_row is replaced by KeyWalk::row; nothing is left behind.
  • No silent failure. A q8_0 cache on a scalar segment, a short codes plane, a misaligned window and --cache-type-v are named errors.
  • Comments state what is true now. No dates, issue numbers or how a bug was found.
  • No relaxed gate. No band or tolerance moved. The one re-pin is the gpu unsafe count, and it carries PIN(2026-10-29): and its reason.
  • cargo fmt and cargo clippy are clean on what I touched; the lint count did not go up.

Duplication found or removed (path:line), or "none": none.

What I ran

On a DGX Spark (GB10), just gate-gpu-qwen35moe-attn builds and runs gate_qwen35moe_attn. The new q8_0 lines, bit for bit against the f16 entries on the dequantized cache:

decode q8 pass=mma keys=5 ctx=45: = the f16 mma twin on the synthesized f16 cache bit for bit true rerun=true sentinel_same=true PASS
decode q8 pass=mma keys=4097 ctx=4137: = the f16 mma twin on the synthesized f16 cache bit for bit true rerun=true sentinel_same=true PASS
decode flash 256 q8 PASS
shape kernel=gqa_flash_seg_mma_256_p12_sel_q8 local_depot=false ld_local=0 st_local=0 PASS
shape kernel=gqa_prefill_flash_256_p12_sel_gated_q8 local_depot=false ld_local=0 st_local=0 PASS
shape kernel=gqa_prefill_flash_256_p4_gated_q8 local_depot=false ld_local=0 st_local=0 PASS
qsa q8 pass counts=[2051] lengths=[2051]: f16 twin bit for bit true sentinel rows changing no bit true finite true PASS
qsa q8 listed prefill counts=[8193] lengths=[2049]: f16 twin bit for bit true sentinel rows changing no bit true finite true PASS
qsa q8 pass short codes plane: flash_gqa::enqueue_256_p12_sel: kq.len() 1049536 < 1049600 PASS
gate_qwen35moe_attn: clauses: 26 ran, 0 left to the real tier
gpu-gate.sh: gate_qwen35moe_attn ran 19 s (exit 0)

gate_qwen4exp_e2e on the Qwen3.8 fixture, the (kv) clause:

kv q8_0: store bytes 36408640 (want 36408640, derived; f16's 42306880) PASS
kv q8_0 PASS

The q8_0 prompt flash against its f16 twin:

cargo test -p bloomery-gpu --release --lib -- --include-ignored flash_gqa
test flash_gqa_prefill::tests::hw_q8_gated_entries_are_the_f16_entries_on_the_dequantized_cache ... ok
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 448 filtered out; finished in 20.17s

The _q8 entries against the pinned PTX shape tables, on the GB10 with ptxas 13.3.73, for each of sm_121a, sm_121 and sm_86, with $a set to the arch. The first line below is sm_121a (sm_121 passes with the same counts), the second is sm_86:

BLOOMERY_ARCH=$a PTX_SPILL_CACHE=off bash tools/ptx-spill-check.sh tools/ref/ptx-shapes.tsv tools/ref/ptx-shapes/ generate_ds41:_q8
ptx-spill bin=generate_ds41 entries=31 pinned=31 nonzero=gqa_prefill_flash_g7_q8(spill=160,jit_local=80) violations=0 PASS
ptx-spill bin=generate_ds41 entries=31 pinned=31 nonzero=gqa_prefill_flash_g7_q8(spill=0,jit_local=80) violations=0 PASS

The seat's unit tests:

cargo test -p bloomery-gpu-gates --release --features deepseek41,gemma-embedding2,hf --bin bloomery-serve-qwen38
test tests::the_cache_format_is_the_flags_then_the_levers_then_the_folders ... ok
test result: ok. 28 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

The real binary, bloomery-serve -m <Qwen3.8-Flash-Next-FP4-Local folder> with the default and with --cache-type-k f16, on a 5-token and a 12,123-token prompt, the long one sent twice (the first load line is the default, the second --cache-type-k f16):

default cache=q8_0
f16 cache=f16
load arch=qwen4exp resident_bytes=79996986024 ctx=16896 slots=1 slot_ctx=16896 ctx_max=262144 ctx_train=262144 verified=3001 layers=48 mode=graph store_bytes=773279360 prefill=auto ubatch=4096 place=a card_layers=48 in 18.2 s (runtime value)
load arch=qwen4exp resident_bytes=80207848104 ctx=16896 slots=1 slot_ctx=16896 ctx_max=262144 ctx_train=262144 verified=3001 layers=48 mode=graph store_bytes=967921280 prefill=auto ubatch=4096 place=a card_layers=48 in 19.8 s (runtime value)
short texts equal across arms and repeats: True
long texts equal across arms and repeats: True
q8 long repeat (cached prefix) equals first: True cached 12122
SERVE-Q8 PASS

Hardware (if the change is for a machine)

  • Card: NVIDIA GB10 (DGX Spark), compute capability 12.1
  • Driver: 595.84
  • CUDA: 13.3.1
  • ptxas: 13.3.73
  • Model: nvidia/Qwen3.8-Flash-Next-FP4-Local

AI help

AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.

@github-actions github-actions Bot added dgx-spark The DGX Spark (aarch64, GB10) port documentation Improvements or additions to documentation gpu The card engine: crates/gpu*, crates/app host Host crates: qdot, threads, engram, engram-lab, runtime, sampler, levers, decision, vision, refset model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja needs-gpu Changes code a card must check, and carries no gate run on a card tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo labels Oct 29, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: MUST_FIX: the q8_0 paths read correct (layout, NaN rows, bytes, shared-memory sizes), but the PR adds a CLI flag to a gate that nothing uses.

Must fix

1. --kv-only is an element nothing needs

gate_qwen4exp_e2e.rs:5796: the gate had no argument parsing. The new flag has no caller in the tree (no just recipe, no script). It copies the gate's tail (tally, exit) and returns before tier::expect_fixture_oracle, so a partial run prints a tally that looks like the gate's. Removing it now is cheaper than keeping a second exit path.
Fix: delete the doc sentence at line 256 and the block at lines 5796 to 5804 (let kv_only … the closing }). The (kv) clause stays in the full run.

Non-blocking

⚠ The default flips to q8_0 on a checkpoint folder with no timed A/B: qwen38.rs:1405. "Performance first" makes the faster path the default. docs/research/adaptive-picks.md §3.3 item 6 says the one unknown is whether the q8_0 flash reads at the f16 flash's byte rate, and asks for tools/ref/depth-decode.sh with BLOOMERY_DEPTHS="1024 4096 16384" and arms f16|q8_0. The PR shows bytes and equal text, not tok/s. Please add that A/B on the GB10 with the conditions (tok/s @ n, depth, card).

⚠ No PTX proof that the f16 entries are unchanged: flash_gqa.rs:2374 (KeyWalk::row replaces stage_row, seg_mma_p and listed_seg_tiles! read through S::word) and flash_gqa_prefill.rs:1965 (listed_rows! gains key < KEY_TILE on the f16 path). The class is "add": ptx-scan must be base plus exactly the new entries. The PR runs ptx-spill-check filtered to _q8, which cannot show it. Paste just ptx-compare BASE BIN.

⚠ No repo test holds the q8_0 host-state paths: saved.rs:127 (Plane::U32, halves), scratch.rs:1392 (KvPlanes::spans) and seq38_bytes(.., Q8) against PlanInputs::seq_state_bytes. Every gate call passes KvQ8::F16 (gate_qwen38_serve.rs:3707), and (kv) never saves a state. Mutant: Plane::halves returns 1 for U32. A prefix restored from the prompt cache then lands at the wrong stride and no assertion turns red; only the PR's own serve script (not in the tree) would. Direction: run the existing seq save/load clause of gate_qwen4exp_e2e on the (kv) model, and compare the two byte owners at Q8.

⚠ Also minor: the bool to KvQ8 mapping is written three times (qwen38.rs:1244, body38.rs:1908, mtp38.rs:369); one KvQ8::of(bool) would own it. Mtp38::store_host (mtp38.rs:517) refuses q8_0 but KvPlanes::f16's doc (scratch.rs:458) names only the qwen3.5 taps.

Checked

  • Duplicates: about 25 new items checked. The in_q8 pick repeats an existing idiom (qwen3moe_place.rs:374). The one dryer pair (with_kv_q8 ~ with_indexer_top_k) is a setter shape.
  • Complexity: the flagged functions grow by one match arm per format (harmless). #[kernel] bodies read for correctness only.
  • Silent failure: 7 sites followed. All end in a named error or the fault word (listed rows at or past ctx give a fault plus NaN in both formats).
  • Tests: the zero-scale mutant and the precedence flip turn tests red. The Spans mutant above does not.
  • Gates: no band moved. The gpu unsafe pin carries PIN(2026-10-29).
  • Escape catalog: no match (no shell changed).

Notes

  • No FAIL-first output for clause 21, (kv) or hw_q8_gated_… (plant the zero-scale mutant, show red).
  • No nvidia-smi line or commit hashes in the PR body, so the GPU evidence list is incomplete.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/bloomery_serve_qwen38.rs, crates/gpu-gates/src/bin/gate_qwen35moe_attn.rs, crates/gpu-gates/src/bin/gate_qwen38_media.rs … and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

//! prompt flashes over the cache's q8 tiles, below and past the selection's onset, then the
//! selected decode flash) judged against ik's by (t)'s rule and bands: the cache's
//! quantization must not move the argmax past a named tie nor a layer output past
//! [`FREE_BAND`]. `--kv-only` runs this clause alone.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

--kv-only has no caller; drop the flag (see the code block below).

Suggested change
//! [`FREE_BAND`]. `--kv-only` runs this clause alone.
//! [`FREE_BAND`].

Comment on lines +5796 to +5804
let kv_only = std::env::args().any(|a| a == "--kv-only");
if kv_only {
let (man, _) = input_manifest(BATCH)?;
let (_, toks, _) = man.step()?;
tier::sc(KV_CLAUSE)?;
ok &= kv_q8(toks, &mut 0)?;
println!("{}", tier::tally_line());
return if ok { Ok(()) } else { Err(checks_failed()) };
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The gate had no arguments and nothing passes this one; the early return also skips expect_fixture_oracle.

Suggested change
let kv_only = std::env::args().any(|a| a == "--kv-only");
if kv_only {
let (man, _) = input_manifest(BATCH)?;
let (_, toks, _) = man.step()?;
tier::sc(KV_CLAUSE)?;
ok &= kv_q8(toks, &mut 0)?;
println!("{}", tier::tally_line());
return if ok { Ok(()) } else { Err(checks_failed()) };
}

@juliankang4
juliankang4 force-pushed the dgx-spark-q38-fp4l-q8-kv branch from 9a46f82 to 801b2ee Compare October 29, 2026 13:19

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the last review:
Must-fix 1 fixed: --kv-only and its separate exit path are removed.

Verdict: CLEAN: no must-fix finding remains; four advisory items remain open.

Non-blocking

⚠ 1 still open: no timed A/B for the folder default. qwen38.rs:1633 defaults checkpoint folders to q8_0.
Each selecting layer's K/V payload changes from 2048 to 1088 B per attended position [derived: two KV heads, 256 values per head, both K and V], with dequantization added. Add a GB10 f16/q8_0 depth A/B at 1024/4096/16384, with tok/s, generation length and commands, to establish the default's cost.

⚠ 2 still open: no comparison proving existing f16 PTX is unchanged. flash_gqa_prefill.rs:1766 shares the revised flash body.
Add just ptx-compare BASE generate_ds41 output against the PR base. The filtered _q8 spill run does not compare the existing f16 entries.

⚠ 3 still open: q8 checkpoint regression coverage. gate_qwen4exp_e2e.rs:938 omits save/load on its q8 model; the prefix-restore clause runs on f16.
Extend prefix-restore checks to q8, including saved-byte counts and code-plane strides. Mutant: Plane::halves returns 1 for U32; the current restore tests use u16 stores and do not detect this wrong stride.

⚠ 4 partly fixed: the bool mapping now uses KvQ8::of. scratch.rs:458 describes only qwen3.5 host taps.
Include the MTP host reader's f16-only contract: mtp38.rs:537 also calls this accessor.

Checked

Confirmed the four cited paths, folder-format precedence, U32 span units and the separate f16 prefix-restore call. The findings are distinct, remain advisory and match no exclusion or escape-catalog pattern. No tests executed.

Notes

The PR body lacks the nvidia-smi line, both tested commit hashes and FAIL-first output for the new GPU clauses.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/bloomery_serve_qwen38.rs, crates/gpu-gates/src/bin/gate_qwen35moe_attn.rs, crates/gpu-gates/src/bin/gate_qwen38_media.rs … and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@juliankang4

Copy link
Copy Markdown
Collaborator Author

The review is done and the contribution check passed, so I'm merging this.

@juliankang4
juliankang4 merged commit 8640549 into midagedev:main Oct 29, 2026
7 checks passed
midagedev added a commit that referenced this pull request Oct 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dgx-spark The DGX Spark (aarch64, GB10) port documentation Improvements or additions to documentation gpu The card engine: crates/gpu*, crates/app host Host crates: qdot, threads, engram, engram-lab, runtime, sampler, levers, decision, vision, refset model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja needs-gpu Changes code a card must check, and carries no gate run on a card tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant