Skip to content

gpu: zero recurrent stores on the device at reset - #643

Merged
juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:dgx-spark-recur-clear-device
Oct 22, 2026
Merged

juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:dgx-spark-recur-clear-device

Conversation

@juliankang4

@juliankang4 juliankang4 commented Oct 22, 2026 •

Copy link
Copy Markdown
Collaborator

새 요청마다 host의 0 버퍼 469,204,992 B를 card로 복사하던 recurrent 상태 초기화를, card에서 직접 0으로 채우도록 바꿉니다. 초기화 시간이 GB10에서 16.807 ms에서 2.416 ms로 줄었습니다.

Part of #565.

What and why

RecStore::clear resets a layer's recurrent state and ring buffers at the start of a request. It did that by copying a zero vector from host memory to both buffers, and every caller built that vector for each request. On the Qwen3.8 fixture's 36 stores, that is 469,204,992 bytes copied to the card per request, from a 12,582,912-byte host vector.

This PR fills both buffers with zero on the card instead, with the existing DeviceBuffer::zero_async on the engine stream. clear no longer takes a host source. Body38, Body35 and the two Nemotron bodies no longer build the vector or compute its length, and the Raon state reset calls RecStore::clear instead of its own copy of the same fill. Stamps are left as they were, and the change adds no kernel and no unsafe.

On a GB10, clearing the 36 stores took 16.807 ms on main and 2.416 ms with this change (mean of two alternating runs per arm). That times the clear alone, from the caller's host zero vector to the final synchronize. It is not TTFT or decode tok/s. The small stamp and control copies at reset are unchanged.

Release notes: Under the hood: a request's recurrent state is zeroed on the GPU instead of copied from a host buffer, which cuts the reset's clear time on a DGX Spark.

Code shape

  • No second copy. Raon's separate device zero copy is gone; its reset calls RecStore::clear, the one owner.
  • Model code holds only architecture facts. The model bodies lose their zero vectors and length calculations and gain no branch.
  • Dead code is gone. The host zero vectors and the host source parameter of clear are removed.
  • No silent failure. CUDA errors from the fill propagate with ?.
  • Comments state what is true now.
  • No relaxed gate. No band, tolerance or pin moves.
  • cargo fmt is clean on what I touched. Clippy was not run on this head.

Duplication found or removed (path:line): the device zero copy in crates/gpu/src/arch/raon1/state.rs is replaced by a call to RecStore::clear.

What I ran

The PR head is 033f058bc on main be69eb0ce. just contrib-check --tier t0 (107 units, none red) and the full just gate-gpu-qwen4exp-e2e on a GB10 ran on this head. The clear timing, the unit tests and the bit comparison against main ran on an earlier revision of this branch. The clear path (crates/gpu/src/recur.rs, crates/gpu/src/arch/raon1/state.rs and crates/gpu/src/arch/qwen3moe/body38.rs) is identical between that revision and this head, so those results carry over. The only change since is in the gate's own source, which now compares the reset through one shared path.

GPU evidence

Card and driver, from nvidia-smi on the GB10 (CUDA 13.3.1 dev container):

| NVIDIA-SMI 595.84                 Driver Version: 595.84         CUDA Version: 13.3     |
|   0  NVIDIA GB10                    On  |   0000000F:01:00.0 Off |                  N/A |

The whole card gate, on the Qwen3.8 fixture tier:

BLOOMERY_BOX_LOCAL=1 BLOOMERY_ARCH=sm_121 BLOOMERY_TIER=fixture \
BLOOMERY_REF_MODEL=<qwen38 fixture gguf> \
just gate-gpu-qwen4exp-e2e

The card-leg and whole-card rows both run the reset clause through the shared paths comparison. It reads the stores back after reset, requires every word to be positive zero, then replays the same five steps and a prompt followed by graph decode:

reset: 2 recurrent stores and PLE ring zero PASS
clauses: 26 ran, 8 left to the real tier
gpu-gate.sh: gate_qwen4exp_e2e ran 370 s (exit 0)
PASS full owning gate

The 8 clauses left to the real tier did not run.

The same gate with the two zero_async calls in RecStore::clear skipped (card model, same paths clause) fails:

reset: 1 recurrent stores and PLE ring zero FAIL
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 16.24s

The test process exits with code 101, and the tracked sources are clean afterwards.

Against main, the five tokens and all 1,241,600 logit words match this change bit for bit.

The new unit tests, recur::tests::hw_clear_keeps_stamps_and_addresses and arch::raon1::state::tests::hw_clear_store_resets_values_and_stamps, check that every word is positive zero, the buffer addresses stay and the stamps are kept. They run from the built test executable with hw_clear --ignored --nocapture --test-threads=1:

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 374 filtered out; finished in 0.68s

A clear that leaves part of the ring untouched, and a Raon reset that skips RecStore::clear, fail these two tests on the positive-zero assertion (test result: FAILED. 0 passed; 2 failed).

Clear time A/B

Main and head alternated in one sitting, in the order M1, H1, M2, H2, on one GB10 with the clock cap lifted for the sitting and restored after. Each run allocates the 36 stores (state of 3,145,728 f32 and ring of 112,640 f32 each), fills them with 1, then times the clear and a stream synchronize. The main arm also times building the caller's host zero vector. The probe test is not part of the diff. Afterwards each run checks that every word is positive zero.

Arm Commit Mean clear time (ms)
main aa3d1690 16.807
head 02f604a1 2.416

Delta (head minus main): clear time -14.391 ms (-85.6%).

Run Arm Clear time (ms)
M1 main 17.142546
H1 head 2.414119
M2 main 16.471375
H2 head 2.417655

Main here is aa3d1690 (upstream main plus the reset gate); its clear path is the same as on be69eb0ce. Head here is 02f604a1, whose clear path is the same as on 033f058bc. Two runs per arm show the clear's cost, not end-to-end speed. To reproduce, add this probe to crates/gpu/src/recur.rs on each side (on main, the clear call takes &zeros, and zeros is vec![0.0f32; 3_145_728] built before the loop), build the lib tests with cargo oxide test --arch sm_121 -- -p bloomery-gpu --release --lib --no-run, and run each executable with --exact recur::rec_clear_probe::request_clear --nocapture:

#[cfg(test)]
mod rec_clear_probe {
    use super::*;
    #[test]
    fn request_clear() -> Result<(), GpuError> {
        let (_ctx, stream) = crate::capsync::fresh_stream(0)?;
        let mut stores: Vec<_> = (0..36)
            .map(|_| RecStore::new(&stream, [3_145_728, 112_640], 4))
            .collect::<Result<_, _>>()?;
        let dirty = vec![1.0f32; 3_145_728];
        for r in &mut stores {
            r.state.copy_from_host(&stream, &dirty)?;
            r.ring.copy_from_host(&stream, &dirty[..112_640])?;
        }
        stream.synchronize()?;
        let start = std::time::Instant::now();
        for r in &mut stores {
            r.clear(&stream)?;
        }
        stream.synchronize()?;
        println!("request_clear bytes={} wall_ms={:.6}",
            36usize * (3_145_728 + 112_640) * 4,
            start.elapsed().as_secs_f64() * 1000.0);
        Ok(())
    }
}

Hardware

DGX Spark (NVIDIA GB10, driver 595.84, CUDA 13.3.1 container), built with cargo oxide ... --arch sm_121. The model gate used a generated Qwen3.8 GGUF fixture (unsloth/Qwen3.8-Flash-Next-GGUF, UD-Q4_K_XL, seed 1). No full NVFP4 checkpoint was run.

What I ran into

None of this blocks the PR. Body38::reset still does a small stamp and control copy for each store, and RecStore::restamp builds its host stamp each time. I did not measure what moving those onto the card would save.

AI help

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

@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 labels Oct 22, 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 new card reset stage repeats contracts already checked by the card row gate.

Must fix

1. Run the card path comparisons through one owner

gate_qwen4exp_e2e.rs:5596 calls paths, which checks eager = graph = pass. gate_qwen4exp_e2e.rs:3747 repeats those checks on the same card model and tokens, starting fresh each time. This is a kind B duplicate under R14 and the one-test-per-contract rule.
Consolidating now removes two owners of the same assertions and saves two token walks and one pass per card-leg run.

Delete reset_replay, including its comment, and the two new lines in card_leg that announce and invoke it. Replace card_rows with this definition; paths retains the new reset and prompt/decode checks:

fn card_rows(m: &mut Qwen38Model, toks: &[u32], plan: &PlanFacts) -> Result<bool, GateError> {
    let (mut ok, _) = paths(m, toks)?;
    let want_memops = shape().memops_card(hostless(plan));
    let want = (
        shape().nodes_verify_card(plan.card_layers) - (memops() - want_memops),
        want_memops,
    );
    ok &= verify_structure::<2>(m, want)?;
    ok &= verify_structure::<3>(m, want)?;
    ok &= verify_structure::<4>(m, want)?;
    let (rows, next) = verify_rows(toks)?;
    let refs = (1..=LANES)
        .map(|k| ref_run(m, Prefix::Steps(&toks[..PREFIX]), &[&rows[..k]], next))
        .collect::<Result<Vec<_>, _>>()?;
    let served = n_layer() - hostless(plan);
    ok &= verify_case::<2>(m, toks, rows, next, 2, &refs, served)?;
    ok &= verify_case::<3>(m, toks, rows, next, 3, &refs, served)?;
    ok &= verify_case::<4>(m, toks, rows, next, 4, &refs, served)?;
    Ok(ok)
}

Non-blocking

⚠ Verify the final gate integration: gate_qwen4exp_e2e.rs:3925 integrates the reset check into the card leg. The reported hw_reset_replays_the_same_bits test is absent from this head. Run just gate-gpu-qwen4exp-e2e and just gate-gpu-lib on the final head and attach commands and output to validate the integration before merge.

Checked

Duplicates: 3 new functions searched; the card gate duplicate is above. Dryer reported 0 pairs; both new unit tests protect distinct clear/stamp contracts.
Complexity: paths rose 5 → 14 through reset-buffer validation and the prompt/decode clause; its orchestration remains bounded.
Silent failure: 2 fill results followed through callers; both propagate errors with ?. No new error-suppression sites.
Tests: static mutation check: omit either fill at recur.rs:84–85, clear/restamp at raon1/state.rs:63–64, or the model clear at body38.rs:4592; the corresponding zero/stamp assertion or gate verdict fails. The RecStore test also checks stable addresses and unchanged stamps; the Raon test checks fresh stamps.
Gates: no tolerance or threshold moved; reset checks were added, with FAIL-first results reported in the body.
Escape catalog: C1–C4 do not match.

Notes

Dryer did not scan crates/gpu-gates; its relevant owners were searched manually.
Source review only; no CUDA build or gate was run here. The supplied output does not establish a completed gate run after the reset clause moved into the card leg.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/gate_qwen4exp_e2e.rs, crates/gpu/src/arch/nemotron_h/body.rs, crates/gpu/src/arch/nemotron_h_moe/body.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
juliankang4 force-pushed the dgx-spark-recur-clear-device branch from 159f930 to 28e36b3 Compare October 22, 2026 04:31

@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:

  • Fixed: card_rows:3745 reuses paths; the separate reset wrapper and repeated comparisons are removed.
  • Answered by author: the body reports completed GB10 owning-gate and clear/stamp unit runs, with the tested revisions identified.

Verdict: CLEAN: The consolidation retains the reset and path assertions and preserves their failure propagation.

Checked

Duplicates: 0 new items in the interdiff; the earlier duplicate is removed. Dryer reported 0 pairs.
Complexity: crapper flags paths, 5 → 14, for reset validation and prompt/decode orchestration; that function is unchanged in this interdiff.
Silent failure: 0 new suppression sites. The shared verdict reaches the gate's final error; both device-fill errors propagate.
Tests: no new tests in the interdiff. Static mutation check: dropping either fill at recur.rs:84–85 fails the positive-zero assertions; skipping restamping at raon1/state.rs:64 fails the fresh-stamp assertion. The body reports red fill mutants.
Gates: no tolerance or pin moved. The removed wrapper delegates to the retained assertions; each verify reference resets through Prefix::feed.
Escape catalog: C1–C4 do not match.

Notes

Dryer did not scan crates/gpu-gates; the changed gate owners were searched manually.
Source review only; no CUDA build or gate was run here. The supplied gate covers the fixture tier; eight real-tier clauses remain unrun.

Card check: gpu-evidence. This pull request changes crates/gpu-gates/src/bin/gate_qwen4exp_e2e.rs, crates/gpu/src/arch/nemotron_h/body.rs, crates/gpu/src/arch/nemotron_h_moe/body.rs … and carries a gate run on the author's card, which counts as verified.

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

@github-actions github-actions Bot added gpu-evidence Verified on the author's card: the pull request carries the gate run and its output and removed needs-gpu Changes code a card must check, and carries no gate run on a card labels Oct 22, 2026
@juliankang4
juliankang4 force-pushed the dgx-spark-recur-clear-device branch from 28e36b3 to 02cb058 Compare October 22, 2026 05:12

@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: carried from 28e36b33, not re-reviewed.

The approval of 28e36b33 stands for 02cb058b. This pull request's 1 commit are the same patches in the same order: git patch-id --verbatim (the changed lines, the lines around them and whitespace) and the subject are equal for every commit. That review ran under the reviewer instructions, tools and slag ledger that review this head, and it approved.

The base moved and also changed crates/gpu/src/arch/qwen3moe/body38.rs, which this pull request changes too. Each of its hunks still applies with the same context lines.

A carry covers each patch's own lines and the lines around them. What the base changed elsewhere is covered by CI on this head and by the landing gates.

Card check: gpu-evidence. This pull request changes crates/gpu-gates/src/bin/gate_qwen4exp_e2e.rs, crates/gpu/src/arch/nemotron_h/body.rs, crates/gpu/src/arch/nemotron_h_moe/body.rs … and carries a gate run on the author's card, which counts as verified.

🔨 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 34b01ea into midagedev:main Oct 22, 2026
6 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 gpu-evidence Verified on the author's card: the pull request carries the gate run and its output

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant