Skip to content

gpu: make the partial head-256 cache append unsafe - #612

Merged
midagedev merged 1 commit into
midagedev:mainfrom
Burntgogi:fix/issue580-append-safety
Oct 21, 2026
Merged

midagedev merged 1 commit into
midagedev:mainfrom
Burntgogi:fix/issue580-append-safety

Conversation

@Burntgogi

@Burntgogi Burntgogi commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Problem and atomic API cutover

Refs #580. Both partial head-256 append entry points accepted ordinary safe calls although duplicate cache-valid positions (for example [0, 0]) give independent token CTAs the same K/V destination. Buffer lengths do not prove a distinct-writer invariant.

  • Make enqueue_head_norm_neox_append_256 and enqueue_head_norm_neox_append_256_q8 unsafe and document their # Safety contracts. The Q8 sibling closes review MUST_FIX 1.
  • Migrate every direct caller. Propagate the obligation through KvPlanes::append_256 (both cache arms) and the selecting-attention helper; no safe generic wrapper hides arbitrary uploaded positions. Producer-local callers cite the embedding sequence/window and separate cache-plane scope. The Q8 gate checks cache-valid host positions before upload; the f16 gate uses its existing distinctness assertion.
  • Preserve the precise rule: among the first m positions, values below ctx are pairwise distinct. Out-of-range words already fault and return before append. Repeated invalid saturation sentinels therefore create no cache writers.
  • Preserve every kernel, launch, geometry, byte formula, position readback and numerical/invalid-position rule. The stricter sibling launchers are unchanged. The separately filed head-128 defect is tracked in gpu: head-128 safe append APIs permit duplicate cache writers #614, not claimed fixed here.
  • Preserve the new release's complete unsafe-pin history; add only dated caller-contract deltas. docs/rust-quality.md records the writer/cache-scope example. No shim or permanent probe/test.

Rebased atomically after the MiniMax/Solar/Raon release merged: base faa8167, head 6f5043f. This supersedes the first revision's 995-entry proof.

Exercised checks on this head

Linux x86_64 / Intel i5-12600K; nightly-2026-08-28; cuda-oxide 87bc9518; CUDA 13.3; sm_86 compilation. This is an AMD-graphics host, not NVIDIA runtime evidence.

Check Observed result
Real safe compile consumers for F16 and Q8 Both rejected with E0133, one at each public launcher
Same real consumers with propagated contract and explicit unsafe CUDA-aware release build passed
Actual gate_qwen35moe_attn and gate_qwen4exp_mtp binaries CUDA-aware release build passed; not executed
Repository just lint, workspace/all targets/full recipe features including MiniMax Passed; warnings in untouched files remain
Owning static contributor slice 7 units / 0 red, including full check-recipes
Official committed-snapshot canonical PTX proof 3 bins / 7 carriers / 1054 entries; all 1054 identical, no reordered/different/one-sided entries, equal resource rows; both scans no-JIT

The baseline accepted safe calls (the original F16 consumer and the Q8 call in the previously compiled attention gate). The corrected two-path consumer was built with:

cargo oxide build --arch sm_86 -- -p bloomery-gpu-gates --features gpu --release --example append_contract_smoke
# ordinary safe functions: E0133 at both calls
cargo oxide build --arch sm_86 -- -p bloomery-gpu-gates --features gpu --release --example append_contract_smoke --bin gate_qwen35moe_attn --bin gate_qwen4exp_mtp
# explicitly unsafe consumers: success

The throwaway example was removed after the experiment. No race reproduction or GPU output is implied by a compile.

fmt rc=0 6s
check-arch rc=0 1s
check-comments rc=0 6s
check-model-tax rc=0 10s
check-recipes rc=0 150s
check-rustflags rc=0 0s
check-unsafe rc=0 0s
DONE tier=t0 total=7 red=0 wall=173s

Command: LC_ALL=C bash tools/contrib-check.sh --tier t0 --only '^(fmt|check-unsafe|check-comments|check-recipes|check-arch|check-rustflags|check-model-tax)$'.

Official immutable-snapshot proof (local CUDA environment, installed LLVM objcopy on PATH):

PATH=/tmp/bloomery-580-bin:$PATH BLOOMERY_BOX_LOCAL=1 BLOOMERY_ENV_FILE=/home/jutai05/bloomery-contributions/tooling/cuda-env.sh bash tools/canon-check.sh faa8167 6f5043ff --out /tmp/bloomery-580-canon-r2
scan-set: 3 bins cover 7 kernel carriers
canon-check: 3 bins, 1054 entries: 1054 identical, 0 reordered-only, 0 differs, 0 only-on-one-side; rows equal (jit columns not compared: no-jit both)

The current scan set is bloomery-serve (clef,gemma-embedding2,glm5next,hf,mimo2,minimaxm3,solar2), gate_kquant, gate_swap. No card, lease or gate lock. Earlier worktree-mode attempts that correctly refused compiler-generated untracked IR/PTX drift are not counted as proof.

Exact GPU handoff and remaining limits

Please retain needs-gpu until a real NVIDIA run supplies the affected runtime evidence. No CUDA runtime, sanitizer/race, graph/eager, token, or performance result is claimed. Local just pre-review was unavailable because the Claude CLI is absent; the normal repository review is still required.

The actual non-executing selector on this revision, given all three successful scan pairs, reports 153 of 219 gate recipes. It refuses to narrow because rope_neox.rs has no host-path row. I did not alter the table, suppress this refusal, or substitute two gates for its list:

tools/affected-gates.sh faa8167..6f5043ff --no-box --narrow --scan /tmp/bloomery-580-canon-r2/base/bloomery-serve.log /tmp/bloomery-580-canon-r2/head/bloomery-serve.log --scan /tmp/bloomery-580-canon-r2/base/gate_kquant.log /tmp/bloomery-580-canon-r2/head/gate_kquant.log --scan /tmp/bloomery-580-canon-r2/base/gate_swap.log /tmp/bloomery-580-canon-r2/head/gate_swap.log

just narrow faa8167 6f5043ff regenerates that scan/selection on the configured workstation. Direct attention/MTP priorities are gate-gpu-qwen35moe-attn and gate-gpu-qwen4exp-mtp, not replacements for the selector's retained list. Its always-checks and PR T0 remain in force.

@github-actions github-actions Bot added documentation Improvements or additions to documentation 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 21, 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 Q8 head-256 sibling retains the duplicate-writer defect.

Must fix

1. Carry the writer contract through the Q8 launcher

crates/gpu/src/rope_neox.rs:2497 still exposes a safe public call. With m=ctx=2, n_head=n_kv=1, sufficiently sized buffers, small finite input rows, unit gains, positive epsilon, an identity rope table and uploaded positions [0, 0], all shape checks pass. Key CTAs 1 and 3 both append row 0 in norm_partial_append (line 371). The non-atomic Q8 code and scale stores at crates/gpu/src/rope_neox.rs:596 race; no duplicate-position check raises a fault. The caller can read cache data produced by competing writers. This is a kind A sibling-path defect (R28).

Closing both head-256 entry points now avoids another API migration and caller audit. Apply this patch, then run the formatter; the existing KV contract and a host distinctness assertion discharge the two caller obligations.

--- a/crates/gpu/src/rope_neox.rs
+++ b/crates/gpu/src/rope_neox.rs
@@ -2496,3 +2496,7 @@
     /// capturable.
-    pub fn enqueue_head_norm_neox_append_256_q8(
+    ///
+    /// # Safety
+    /// Cache-valid positions among the first `args.m` entries of `args.pos`
+    /// are pairwise distinct (`pos < args.ctx`).
+    pub unsafe fn enqueue_head_norm_neox_append_256_q8(
         &self,
--- a/crates/gpu/src/arch/qwen3moe/scratch.rs
+++ b/crates/gpu/src/arch/qwen3moe/scratch.rs
@@ -565,3 +565,5 @@
             },
-            KvPlanes::Q8 { kq, kd, vq, vd } => neox.enqueue_head_norm_neox_append_256_q8(
+            KvPlanes::Q8 { kq, kd, vq, vd } =>
+            // SAFETY: append_256 requires distinct cache-valid positions.
+            unsafe { neox.enqueue_head_norm_neox_append_256_q8(
                 stream,
@@ -587,3 +589,3 @@
                 },
-            ),
+            ) },
         }
--- a/crates/gpu-gates/src/bin/gate_qwen35moe_attn.rs
+++ b/crates/gpu-gates/src/bin/gate_qwen35moe_attn.rs
@@ -524,2 +524,4 @@
         use bloomery_gpu::rope_neox::PartialNeoxQ8Args;
+        assert!(pos.iter().enumerate().all(|(i, p)| !pos[..i].contains(p)),
+                "rope gate: positions must be distinct");
         let m = pos.len();
@@ -540,3 +542,4 @@
         let mut vd = DeviceBuffer::from_host(stream, &sc)?;
-        kern.enqueue_head_norm_neox_append_256_q8(
+        // SAFETY: the host assertion above checks distinct positions before upload.
+        unsafe { kern.enqueue_head_norm_neox_append_256_q8(
             stream,
@@ -562,3 +565,3 @@
             },
-        )?;
+        ) }?;
         stream.synchronize()?;
--- a/tools/unsafe-ratchet.txt
+++ b/tools/unsafe-ratchet.txt
@@ -391,3 +391,5 @@
 # Ten audited caller blocks discharge that obligation; no device code or launch changes.
-gpu 2034 240 10
+# PIN(2026-10-21): gpu +1 block and +1 fn: the Q8 head-256 launcher carries
+# the same writer contract, discharged by the existing append_256 contract.
+gpu 2035 241 10
 # PIN(2026-10-01): gpu-deepseek41 459 -> 464 blocks, 51 -> 52 fns, a new kernel entry, not old code relaxed:
@@ -461,3 +463,5 @@
 # contracted launcher only after rope_gate::run checks distinct host positions.
-gpu-gates 85 5 1
+# PIN(2026-10-21): gpu-gates +1 block: the Q8 rope gate checks host positions
+# are distinct before invoking its contracted launcher.
+gpu-gates 86 5 1
 # PIN(2026-10-15): gpu-gemma-embedding2 0 -> 1 blocks, new code, not old code relaxed: the head-512

Checked

Duplicates: 0 new items; 3 declarations changed safety. Dryer reported no pairs; its omitted gpu-gates scope was checked by Grep.
Complexity: crapper flagged no functions; no branch growth.
Silent failure: 0 added default/error-suppression sites. Invalid-position handling was followed through the no-append return to the head's fault refusal.
Tests: no tests added. Removing the changed gate caller's unsafe block would make its call a compile-time error; this was not executed during validation.
Gates: both unsafe-count changes have dated PIN reasons; no numeric band changed.
Escape catalog: C1–C4 have no matching changed code.
Performance: decode/prefill callers change no allocations, launches, copies, synchronization or reduction order.

Notes

Static review only; no builds or runtime gates executed. The PR explicitly reports no NVIDIA execution and supplies no card gate evidence.

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

Filed outside this PR: #614

@Burntgogi

Copy link
Copy Markdown
Contributor Author

Resolved MUST_FIX 1 in 6f5043f, atomically rebased onto faa8167 (the merged MiniMax/Solar/Raon release). Both head-256 formats now expose the same cache-valid distinct-writer contract; the KV Q8 arm propagates its existing obligation, and the Q8 gate checks the host positions before upload. Both ordinary real consumers now fail E0133, while the explicit-contract consumers and actual attention/MTP binaries compile. Fresh official proof: 3 bins / 7 carriers / 1054 entries, all identical, equal rows, no-JIT both. Current workspace lint and seven owning static units passed. The refreshed PR body supersedes the old proof and records the exact 153/219 conservative selector result. NVIDIA execution remains explicitly unclaimed; #614 remains a separate head-128 issue.

@Burntgogi
Burntgogi force-pushed the fix/issue580-append-safety branch from bed4c76 to 6f5043f Compare October 21, 2026 14:52

@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 is fixed at crates/gpu/src/rope_neox.rs:2501. The Q8 launcher is unsafe, its KV caller propagates the contract, and its gate checks distinct cache-valid positions before upload.

Verdict: CLEAN: the Q8 sibling now carries the required writer contract, and no must-fix defect remains in the interdiff.

Non-blocking

⚠ Retain Q8 API regression coverage: crates/gpu/src/rope_neox.rs:2501. Changing this declaration back to pub fn leaves the committed callers and runtime assertions valid; the E0133 smoke consumer was removed.
Retain the safe-call probe as a compile-fail check, or explain why recurrence coverage is omitted. Keeping it now prevents a later edit from silently restoring the safe API.

Checked

Duplicates: 0 new functions, types or constants; 4 existing declarations change safety across the full patch. Grep found both Q8 callers. Dryer reported 0 pairs; its omitted gpu-gates scope was checked manually.
Complexity: crapper flagged no functions; the Q8 caller gains a precondition check, with no production branch growth.
Silent failure: 0 new suppression sites. Invalid-position and nonfinite Q8 paths were followed to named faults and token readback refusal.
Tests: the Q8 host predicate rejects duplicate cache-valid positions and permits repeated invalid sentinels. The PR reports temporary E0133 checks; no committed compile-fail coverage was found.
Gates: both unsafe-count changes have dated PIN reasons. No numeric band changed.
Escape catalog: C1–C4 match no changed code.
Performance: decode/prefill paths add 0 allocations, launches, copies or synchronizations per token; reduction order is unchanged. This is the move class; the PR reports identical canonical PTX.

Notes

No CUDA build or GPU gate was run during this review. The PR explicitly supplies no NVIDIA runtime evidence.

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

@Burntgogi

Copy link
Copy Markdown
Contributor Author

Addressing the non-blocking recurrence-coverage note on 6f5043ffaf90e54cbbf2eaff656f1469896c45e9:

I have not retained a permanent GPU compile-fail fixture in this patch. .github/workflows/pr.yml runs the CPU-only T0 surface; it deliberately does not install even the CUDA-header prerequisites of T1. The repository has model compile-fail doctests, but the searched GPU crates/tools do not have a corresponding CUDA-aware negative-compilation runner. The real public GPU consumer needs the supported cargo oxide build path. This is a compiler/toolchain requirement, not a claim that a card is required for the compile-fail check.

Rather than introduce a new CUDA test stage here, or test copied/stubbed declarations instead of the real API, I exercised the temporary real consumer against the final revision: both ordinary F16/Q8 calls fail specifically with E0133, while the explicit unsafe consumers and the actual attention/MTP binaries compile. The commands and results are recorded in the PR body; the temporary source was removed.

This intentionally leaves a permanent API-regression coverage gap: the existing valid callers/runtime assertions alone would not prevent changing pub unsafe fn back to pub fn. The smoke result is not presented as a retained regression test. NVIDIA runtime validation also remains outstanding under needs-gpu.

@midagedev
midagedev merged commit 1e8e923 into midagedev:main Oct 21, 2026
6 checks passed
@midagedev

Copy link
Copy Markdown
Owner

Merged as 1e8e923 on main, with no conflicts.

Card evidence (RTX 3090 and RTX A6000):

  • just narrow: every bin's --no-jit scan is identical to main's, so no kernel moved.
  • Fixture tier over the list that recipes.py reach keeps for the changed files (63 gates, gate-gpu-lib and gate-ptx-spill included): green.
  • gate-gpu-qwen4exp-mtp and gate-gpu-qwen35moe-attn on the real tier: green.

Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation gpu The card engine: crates/gpu*, crates/app 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.

2 participants