Skip to content

gpu: Qwen3.8's selecting stores and draft store back only the rows a sequence reaches - #993

Merged
juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:dgx-spark-q38-opt-kv-request-len
Oct 30, 2026
Merged

juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:dgx-spark-q38-opt-kv-request-len

Conversation

@juliankang4

Copy link
Copy Markdown
Collaborator

Qwen3.8의 슬롯별 KV 저장소가 컨텍스트 전체 대신 시퀀스가 닿은 페이지만 카드 메모리로 받치게 했습니다.

What and why

Qwen3.8 keeps per-slot stores indexed by position: each selecting layer's K/V planes (f16 or q8_0 codes and scales), its pooled indexer keys, and the MTP draft's store. Today every store is allocated at the slot's full context, so a default slot (1 slot, ctx 262144, fp4l with MTP) holds 7985954816 B of card memory even when the request is a few thousand tokens.

This PR keeps the whole-context layout and every address, and backs with card memory only the pages that the rows a sequence reached lie on. A new Room in crates/gpu/src/room.rs reserves the address range once at load and maps unbacked pages to one shared spare page per device (the driver checks the whole extent of a strided device copy, so a sequence save or put-back needs every page mapped). fit(positions) backs new pages before a call is staged, and settle() at a sequence's end maps the pages past the ended sequence's reach back to the spare. Kernels, layouts, addresses and graph captures are unchanged. The plan still counts every store at the slot's full context, so every growth fits inside the planned memory.

A second commit fixes two defects that landed with the q8_0 cache: bloomery-serve-qwen38's lever test scan now reads the closure's accessor levers.and_then(|l| l.qwen3_kv_set()), and the checked-in tools/bloomery/schema/bloomery-serve-qwen38.jsonl gets the setup record's cache key.

The serve seat prints a new kv room slot= positions= mapped_bytes= layout_bytes= record (kind kv_room, in BLOOMERY_SERVE_QWEN38 and the checked-in schema) when a slot's backed bytes change.

Release notes: Changed: Qwen3.8 backs a slot's KV cache with card memory only for the positions a sequence reaches, not the whole context.

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": crates/gpu/src/arch/qwen3moe/scratch38.rs:126 (Store38::qsa) beside crates/gpu/src/arch/qwen3moe/scratch.rs:410 (KvPlanes::new). They differ: Store38::qsa builds the Qwen3.8 selecting store in rooms, while KvPlanes::new builds the plain planes the Qwen3.5 and qwen3moe bodies keep, which this PR does not change.

What I ran

Memory, from the kv room lines the real bloomery-serve prints (head). Base allocates the whole layout, so its backed bytes equal layout_bytes. Default slot (1 slot, ctx 262144, fp4l with MTP), one 4096-id prompt with 128 greedy ids:

Metric Base Head
backed bytes at positions=4095 7985954816 159383552
backed bytes at positions=4099 7985954816 268435456

With --ctx-size 12288 --parallel 1, one request run to the end of the context: mapped_bytes=159383552, 268435456, then 402653184 at positions=8195. After the next request's reset to a reach of 2063 the slot is back to mapped_bytes=159383552 at positions=2999. At full context the head holds up to one page a buffer more than the plan counts (402653184 backed against 374341632 layout).

Token ids on the real binary, base against head, same prompts: TOKENS fp4l equal=True n=128, TOKENS long equal=True n=8193 (ctx 12288 to the end), TOKENS resume equal=True n=[64, 64, 256] (a state saved at 3064 and a prefix of 2063 put back from the prompt cache), TOKENS nvfp4 equal=True n=128.

Throughput on a DGX Spark, base against head with the q8_0 cache at ctx 16896 (fp4l without MTP, fp4l with MTP, nvfp4 without MTP), greedy ids equal (greedy_equal: True). This is a memory change and no speed claim is made:

Metric Base Head Difference Ranges overlap
fp4l-off code-fn decode tok/s 31.6098 31.5151 -0.299% True
fp4l-mtp code-fn decode tok/s 59.059 59.0293 -0.050% True
nvfp4-off code-fn decode tok/s 22.8345 22.8056 -0.126% True

Reproduction of the failure the spare page fixes:

bash tools/gate.sh --gpu --oxide -p bloomery-gpu --release --lib -- --include-ignored hw_a_room_backs_the_rows_a_fit_reaches
  • Before the spare page: test result: FAILED. 0 passed; 1 failed, with a 2-D write of each head's first row over the unbacked pages between: Driver { op: Some("cuMemcpy2DAsync_v2 (host to device)"), source: DriverError(1, "invalid argument") }. The real server hit the same error at a sequence save.
  • After: test result: ok. 1 passed; 0 failed.

Gates:

bash tools/gate.sh --oxide -p bloomery-gpu-gates --release --features deepseek41,gemma-embedding2,hf --lib -- serve_client:: record::
bash tools/gate.sh --oxide -p bloomery-gpu-gates --release --features deepseek41,gemma-embedding2,hf --bin bloomery-serve-qwen38
  • serve_client:: and record::: test result: ok. 31 passed; 0 failed.
  • bloomery-serve-qwen38 bin: test tests::the_levers_list_is_the_levers_the_seat_reads ... ok, test result: ok. 27 passed; 0 failed.

On the fixture tier, gate_qwen4exp_e2e ran 380 s (exit 0) with kv q8_0: store bytes 36408640 (want 36408640, derived; f16's 42306880) PASS and kv q8_0 PASS, gate_qwen4exp_mtp ran 327 s (exit 0), and serve_client:: reported test result: ok. 6 passed; 0 failed.

Hardware (if the change is for a machine)

Runs above: DGX Spark (NVIDIA GB10, 595.84, CUDA 13.3) and an RTX 5090 machine (card name GeForce_RTX_5090 in the gate log) for the room test and the bin and record gates. Pages are backed at the card's allocation granularity.

AI help

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

…sequence reaches

Each slot's K/V planes (f16 or q8_0 codes and scales), pooled indexer keys
and MTP draft store keep their whole-context layout and addresses, reserved
at load, and give a page of the device's allocation granularity its own
zeroed memory the first time a staged call, a draft walk or a state put back
reaches its rows. A reset gives back the memory of the pages past the rows
the ended sequence reached. A page with no memory of its own maps one spare
page per device, so a 2-D copy whose extent crosses unbacked pages between a
store's planes (a sequence save or put-back) still finds its whole range
mapped. The plan still counts every store at the slot's context; a buffer
that is not a whole number of pages maps its last page whole. Captures and
launches over the stores are unchanged. The expert stream's ring, which
sizes itself from the card's free bytes, leaves free what the planned slots'
stores may still back. The server prints a kv room record when a slot's
backed bytes move.
@github-actions github-actions Bot added gpu The card engine: crates/gpu*, crates/app 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 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 must-fix defect survived the bounds, backing, restore, and reset checks.

Non-blocking

⚠ Complete GPU evidence: crates/gpu/src/room.rs:177 changes backing on staged calls. The PR gives run summaries without both commit hashes, the model path, and complete reproduction commands and output. Attach those with the actual nvidia-smi line so the reported gates and A/B can be reproduced before merge.

Optimization headroom

  • G. Per-launch and per-sync fixed cost: crates/gpu/src/room.rs:218 drains once per room returning pages during request reset. Move the common drain before page releases. For R ≥ 1 releasing rooms and T > 0 request tokens, this removes R−1 syncs per reset, or (R−1)/T per token [derived].

Checked

Duplicates: 61 new items checked; no duplicate owner found. Dryer reported zero pairs in model; GPU and GPU-gates were searched manually.
Complexity: room_padding (new, 24) already separates rounding, planes, and totals into closures. paths and long_point add reset clauses; props_engine, place38, serve_seats::run, and open_qwen38 add admission work; load_state, stores_host, reset, and run_walk add backing lifecycle work.
Silent failure: nine clamp/default/recovery sites followed. Row counts are guarded by callers; full-buffer fits deliberately saturate; absent backing selects the spare; driver failures propagate.
Tests (mutation analysis): dropping backing at crates/gpu/src/room.rs:200 fails the room test's mapped-byte assertion. Omitting the spare at crates/model/src/arch/qwen35moe/place.rs:404 fails both admission tests. Dropping the fit at crates/gpu/src/arch/qwen3moe/body38.rs:3842 fails the e2e fresh-short assertion. Dropping draft settlement at crates/gpu/src/arch/qwen3moe/body38.rs:5602 fails the MTP short-request equality.
Bounds: an in-memory simulation checked 5,616 growth/reset transitions across small page, row, head, context, and pooling shapes; requested and cached-covered rows remained backed. Restore copies wait for engine writes; page release drains outstanding copies.
Gates: no tolerance relaxed or case removed. The unsafe-count increase has a dated PIN and enumerates the six new blocks. The room test has FAIL-first output in the PR.
Escape catalog: no C1–C4 pattern matched.

Notes

GPU gates were not rerun during this review. Dryer excluded GPU and GPU-gates because of scope/budget; crapper ran.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/gate_qwen38_serve.rs, crates/gpu-gates/src/bin/gate_qwen4exp_e2e.rs, crates/gpu-gates/src/bin/gate_qwen4exp_mtp.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 879cd26 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 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant