Skip to content

gpu: Qwen3.8 slots share a prompt prefix's KV pages and copy them on write - #1012

Merged
juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:dgx-spark-q38-opt-prefix-share
Oct 30, 2026
Merged

juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:dgx-spark-q38-opt-prefix-share

Conversation

@juliankang4

Copy link
Copy Markdown
Collaborator

Qwen3.8에서 여러 슬롯이 같은 프롬프트 앞부분의 KV 페이지를 공유하고, 쓸 때 복사하게 합니다.

What and why

Under --parallel N on the Qwen3.8 seat, a request whose prompt starts with a prefix that another resident slot holds now takes that slot's state on the card. Before, it prefilled the prefix again unless a prompt cache entry existed, and no entry exists while the other request is still running. The recurrent state, the per-layer embedding ring and the raw key rings load from the source slot's checkpoint at the share point, so a shared slot continues from the same bits as a cut back to that point. A share is chosen only when it keeps more than the slot's own state and every cache entry; if the engine refuses it, the slot resets and the request prefills as before.

Release notes: Changed: with --parallel, a Qwen3.8 request that repeats a running request's prompt prefix reuses that prefix's KV pages instead of prefilling it again.

Code shape

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

  • No second copy. Logic two models (or two call sites) share has one common owner; I lifted it there instead of
    copying it (AGENTS.md "Common code first", docs/rust-quality.md R14). Where I found an existing copy, I
    named it below.
  • Model code holds only architecture facts. A model's own files carry only what its architecture forces
    (tensor shapes, the attention kind, the quant). A common owner gained no per-model branch, flag or trait method.
  • Dead code is gone. Nothing I made unused is left behind (functions, flags, gate clauses, docs).
  • No silent failure. Undefined input is a named error or panic, never a defined-looking output.
  • Comments state what is true now. No dates, issue numbers or how a bug was found (tools/check-comments.sh).
  • No relaxed gate. No band, tolerance or lint moved to make a check pass; a re-pin carries PIN(YYYY-MM-DD):
    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. The duplicate scan reports only per-command wrappers in crates/gpu-gates/src/bind.rs and per-room accessors in scratch38.rs, each with its own command or figure.

How it is built:

  • crates/gpu/src/room.rs: Room::share(from, n) maps the source room's memory for every page that holds only whole rows below n. The page where the prefix ends gets its own memory with the bytes copied (one new unsafe block, so the gpu pin in tools/unsafe-ratchet.txt moves from 2838 to 2839 with a PIN line). Room::own_from(pos) gives every shared page that a write from pos reaches its own memory with the same bytes. The new pages are made first and filled through a scratch virtual range, then remapped, so a failure moves no page and the copy takes no device memory beyond the new pages. A lent flag skips the page scan on rooms that never shared.
  • scratch38.rs, mtp38.rs, body38.rs: the K/V planes, the pooled keys and the MTP draft store share pages. Every writer calls own_from after fit. Slot38::share_point grants nothing when the source sequence holds an image, because a share does not carry the M-RoPE table.
  • crates/serve: Engine::share_keepable and Engine::share_prefix (defaults 0 and Unsupported), a cache share note, and a choice in genloop that takes the share only when it keeps more than the slot's own state and every cache entry.
  • crates/gpu-gates: the qwen38 seat implements both calls, the kv room record gains shared_bytes, and gate_qwen4exp_e2e gains a slots share clause.

What I ran

Card for every run below: GB10, driver 595.84, CUDA 13.3 (nvcc V13.3.73), sm_121a.

Gates on head a0429839d, base fb43427d1, with the Qwen3.8 fixture qwen38-fixture-00001-of-00001.gguf and its draft mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf:

./tools/box.sh 'bash tools/gate.sh --gpu --oxide -p bloomery-gpu --release --lib -- --include-ignored room::tests::hw_'
BLOOMERY_TIER=fixture BLOOMERY_MODEL=qwen4exp ./tools/box.sh "export BLOOMERY_GATE_V41_LOAD=1 && cargo oxide build --arch sm_121a -- -p bloomery-gpu-gates --features gpu --release --bin gate_qwen4exp_e2e --bin gate_qwen4exp_mtp && BLOOMERY_GATE_CARD=any bash tools/gpu-gate.sh gate_qwen4exp_e2e && BLOOMERY_GATE_CARD=any bash tools/gpu-gate.sh gate_qwen4exp_mtp"
test room::tests::hw_a_room_backs_the_rows_a_fit_reaches ... ok
test room::tests::hw_rooms_share_the_rows_below_a_point ... ok
slots share: slot 1 took slot 0's first 8192 of 8195 asked (share point 8192), standing at 8192, 33554432 B mapped and 4194304 B copied (derived 33554432 and 4194304, whole pages true), 33554432 B shared; slot 0 cut back to 4096 and prompted other ids, leaving 16777216 B shared (derived 16777216); after the rest slot 1's stores differ from slot 0's before the cut at [] (PLE ring false), its steps [139594, 25332, 242950] slot 0's [139594, 25332, 242950] true; a share onto the slot it comes from refused by name true, one below every point true PASS
gpu-gate.sh: gate_qwen4exp_e2e ran 436 s (exit 0)
gpu-gate.sh: gate_qwen4exp_mtp ran 327 s (exit 0)

The new slots share clause fails without the change. With Body38::stage not calling own_from, the same run gives:

leaving 33554432 B shared (derived 16777216); after the rest slot 1's stores differ from slot 0's before the cut at [1, 2, 3] (PLE ring true), its steps [139594, 25332, 242950] slot 0's [139594, 25332, 242950] false; a share onto the slot it comes from refused by name true, one below every point true FAIL
gpu-gate.sh: gate_qwen4exp_e2e ran 443 s (exit 1)

With Room::own_from made a no-op, the room test fails on the pages the write reached:

test room::tests::hw_rooms_share_the_rows_below_a_point ... FAILED
assertion `left == right` failed: pages 1 and 5 of each buffer given their own memory
  left: (12582912, 12582912)
 right: (4194304, 4194304)

MTP draft store gate on head ef6391584, base b9584f6a6, the Qwen3.8 fixture and its draft above, GB10, driver 595.84, CUDA 13.3 (nvcc V13.3.73):

BLOOMERY_BOX_LOCAL=1 BLOOMERY_TIER=fixture BLOOMERY_MODEL=qwen4exp ./tools/box.sh 'export BLOOMERY_GATE_V41_LOAD=1 && bash tools/gate.sh --gpu --oxide -p bloomery-gpu-gates --release --features gpu --bin gate_qwen4exp_mtp -- --ignored hw_mtp_shared_store --nocapture'
draft share eager: 8192 positions mapped, source rewritten, other slot K/V bit-identical PASS
draft share graph: 8192 positions mapped, source rewritten, other slot K/V bit-identical PASS
draft share store: 8192 positions mapped, source rewritten, other slot K/V bit-identical PASS
draft share slots: 8192 positions mapped, source rewritten, other slot K/V bit-identical PASS
draft share resume: 8192 positions mapped, source rewritten, other slot K/V bit-identical PASS
draft share prefix: 8192 positions mapped, source rewritten, other slot K/V bit-identical PASS
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 65.01s
HEAD MTP shared-store gate PASS

The gate fails when a copy-on-write call is left out. Without it in Mtp38::run_walk, in stage_store, or without reset returning the shared pages before a put-back, the same run stops with:

assertion `left == right` failed: eager: only the draft tail detached
assertion `left == right` failed: slots: only the draft tail detached
assertion `left == right` failed: resume: reset must release shared pages before the put-back

The real bloomery-serve with the MTP draft (--ctx-size 12288 --parallel 1, model nvidia__Qwen3.8-Flash-Next-FP4-Local b9ce18a6) restores a cached prefix and continues bit-identically over three requests of 8 tokens:

REAL bloomery-serve MTP: 3 requests, 8 tokens each, restored continuation bit-identical PASS
bloomery-serve-qwen38: cache load positions=138 common=127 kept=127 slot_kept=0 bytes=298503424 ms=11.001 resumed=127 waited_ms=0.000

Real bloomery-serve (qwen38 seat, release feature set from tools/release/build.sh) on head b26420251, model nvidia__Qwen3.8-Flash-Next-FP4-Local (b9ce18a6). Request A is a 10,000-id prompt with 768 greedy ids, streamed. Request B is A's first 9,000 ids plus 600 other ids with 128 greedy ids, sent when A's first chunk arrives. The server runs with --ctx-size 32768 --parallel 2; the reference runs A then B with --ctx-size 16384 --parallel 1. Both run with the MTP draft and with BLOOMERY_DRAFT=off. The ids of A and B from the two runs are compared:

TOKENS mtp A equal=True n=768 first_diff=None; B equal=True n=128 first_diff=None
TOKENS off A equal=True n=768 first_diff=None; B equal=True n=128 first_diff=None
bloomery-serve-qwen38: cache share from=0 common=9000 kept=8192 slot_kept=0 mapped_bytes=109051904 copied_bytes=79691776 ms=14.727
kv room slot=1 positions=9599 mapped_bytes=297795584 shared_bytes=109051904 layout_bytes=244352000

Request B with the MTP draft, on base 2a20a6e47 and on head b26420251, same requests, one run each:

Metric Base Head Difference
B prompt tokens evaluated 9600 1408 -8192
B prompt_ms 4642.04 1003.2 -3638.8
Shared device pages while both requests are resident 0 B 109051904 B 104 MiB

The head also spends 14.7 ms on the share itself, shown in the cache share line above.

AI help

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

…write

A request whose prompt starts with a prefix another resident slot holds
takes that slot's state at its nearest point below the common prefix
instead of prefilling it again. The selecting layers' K/V planes, pooled
keys and the MTP draft store map the other slot's pages that hold only
whole rows of the prefix, and copy the page where it ends. The recurrent
stores, the PLE ring and the raw key rings are loaded from the other
slot's checkpoint. Every writer gives a shared page it reaches memory of
its own first, and a reset gives shared pages back.
@github-actions github-actions Bot added gpu The card engine: crates/gpu*, crates/app needs-gpu Changes code a card must check, and carries no gate run on a card serve The HTTP server: crates/serve tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo labels Oct 30, 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: CLEAN: No merge-blocking defect survived the state, ownership, and error-path checks.

Non-blocking

⚠ Measure decode while pages remain shared: crates/gpu/src/room.rs:414 and crates/gpu-gates/src/bin/shared/serve_seats/qwen38.rs:2998.
own_from and shared each scan every page while sharing persists. For a plain selected-slot step that detaches no pages, M backed pages in its still-shared rooms incur at least 16M B of reference-counter loads on 64-bit hosts [derived], plus metadata and lends probes; this is not a DRAM-traffic estimate.
The timing table measures B's prefill. Add a same-card base/head decode A/B while both requests share pages, so this per-token term is bounded before wider parallel use.

Checked

Duplicates: 64 new items checked; no duplicate owner found. Both dryer functions read: different builder options, shared shape only.
Complexity: new slots_share (51) and hw_mtp_shared_store (48) combine setup, rewrites, and assertions; those are their logical stage boundaries. reuse 27→32 adds a share-selection branch; run 55→57 and spawn 41→43 add dispatch; run_walk 27→28 adds a COW check.
Silent failure: 6 fallback sites followed. Missing share points grant no reuse; refusals reset; failed thread queries surface on the next engine command. Saturated requests still select an existing source checkpoint.
Tests, static mutation check: room gate protects Room::own_from line 415 (no-op fails shared-byte counts); slots-share protects Body38::stage line 3956 (dropped COW fails store/logit equality); MTP gate protects run_walk line 1690, stage_store line 1851, and Room::settle line 314 (dropped detach/release fails isolation/reset assertions); serve test protects Slot::reuse line 802 (disabled share selection fails cache counts). GPU FAIL-first output is supplied for COW/reset mutants.
Gates: no accuracy band or tolerance moved; the added unsafe block has a dated ratchet PIN and reason.
Escape catalog: C1–C4 do not match the changed code.
Adversarial checks: rewinds, pending verifies, image prefixes, boundary pages, and three-slot sharing retain guards or independent ownership.

Notes

Review and mutation checks were static; no build or gate was run locally. The PR states GB10 and driver 595.84 and supplies gate output, but omits the required nvidia-smi output line; GPU evidence is incomplete.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/gate_qwen4exp_e2e.rs, crates/gpu-gates/src/bin/gate_qwen4exp_mtp.rs, crates/gpu-gates/src/bin/shared/serve_seats/ds41.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 5c9f5d7 into midagedev:main Oct 30, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gpu The card engine: crates/gpu*, crates/app needs-gpu Changes code a card must check, and carries no gate run on a card serve The HTTP server: crates/serve 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