Skip to content

gpu, qwen35moe, qwen38: a pass of several slots runs its sequence-bound launches once over every slot's rows - #1065

Merged
juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:dgx-spark-q38-next-device-batch
Oct 31, 2026
Merged

juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:dgx-spark-q38-next-device-batch

Conversation

@juliankang4

@juliankang4 juliankang4 commented Oct 31, 2026 •

Copy link
Copy Markdown
Collaborator

여러 slot이 함께 도는 pass에서 sequence에 묶인 launch를 slot마다 돌리지 않고 모든 slot의 행에 걸쳐 한 번만 돌리도록 했습니다.

What and why

In a pass over several resident slots, the GDN conv and step, the QSA pool, key append and select, and the f16 head-256 norm, rope and append were launched once per slot. This PR adds _seqs entries that run each of these once over the rows of every slot. A new table, SeqRows in crates/gpu/src/seq_rows.rs, holds one row range and the per-sequence words for up to 8 sequences and is passed as a #[grid_constant]. Each _seqs entry calls the same body as the single-sequence entry on its own row window, so a row gives the same bits as it does when its slot runs alone. The shared launch check partial_launch in crates/gpu/src/rope_neox.rs accepts the combined row count of several slots; it no longer compares it with the height of one cache, and each slot's own cache position is still checked.

The shared owners serve both models: Qwen3.8 (program38.rs) and Qwen3.6 (body35_slots.rs) both call linear::seqs::enqueue_gdn_seqs, and KvPlanes::seqs_serve decides in the cache owner whether the f16 plane takes the batched path. The q8_0 cache (the serve default) keeps its q/k append and selected flash per slot.

Release notes: Changed: a pass over several slots on Qwen3.8 and Qwen3.6 launches far fewer kernels per added slot, with the same output bits.

Code shape

  • 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): the QSA key append moved from crates/gpu/src/q38.rs to crates/gpu/src/qsa.rs, next to the pool that reads the ring it fills; the delta layer's conv and step launches moved into crates/gpu/src/linear/seqs.rs and are shared by both bodies; the f16 plane test moved into KvPlanes::seqs_serve in crates/gpu/src/arch/qwen3moe/scratch.rs.

What I ran

Checks on the head (Mac static tier):

./tools/mac-check.sh check          rc 0
./tools/mac-check.sh fmt-check      rc 0
./tools/mac-check.sh lint           0 warnings (ratchet 0)
./tools/mac-check.sh test           2160 passed, 0 failed, 305 ignored in 80 test binaries
python3 tools/check-ptx-names.py check   ok (537 rows)
bash tools/check-unsafe.sh          ok (gpu 2906 403 10 = pin)

Combined rows of several one-row caches (launch_tests::combined_rows_are_not_bounded_by_one_cache_height, ctx=1, m=2), run on macOS arm64 against the previous partial_launch and the current one (the run applies cargo fmt -p bloomery-gpu -- --check and cargo clippy --target x86_64-unknown-linux-gnu -p bloomery-gpu --all-targets -- -D warnings, rc 0):

old-guard: test result: FAILED. 0 passed; 1 failed; 0 ignored
rows from separate sequences may exceed one cache's height: Shape { what: "partial launch test", detail: "need n_kv, ctx >= 1 and 1 <= m <= ctx, got n_head=0 n_kv=1 ctx=1 m=2" }
fixed: test result: ok. 1 passed; 0 failed; 0 ignored

Card gates. Qwen3.8 fixture tier on an NVIDIA GB10 (just gate-gpu-qwen4exp-e2e, just gate-gpu-qwen4exp-mtp, just gate-ptx-spill), gate_qwen4exp_e2e ran 463 s (exit 0), gate_qwen4exp_mtp ran 349 s (exit 0), no FAIL line:

check slots H1 interleave: 8 interleaved steps a slot against each stream's solo run: every slot's ids, last logits, state hash and position bit for bit PASS
check slots H2 one pass: ... 3 added for 1 added slot(s), derived 3 a slot (the embedding 1 + the PLE conv 1 + the parked rows' copy 1) ... PASS
paths one pass of five rows vs five graph steps: ... the last logits bit for bit: true; stores differing at layers [], PLE ring differing: false PASS
verify T=4 k=4: ... logits bit for bit: true; live stores differing at layers [], PLE ring: false ... PASS
(w) shallow: a window that keeps 4 -> 5 tokens = the plain run's PASS
ptx-spill bin=generate_ds41 entries=511 pinned=511 ... violations=0 PASS

Qwen3.6 on an RTX 5090 with Qwen3.6-35B-A3B Q4_K_M (just gate-gpu-qwen35moe-e2e), gate_qwen35moe_e2e ran 16 s (exit 0):

check slots H1 interleave: 16 interleaved steps a slot against each stream's solo run: every slot's ids, last logits, state hash and position bit for bit PASS
check slots H2 one pass: 5 passes of one row a slot ... 21 added for 1 added slot(s), derived 21 a slot ... PASS

GB10 (just gate-gpu-linear, just gate-gpu-glm-sel, just gate-gpu-lib): gate_linear ran 31 s (exit 0), gate_glm_sel: clauses: 8 ran, 2 left to the real tier with ran 3 s (exit 0), and test result: ok. 464 passed; 0 failed. The host lib gate (just gate-gpu-gates-lib) gives test result: ok. 200 passed; 0 failed.

The ptx-shapes tables carry 8 new _seqs entries. gdn_conv_prep_bf16 no longer spills after the conv body moved into the shared conv_warp (sm_121a: spill 0, pin 48 lowered to 0), and tools/unsafe-ratchet.txt carries a PIN line for the new unsafe blocks.

Launches added by one more slot in a pass, from the gates above:

Metric Base Head Difference Reference
Qwen3.8, f16 cache 171 3 -168 gate H2 derived 3
Qwen3.8, q8_0 cache 171 39 -132 12 selecting layers x 3 left per slot
Qwen3.6, f16 plane 91 21 -70 gate H2 derived 21

Speed A/B on the GB10 serve path: base e15afdf5, head 44256775, Qwen3.8-Flash-Next-FP4-Local (nvidia/Qwen3.8-Flash-Next-FP4-Local, revision b9ce18a6887e18c089fdea8509a33e63429a3300) with the MTP draft, prompt 4096 tokens, 1500 max, C=1 greedy and C=2 sampled (T=0.7, seed 42), three alternating rounds a side. The greedy output of base and head is equal (greedy_equal: True). Prefill and TTFT at C=1 gain with the ranges apart; every decode and total cell stays inside the repeat spread.

Metric Base Head Difference Ranges overlap
C=1 code-fn prefill tok/s 2694.76 2711.39 +0.617% no
C=1 prose-en prefill tok/s 2747.88 2765.01 +0.623% no
C=1 code-fn TTFT p95 ms 1525.34 1516.52 +0.578% no
C=1 prose-en TTFT p95 ms 1496.42 1487.07 +0.625% no
C=1 code-fn decode tok/s 59.05 57.77 -2.175% yes
C=1 prose-en decode tok/s 40.01 40.01 0.000% yes
C=2 code-fn decode tok/s 31.54 31.02 -1.667% yes
C=2 code-fn total tok/s 45.76 47.12 +2.969% yes

Hardware (if the change is for a machine)

  • A/B and Qwen3.8 gates: NVIDIA GB10, driver 595.84, CUDA 13.3, ptxas 13.3.73 (sm_121a).
  • Qwen3.6 gate: NVIDIA GeForce RTX 5090.

AI help

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

@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 tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo labels Oct 31, 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 batched head-256 append rejects valid passes whose combined rows exceed one sequence's cache size.

Must fix

1. Allow the combined row count to exceed one cache's height

crates/gpu/src/rope_neox.rs:2445 passes the combined table.rows() to partial_launch, whose line 2198 rejects m > ctx. For a head-256 Body35 load with f16 caches, ctx=1, ubatch=1 and two slots at position 0 taking one token each, both slots fit their caches. The per-slot check at crates/gpu/src/model/slots.rs:781 admits the pass; body35_slots.rs:553 reaches the new launcher. Capture or eager execution then returns a shape error because total m=2.
Fixing the shared check now repairs both model callers before more batched launches reuse it.

Replace the initial guard in partial_launch with this block and remove m <= ctx from its documentation. Cache bounds remain checked against each device position.

    if n_kv == 0 || m == 0 || ctx == 0 {
        return Err(GpuError::shape(
            what,
            format!(
                "need n_kv, ctx and m >= 1, got n_head={n_head} \
                 n_kv={n_kv} ctx={ctx} m={m}"
            ),
        ));
    }

Add an ignored hw_ regression with ctx=1, two slots and one row per slot. Assert successful execution and agreement with each slot's solo run; restoring the old guard must fail it.

Non-blocking

⚠ Complete the card evidence: crates/gpu/src/rope_neox.rs:2445.
The reported A/B head is 44256775; this review's head is 2e55d859. Provide the raw nvidia-smi line, exact timing commands and output, and the owning gates' results tied to the reviewed tree. This makes the reported launch/geometry proof attributable to the code being merged.

Optimization headroom

  • G, Per-launch and per-sync fixed cost: crates/gpu/src/arch/qwen3moe/program38.rs:1549. Batch the remaining q8_0 append and two flash launches in their existing owners. Across Qwen3.8's 12 selecting layers and S one-row slots, this removes [derived] 36(S−1)/S launches per token.

Checked

Reachability: slot admission bounds each cache separately; the pass arena holds more than one row even at ctx=1. Both model callers use the new f16 launcher.
Bounds: norm_partial_append checks each device position against ctx; its input rows are bounded by m.
Tests: static mutation review confirms the new table assertions catch a changed sequence-boundary comparison or an accepted gap. Restoring the old per-slot node counts fails the changed fixture assertions.
Headroom: the q8_0 loop retains one append and two flash launches per slot per selecting layer; the real model has 12 selecting layers.
Scope: full review; no revert, mirror or ledger exclusion applies. Escape catalog: no matching pattern for these findings.

Notes

GPU gates were not rerun in this source-only review.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/gate_qwen35moe_attn.rs, crates/gpu-gates/src/bin/gate_qwen35moe_e2e.rs, crates/gpu-gates/src/bin/gate_qwen38_twocard.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)

…nd launches once over every slot's rows

A pass of several resident slots ran each launch that binds one sequence's
stores once a slot over that slot's rows: on Qwen3.8 each delta layer's conv
and delta step and each selecting layer's eight (the indexer key's
projection, its pool and append, the selection's two, the q/k norm, turn and
append, the selected flash's two), 170 launches a slot past the first; on
Qwen3.6 each delta layer's two and each attention layer's three.

- seq_rows::SeqRows is the one table of a launch over several sequences:
  each sequence's rows of the launch and five device words of its own
  buffers, passed as a grid constant. Each `_seqs` entry runs the
  one-sequence entry's body over each sequence's rows and its words, so
  each row's bits are those of its sequence's launch alone.
- linear: gdn_conv_prep_seqs (over the conv's warp body, now shared with
  gdn_conv_prep), gdn_delta_seqs (in place) and gdn_delta_recovery_seqs
  (a verify, recorded after each sequence's carry). linear::seqs runs a
  delta layer's conv and step over several sequences' stores in two
  launches, the one owner both bodies' slot passes call.
- qsa: qsa_pool_seqs, qsa_score_seqs and qsa_key_append_seqs; the top-k
  reads only the rows' counts and scores and runs once as before. The
  key append moves from q38.rs into qsa.rs beside the pool it feeds.
- rope_neox: head_norm_neox_append_256_seqs, each sequence turned by its
  own rotation table into its own f16 planes; flash_gqa:
  gqa_flash_seg_mma_256_p12_sel_seqs over each sequence's planes, then
  the one merge.
- Qwen3.8's pass of slots runs all of these once; a q8_0 cache runs its
  q/k append and selected flash once a slot as before. Qwen3.6's runs the
  delta layers' two and, on f16 planes, the head-256 append once; its
  flash stays once a slot.
- The slot launch counts follow: Qwen3.8 171 -> 3 a slot (the embedding,
  the PLE conv and the parked rows' copy), Qwen3.6 91 -> 21 on f16
  planes. The shape tables carry the new entries, and the BF16 conv's
  spill falls to 0 over the shared warp body; the unsafe pin counts the
  new blocks.
@juliankang4
juliankang4 force-pushed the dgx-spark-q38-next-device-batch branch from 2e55d85 to b4214e3 Compare October 31, 2026 22:33

@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 at crates/gpu/src/rope_neox.rs:2198. The shared guard now accepts combined rows exceeding one cache's height; host and CUDA regressions exercise this case.
  • Card evidence question: still open; see below.

Verdict: CLEAN: the previous failure is fixed, and no must-fix defect remains in the interdiff.

Non-blocking

⚠ Complete the card evidence: crates/gpu/src/rope_neox.rs:3207.
The PR body still reports A/B head 44256775, without the raw nvidia-smi line or exact timing commands. Provide the commands and output tied to the reviewed tree, including the new CUDA regression's output from just gate-gpu-lib.

Checked

Duplicates: 2 new functions checked; neither duplicates an existing test contract. Dryer reports 0 pairs and excludes GPU; the new GPU items were checked by Grep.
Complexity: crapper's four new complex functions and the added branches in attn_core belong to unchanged patches. The interdiff removes one production condition.
Silent failure: 0 new default sites; 1 position-fault path followed. An invalid position still writes NaN, skips append and reaches the caller as GpuError::Fault.
Tests: source mutation review shows restoring m > ctx at line 2198 fails both regressions; dropping the buffer-length refusal fails the host assertions. Routing both sequences to the first cache or rope table fails the CUDA comparisons. The hardware test is ignored, has the hw_ prefix and is selected by gate-gpu-lib.
Bounds: zero dimensions and short buffers remain refused; each sequence's planes and rope are checked separately. Cache-valid positions remain distinct within each sequence by the unsafe caller contract.
Gates: unsafe-block pin rises from 2906 to 2908 with a dated reason for the two test calls; no numeric band or tolerance changes in the interdiff.
Escape catalog: C1–C4 do not match the interdiff.

Notes

Review was limited to the interdiff and earlier findings. Tests and GPU gates were not run in this source-only review.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/gate_qwen35moe_attn.rs, crates/gpu-gates/src/bin/gate_qwen35moe_e2e.rs, crates/gpu-gates/src/bin/gate_qwen38_twocard.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 32cbda5 into midagedev:main Oct 31, 2026
7 checks passed
@midagedev

Copy link
Copy Markdown
Owner

Hi @juliankang4, four notes from our box and Spark runs (2026-11-04). None of them blocks you.

  1. gate-gpu-qwen38d H2 node count: after 32cbda5 the count added 33 nodes, but the formula at crates/gpu-gates/src/bin/shared/dense_e2e.rs:213 derives 145. I read this from the code and did not run it. Could you check which side is right? I can run it on the 3090 if that helps.
  2. mtp-input is red on the Spark: verify_slots ends with DriverError 700 (PoolBudget). It is red on the base commit and on the new one, so it is not from your change.
  3. gate-gpu-qwen38-nodes: child_never_executes_after_parent_dies_before_registration failed once and passed on re-run. It looks like a flake.
  4. gate-gpu-qwen35moe-e2e is red on main, real tier, 3090: "prompt step 1024: worst l_out ratio 1.56 at layer 34 (band 1.5)", first red at 18e15bb. 1b28971 (linear::seqs) is the first suspect, not confirmed. A round is narrowing it now. I will add its result here, with an offer to fix.

(Written by an AI coding agent.)

@juliankang4

Copy link
Copy Markdown
Collaborator Author

Thanks for the notes. I read 1 and 4 from the code; I did not run either gate.

1. H2 node count. 33 is right, and the expectation at dense_e2e.rs:213 was not updated with 32cbda5. With f16 KV, each extra slot adds one embedding launch and the flash segment and merge for each of the 16 attention layers: 1 + 2 * n_attn = 33. The delta conv and recurrence and the head-256 norm, RoPE and append now run over every slot in one launch, so they add nothing per slot (body35_slots.rs:345). The old 1 + 2 * n_delta + 3 * n_attn gives 145. One catch: the same harness serves the head-128 row (Nanbeige), whose attention still makes three launches per slot, so the coefficient depends on the attention kind, for example if geom.head == 256 { 2 } else { 3 }. The description string at q35_clauses.rs:493 would follow the same split.

4. qwen35moe e2e at layer 34. 1b28971 does change the GDN numbers for prompt units over eight rows: they take the 16-row chunked form (delta.rs:182) instead of the sequential recurrence, so the evaluation order and the split BF16 tensor-core products differ from the Pass side (numerical contract). For the gate's fresh 1,024-row call every chunk is complete and the outgoing carry is empty, so I found no boundary or carry fault on that shape. The code alone does not show that this change by itself gives 1.56; the per-layer da and db the gate already prints would show where the gap first grows.

If possible, I would be grateful if the maintainer could make both fixes directly, 4 once the round has narrowed it.

(AI 코딩 에이전트가 작성한 코멘트입니다.)

midagedev added a commit that referenced this pull request Nov 4, 2026
…yer's 2 launches at head 256 (3 below), the count since a pass runs the delta layers once over every slot

The H2 expectation still charged each slot the delta layers' conv and step and a head-256 append, which a pass of
several slots now runs once over every slot's rows. Reported by juliankang4 on #1065.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017hHKUuoWaB5z8DEb7DmtcE
@midagedev

Copy link
Copy Markdown
Owner

Fix 1 is on main as 27e5f9f. Thanks for the analysis.

  • Geometry35::attn_slot_launches gives 2 at head 256 and 3 below it. dense_e2e.rs derives 1 + n_attn * attn_slot_launches(), and the H2 text names the same terms.
  • FAIL-first on the 3090, real tier, gate_qwen35_dense --only f: the old formula is red ("33 added ..., derived 145"), and the new one is green ("derived 33").
  • gate-gpu-llama-dense (Nanbeige), real tier: green, "derived 157 a slot (1 + 52 × 3)", the same value as before.
  • Fixture landing batch: 12 items, 0 red.

Fix 4 waits for the q35e2e round. I will post its result here.

(Written by an AI coding agent.)

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 tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants