Skip to content

gpu: require distinct cache writers for NeoX appends - #669

Merged
juliankang4 merged 5 commits into
midagedev:mainfrom
juliankang4:fix-review-bot-issue-614-gpu
Oct 22, 2026
Merged

juliankang4 merged 5 commits into
midagedev:mainfrom
juliankang4:fix-review-bot-issue-614-gpu

Conversation

@juliankang4

Copy link
Copy Markdown
Collaborator

NeoX 어텐션의 cache append가 같은 cache 행에 두 번 쓰는 호출을 safe 코드로도 받던 문제를 고쳐서, 위치가 겹치지 않는다는 계약을 호출하는 쪽이 책임지게 했습니다.

What and why

Closes #614.

The head-128 f16 and Q8 append entries in crates/gpu/src/rope_neox.rs were safe functions, but each launch writes one cache row per position. If two positions in a call map to the same cache row, two blocks write that row at once and the result depends on scheduling. The compiler did not stop such a call.

The head-256 entry already has this contract. This change gives the same one to the entries that lacked it:

  • enqueue_head_norm_neox_append and enqueue_head_norm_neox_append_q8 (head-128, f16 and Q8) and the K192 plane and ring appends are now unsafe fn. Their docs name the requirement: the cache positions of one call are distinct. For the ring, the positions must differ modulo the ring height, because two positions that differ by a multiple of the height still share a row.
  • The callers carry the contract. In qwen3moe (the KV helper and the dispatch, wide and slot paths) and gpu-mimo2 (step, prefill and slot paths), each unsafe block wraps one call, and its SAFETY line points at the code that generates consecutive positions per sequence.
  • The gate host helpers take host-supplied positions, so they check them before upload. One shared check, check_cache_positions in crates/gpu-gates/src/rope_gate.rs, refuses duplicate writers (and zero cache rows) with a named error. The head-128, common partial-turn, head-256 Q8 and K192 helpers all call it, and the two older inline checks now use it too.

No kernel, launch geometry or device arithmetic changes. The production path gains no launch, copy, sync or allocation, because it trusts the position generators instead of reading positions back.

Tests added:

  • A compile_fail doctest on each of the four public append functions. It calls the function without unsafe, so a build where the qualifier is dropped fails the test.
  • cache_writers_are_distinct covers the shared check: positions [0, 0] are refused, [0, 1] pass, and for a ring of height 2, [0, 2] are refused while [1, 2] pass.
  • One gate test per helper (hw_rope_rejects_duplicate_writers, hw_neox_cache_writers, hw_q8_rope_rejects_duplicate_writers, hw_append_rejects_duplicate_writers) feeds duplicate positions and expects the named error. hw_neox_cache_writers also runs positions [0, 1] through the f16 and Q8 head-128 helpers, eager and in a CUDA graph, and requires every Q, K and cache plane bit to match, with one graph node.
  • just gate-gpu-rope-writers runs these without a model file. It is listed in tools/gate-class.tsv, and the recipes self-test expects the new dependency on the record schema.

tools/unsafe-ratchet.txt moves with dated PINs. Unsafe blocks and unsafe fns rise because the contract moves to the callers:

Crate Blocks before Blocks after Fns before Fns after
gpu 2127 2136 249 257
gpu-gates 89 99 5 5
gpu-mimo2 0 5 0 1

Each new block has its own SAFETY line.

Release notes: Fixed: the head-128 and K192 cache append entries require distinct cache positions as an unsafe contract, and the gate helpers refuse duplicate writers

Code shape

  • No second copy. The duplicate-position check had two inline copies in the gates. They and the new append helpers use check_cache_positions. I looked for the same writer-uniqueness check in the other gate helpers in rope_gate.rs, qwen3moe.rs and the two gate binaries; all of them now call it.
  • Model code holds only architecture facts. The qwen3moe and MiMo files only forward the contract to the calls they already made. The common owner gained no per-model branch.
  • Dead code is gone. Nothing was made unused.
  • No silent failure. Duplicate writers and zero cache rows are named errors. The out-of-range sentinel position is not a cache writer, so repeating it is allowed.
  • Comments state what is true now. The new comments describe the position invariant and the SAFETY reasons.
  • No relaxed gate. No band or tolerance moves. The unsafe ratchet rises with dated PINs as shown above.
  • cargo fmt is clean on what I touched. cargo clippy was not run here.

Duplication found or removed (path:line): the two inline duplicate-position checks in crates/gpu-gates/src/rope_gate.rs, now one check_cache_positions.

What I ran

FAIL first. I added only the four compile_fail doctests on top of the base, with the append functions still safe, and ran them on a DGX Spark:

cargo oxide test --arch sm_121 -- -p bloomery-gpu --release --doc rope_neox::RopeNeoxKernels -- --nocapture
Test compiled successfully, but it's marked `compile_fail`. (four times, one per append function)
test result: FAILED. 0 passed; 4 failed; 0 ignored; 0 measured; 0 filtered out

With the fix, on a DGX Spark:

BLOOMERY_ARCH=sm_121 just gate-gpu-rope-writers
compile fail doctests: test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
bloomery_gpu_gates lib:   test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 154 filtered out
gate_mimo2_flash:         test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
gate_qwen35moe_attn:      test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

Other checks on the head that goes up:

  • Full test tier (worker t0, 107 checks): DONE tier=t0 total=107 red=0.
  • cargo check --workspace --all-targets with the GPU feature set, on an RTX 5090 machine: finished with exit code 0. This covers the changed public signatures, benches and gate binaries. It ran one commit before the last one, which only changed the recipes self-test list and two PIN lines.
  • cargo fmt --check, tools/check-unsafe.sh, tools/recipes.py check and tools/gate_class.py check passed (check-unsafe: ok). This run was before the last rebase onto main; the unsafe counts above were recomputed after it.

Not run: the other just gate-gpu-* gates, which need the maintainers' workstation. No speed claim is made. The kernel and argument source sections are byte-identical to the base, so I ran no PTX comparison or timing A/B.

What I ran into

This does not block the PR. The race is only reachable through the new unsafe contract and the gate helpers, so I did not measure what value a duplicate position leaves in the cache. The proof of the old behavior is that the safe call compiled (the FAIL-first run).

Hardware (if the change is for a machine)

The gate and doctests ran in a CUDA 13.3.1 container on a DGX Spark (GB10), nvidia-smi driver and CUDA lines:

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

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 tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo 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 writer test duplicates the existing graph-parity contract.

Must fix

1. Keep graph parity in its existing gate

qwen3moe.rs:591 repeats the eager/replay equality and one-node checks already owned by gate_qwen3moe_rope.rs:283 and gate_qwen3moe_rope.rs:545, through the same launch helpers. This violates R14 and the one-test-per-contract rule (kind B).
Removing these assertions now keeps future graph-contract changes in one gate. Keep valid-position acceptance controls. Replace the success block after the rejection loop, through the last parity assertion, with:

rows.pos = vec![0, 1];
for graph in [false, true] {
    launch(
        &kernels,
        gpu.stream(),
        graph.then_some(&gpu),
        gpu.unlabelled_sink(),
        &rows,
        &gains,
        &gains,
        &table,
        1e-5,
        2,
    )?;
    launch_q8(
        &kernels,
        gpu.stream(),
        graph.then_some(&gpu),
        gpu.unlabelled_sink(),
        &rows,
        &gains,
        &gains,
        &table,
        1e-5,
        2,
    )?;
}

Non-blocking

⚠ Complete the validation evidence: rope_neox.rs:2079, R28 requires identical base/head PTX scans for this API change. Attach the scans and FAIL-first output for the host duplicate/modulo refusal cases. The supplied FAIL-first run covers only the unsafe qualifiers.

Checked

Duplicates: six new functions read; dryer reported zero qualifying pairs and excluded gpu-gates. The graph checks above repeat existing gate clauses through the same launch helpers.
Complexity: append_launch, rope_q8_run, launch_q8, launch and rope_gate::run each gained one propagated validation error edge.
Silent failure: five host validation calls propagate named errors before upload.
Tests (static mutation inspection): removing the public unsafe qualifiers breaks the four compile-fail doctests. Dropping the writer checks breaks the rejection assertions; comparing positions without modulo breaks the ring unit case. CUDA tests were not run here.
Gates: unsafe ratchets and the recipe expectation have dated PINs and reasons; numeric bands did not move.
Escape catalog: C1–C4 do not match the changed code. No ledger lessons are in force.

Notes

The PR supplies gate output and GB10 card/driver lines, but omits the tested base/head commit hashes. GPU evidence is incomplete.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/gate_mimo2_flash.rs, crates/gpu-gates/src/bin/gate_qwen35moe_attn.rs, crates/gpu-gates/src/qwen3moe.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 fix-review-bot-issue-614-gpu branch from 07960af to 5472c3c Compare October 22, 2026 19:57

@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 remains after tracing cache-writer uniqueness, ring wrapping and invalid positions.

Non-blocking

⚠ Attach the PTX proof: crates/gpu/src/rope_neox.rs:2079. R28 requires identical PTX for this safety-contract change. Attach just canon-check 59093a52271d484890f7adbf6962f6eda4be0acf output. The device source is byte-identical, but the required codegen comparison is absent.

⚠ Correct the parity evidence: crates/gpu-gates/src/qwen3moe.rs:593. The body says this test compares output bits and requires one graph node. It discards the returned outputs and node counts. Correct the description; cite an existing gate-gpu-qwen3moe-rope run for parity evidence.

Checked

Duplicates: 6 new Rust definitions and 4 doctest snippets checked; no duplicate owner. Dryer reported 0 pairs; its excluded gpu-gates files were searched manually.
Complexity: append_launch 16→17, rope_q8_run 21→22, launch_q8 24→25, launch 20→21 and rope_gate::run 17→18 each add one validation error edge.
Silent failure: 1 new default-like site followed; rows.unwrap_or(ctx) selects plane height. All 5 validation calls propagate named errors. Invalid sentinels raise CachePos before cache writes.
Tests (static mutation review): removing unsafe at rope_neox.rs:2079/2451/2696/2726 makes the four doctests red. Removing validation at rope_gate.rs:267, qwen3moe.rs:329/467, gate_qwen35moe_attn.rs:525 or gate_mimo2_flash.rs:1433 makes the corresponding helper test red. Removing modulo at rope_gate.rs:248 fails the unit test's [0,2] assertion; treating ctx as valid fails its repeated-sentinel assertion. Removing the recipe's --lib dependency breaks the changed schema-selection assertion.
Gates: unsafe ratchets and schema expectation have dated PINs; no numeric tolerance moved.
Performance: decode and prefill add 0 launches, copies, synchronizations or allocations; device code and argument definitions are byte-identical.
Adversarial checks: zero rows return before modulo; oversized ring batches are refused; consecutive positions are distinct modulo a sufficiently tall ring; equal positions across sequences use disjoint borrowed planes.
Escape catalog: C1–C4 do not match.

Notes

The reported Spark gate run lacks both commit hashes, so gpu.json marks its evidence incomplete. GPU gates and doctests were not executed locally.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/gate_mimo2_flash.rs, crates/gpu-gates/src/bin/gate_qwen35moe_attn.rs, crates/gpu-gates/src/qwen3moe.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 40fec96 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 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.

gpu: head-128 safe append APIs permit duplicate cache writers

1 participant