Skip to content

Mac port train 1: the device contract, the first Metal kernels, the record core and the device-free qwen3moe chain (#593) - #666

Merged
midagedev merged 22 commits into
mainfrom
mac-train3
Oct 23, 2026
Merged

midagedev merged 22 commits into
mainfrom
mac-train3

Conversation

@midagedev

@midagedev midagedev commented Oct 22, 2026 •

Copy link
Copy Markdown
Owner

The Mac port's first train (#593): the device contract, the CUDA side implementing it, the first Metal kernels, the record core, and the qwen3moe chain plan with its walk.

What lands

  • bloomery-device: the device contract every backend implements (elements u8 to f64 with atomic twins, spans and casts, device read/write/copy, ordered shared pages, a stream, a typed error), one fault table, one set of contract clauses. crates/gpu implements it; its fault table is a re-export. gate-gpu-device runs the clauses on a card.
  • bloomery-metal: the Q4_K and Q6_K mat-vecs (adapted from ggml-metal, notice in THIRD_PARTY_NOTICES.md), norm on load, the residual epilogue and the embed. gate_metal_qwen35moe_kernels checks them against an f64 oracle on the fixture's tensors with a derived band; --mutants-all turns each clause red. It runs in just lab-metal on a Mac.
  • bloomery-record: the record core, lifted from gpu-gates; the kinds stay there.
  • bloomery-chain: the qwen3moe plan moved to a device-free crate (sites, the header reads, card_leg), and the walk over ChainOps (ten ops) is the one owner of the layer order. CUDA launch facts stay in crates/gpu.
  • crates/gpu/src/arch/step_order.rs: each architecture's step order in the arch registry.

Proof

  • Move class, at this tip on e53cabebb, just canon-check (--no-jit both sides) per range whose scan sets match: the device seam's CUDA side (2c545928e against its parent): 3 bins, 1072 entries, 1072 identical; the seam's review fixes (0139dfc98 against 57dad0357): 4 bins, 1396 identical; the chain commits (bd6930522 against f4675245a): 4 bins, 1396 identical. The one bin the train adds is gate_gpu_device (b0f3b817a). No existing kernel moved.
  • Fixture batch (tools/gate-batch.sh --tier fixture --ledger, the union of recipes.py reach over the changed files): 168 items, red 0: 86 ran green, 82 deferred by name to the real tier (41 real-only, 36 real-file, 4 no-fixture, 1 needs-env), which the release batch and just weekly run; wall 63 min.
  • After rebasing onto main's body38.rs change: the 27 gates where its recipes.py reach meets this list, fixture tier: red 0 (13 ran green, 14 deferred by name); box just check rc 0.
  • Main's later files (hermes.rs, a text parser; folder.rs; the BF16 head kernels) touch no file of this branch; the canon-check above is at the newest base.
  • Real tier: gate-gpu-qwen35moe-e2e rc 0 (88 s), gate-gpu-qwen3moe-e2e rc 0 (152 s).
  • gate-gpu-device and gate-gpu-lib green (fixture tier) after the last change to crates/gpu/src/device.rs.
  • Cards: NVIDIA GeForce RTX 3090, 615.71.09, 24576 MiB, 250.00 W and NVIDIA RTX A6000, 615.71.09, 49140 MiB, 300.00 W. Batch summary lines: DONE total=168 red=0 tier=fixture skipped=28 wall=3135s; DONE total=27 red=0 tier=fixture skipped=0 wall=5472s; DONE total=2 red=0 tier=real skipped=0 wall=245s; DONE total=2 red=0 tier=fixture skipped=0 wall=1014s.
  • Review fixes (the bot's four): the stream's wait holds the pending list under its lock through the poll, and a new device-gate clause (sync_two_waiters) runs two waiters on one held stream (red on the old wait); the norm refuses a scale that is not finite and positive, with an infinite-epsilon case for both quants (red on the old predicate); the timer refuses an unknown or missing --only (exit 64); check_word is gone. just lab-metal PASS (sync_two_waiters PASS, 10 kernel mutants red); clippy (macOS and x86_64-linux), fmt, check-comments, check-unsafe rc 0.
  • Mac: just remote-static origin/main before the review fixes: fmt, lint (0 warnings, ratchet 3), 76 combos 0 red, check-recipes 145 blocks and every check script green.
  • Box: just check rc 0, Cargo.lock unchanged.
  • Second review's fixes, rebased onto 010729ed6: the mat-vec epilogue raises the norm site and writes NaN for a row whose scaled sum is not finite (no lane-divergent continue; two kernel mutants added, norm_no_raise now red on 4 cases); Quant names its ggml type as a const and takes its block bytes from gguf::type_size (the gate's copies are gone); body35_slots passes the slot rows to delta_in, which is bounded by MAX_PASS_ROWS; check-arch.sh says why the gate bins are exempt. just canon-check from the reviewed tip (1ddfc4661) to this tip: 4 bins, 1408 entries, 1408 identical. just lab-metal PASS (10 kernel mutants red), clippy (macOS and x86_64-linux), fmt, check-comments, check-arch rc 0.
  • Fixture batch at this tip (affected over the review fixes, narrowed by the scan pair above): DONE total=61 red=1 tier=fixture skipped=3 wall=1648s, 31 deferred to the real tier by name. The one red, gate-gpu-qwen35moe-leg@BLOOMERY_FIXTURE_VARIANT=q35iq3s6 (placed common wide arm: logits rel 1.102e-1 … (bound 1e-1)), is red on origin/main 31b5be41f with the same value and tokens, and gate-ptx-spill (mxfp8_gemv_ids spill 28 against its pin 0) is red there too, with the entry's md5 6a1620374c4367a567928af5f9f4b0a0 the same on both sides. Both are main's and are tracked apart from this train.

The dispatch path moved only by the walk refactor with identical PTX and node counts, so its predicted speed effect is 0; a same-lease A/B on the A6000 follows the landing.

Written with Claude Code (lead session and delegated rounds); every gate was re-run by the lead.

🤖 Generated with Claude Code

@midagedev midagedev added the needs-gpu Changes code a card must check, and carries no gate run on a card label Oct 22, 2026
@github-actions github-actions Bot added gpu The card engine: crates/gpu*, crates/app 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: concurrent Metal waits can report completion early, and invalid inputs can return successful results.

Must fix

1. Keep pending work protected until the wait finishes

crates/metal/src/stream.rs:156: thread A removes unfinished buffers and releases the lock. Thread B then sees no pending work and returns Ok(()); Device::read can return stale output, and write can overwrite a running kernel's input. Stream: Sync now permits this interleaving.
Close this contract before more callers adopt the shared stream. Keep the lock through polling, including a bounded wait to acquire it:

pub fn sync_for(&self, timeout: Duration) -> Result<(), DeviceError> {
    use std::sync::TryLockError::{Poisoned, WouldBlock};
    let deadline = Instant::now() + timeout;
    let timed_out = || DeviceError::backend(
        "command buffer",
        format!("not done within {} ms", timeout.as_millis()),
    );
    let mut state = loop {
        match self.committed.try_lock() {
            Ok(state) => break state,
            Err(Poisoned(e)) => break e.into_inner(),
            Err(WouldBlock) => {
                if Instant::now() >= deadline {
                    return Err(timed_out());
                }
                std::thread::sleep(POLL);
            }
        }
    };
    let pending = std::mem::take(&mut state.pending);
    let mut first = None;
    for buffer in pending {
        while !is_over(buffer.0.status()) && Instant::now() < deadline {
            std::thread::sleep(POLL);
        }
        match buffer.0.status() {
            MTLCommandBufferStatus::Completed => {}
            MTLCommandBufferStatus::Error => {
                first.get_or_insert_with(|| command_buffer_error(&buffer));
            }
            _ => {
                first.get_or_insert_with(timed_out);
                state.pending.push(buffer);
            }
        }
    }
    first.map_or(Ok(()), Err)
}

Add a held-stream case with two simultaneous waiters; neither may succeed before release.

2. Reject a zero RMS scale

crates/metal/kernels/norm.metal:40: a finite sum of squares and eps = +∞ produce scale = 0. This predicate accepts it, so both mat-vecs write plausible zero rows and leave the fault clean. The host launcher accepts this epsilon, although NormOnLoad promises a fault for zero scale.
Pin the boundary while both kernels share this helper. Replace the predicate and add the infinite-epsilon fault case for both quants:

inline bool rms_usable(float sum_squares, float scale)
{
    return isfinite(sum_squares) && isfinite(scale) && scale > 0.0f;
}

3. Refuse invalid timing-probe selections

crates/metal/src/bin/metal_matvec_time/mac.rs:260: --only q4kk skips every shape and exits 0. A trailing --only instead runs both types. Both report success for an invalid selection.
Reject these inputs before scripts rely on exit 0. Insert after the only assignment:

if args.iter().any(|a| a == "--only")
    && !matches!(only, Some("q4k" | "q6k"))
{
    eprintln!("metal_matvec_time: --only takes q4k or q6k");
    return ExitCode::from(64);
}

4. Remove the one-use count-check wrapper

crates/metal/src/kernels/mod.rs:89: check_word only discards the result of the existing word owner. Its sole caller is the embedding launch. This adds a function and import without adding a contract.
Remove the alias while it has one caller. Delete check_word and its documentation; replace the import and call in kernels/embed.rs with:

use super::{Kernels, args_bytes, check_window_len, word};
word("embed", "the value count", values)?;

Checked

Elements: check_word has one caller and only discards word's converted value.
Silent failure: traced concurrent sync into device reads/writes, zero scale into both mat-vec outputs, and invalid --only into the success exit.
Tests: existing norm fault cases omit infinite epsilon. Validation was static; hardware gates were not run.
Inline: the norm replacement is valid code on added line 40. All four findings cite added lines.
Escape catalog: C1–C4 do not apply to the retained findings. No ledger lessons are in force.

Notes

The PR body reports card runs but omits the nvidia-smi line and gate command output required by CONTRIBUTING.md. The GPU-evidence flag is therefore false.

Card check: needs-gpu. This pull request changes crates/gpu-gates/Cargo.toml, crates/gpu-gates/src/bin/gate_gpu_device.rs, crates/gpu-gates/src/record.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)

Comment thread crates/metal/kernels/norm.metal Outdated
// input.
inline bool rms_usable(float sum_squares, float scale)
{
return isfinite(sum_squares) && isfinite(scale);

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.

A zero scale from infinite epsilon currently writes zero rows without raising the norm fault.

Suggested change
return isfinite(sum_squares) && isfinite(scale);
return isfinite(sum_squares) && isfinite(scale) && scale > 0.0f;

midagedev added a commit that referenced this pull request Oct 22, 2026
… from the head's checkout

GitHub's diff media type answers HTTP 406 above 20000 lines, and both the
diagnostics and the review job died on it (#666, 20440 lines). pr-diff.sh
asks the API first; on a 406 it deepens the head's shallow checkout from the
base repository until it holds the merge base and runs git diff from there,
the same base...head diff. Any other failure ends it by name.

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

@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: Metal norm launches can return NaNs with a clean fault word; duplicate owners and an unpinned check exemption remain.

Must fix

1. Raise the norm fault for non-finite gain products

crates/metal/kernels/matvec_q4k.metal:172 and crates/metal/kernels/matvec_q6k.metal:142: x[i] = 1, eps = 1 and gain[0] = NaN pass the host's shape checks and leave sum_squares and scale finite. The dot becomes NaN, but no fault is raised. The caller reads NaN rows and a clean fault word, contrary to NormOnLoad's contract. Catching it here preserves the originating layer.

Replace the scale multiplication in both norm epilogues with:

sum_all *= scale;
if (!isfinite(sum_all)) {
    raise(faults, args.layer, BLOOMERY_FAULT_SITE_NORM_QUANT);
    sum_all = NAN;
}

Add NaN/infinite-gain cases for both quants to norm_on_load. Its current activation/epsilon cases stay green on this defect.

2. Reuse the quant metadata owner (R14)

crates/metal/src/kernels/matvec.rs:24 repeats the byte sizes already owned by crates/gguf/src/quant.rs:243. The Quant-to-GGML map is also copied in crates/metal/src/bin/gate_metal_qwen35moe_kernels/clauses.rs:50 and crates/metal/src/bin/shared/oracle.rs:141. Consolidating now removes two maps before backend metadata diverges.

Use these methods in Quant's existing impl:

/// The GGUF type this kernel reads.
pub fn ggml(self) -> gguf::quant::GgmlType {
    match self {
        Self::Q4K => gguf::quant::GgmlType::Q4_K,
        Self::Q6K => gguf::quant::GgmlType::Q6_K,
    }
}

pub fn block_bytes(self) -> usize {
    usize::try_from(self.ggml().type_size().expect("both kernel types have GGUF rows"))
        .expect("Q4_K and Q6_K block sizes fit usize")
}

Delete Tensor::ggml and oracle::ggml_type; replace their calls with self.quant.ggml() and quant.ggml(). In q4k_magnitude_blocks, delete const BLOCK and replace its loop header with:

for block in out.chunks_exact_mut(Quant::Q4K.block_bytes()) {

Remove block_shape's byte-size comparison, which is then true by construction; retain its block-values check.

3. Reuse the delta input checks (R14)

crates/gpu/src/arch/qwen3moe/body35_slots.rs:468 repeats the kernel/arena/shape checks in crates/gpu/src/arch/qwen3moe/delta.rs:89 before calling the same project function. Slot passes are capped at GEMV_COLS. Reusing the owner removes the independent predicate now.

fn delta_in(&mut self, l: LayerCtx<'_>, d: &DeltaPlan) -> Result<(), GpuError> {
    delta::delta_in(&layer_ctx(self.c, l)?, d, self.s, l.m)
}

4. Pin the architecture-check exemption

tools/check-arch.sh:97 exempts every Metal bin from rule 2 without a dated reason. This relaxes a check. Record the scope now so later changes can distinguish fixture code from engine code. Add immediately above scan_lits:

# PIN(2026-10-22): Metal gate/probe bins name fixture tensors, like gpu-gates bins; exempt those binaries from rule 2.

Checked

Duplicates: confirmed the quant metadata and delta input-check copies against their existing owners. Both proposed consolidations remove more code and names than they add.

Complexity: no finding rests on a complexity score.

Silent failure: followed gain binding, both norm reductions, output readback and fault-word decoding; no guard rejects a non-finite gain.

Tests: norm_on_load covers non-finite activations and infinite epsilon, but no non-finite gain. NaN-gain cases for both quants would expose finding 1. Hardware gates were not run here.

Gates: the added Metal-bin exemption has no dated reason. No retained finding uses escape catalog C1–C4; no ledger lessons are in force.

Notes

The body omits model paths and full just gate-* commands with their output, so the supplied card/batch summaries do not meet the GPU evidence list.

Card check: needs-gpu. This pull request changes crates/gpu-gates/Cargo.toml, crates/gpu-gates/src/bin/gate_gpu_device.rs, crates/gpu-gates/src/record.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)

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

  • Norm fault handling: fixed for both quants, with NaN and infinite-gain cases.
  • Quant metadata: fixed through Quant::ggml() and GGUF block sizes.
  • Delta input checks: fixed by reusing delta::delta_in.
  • Architecture-check exemption: still open at tools/check-arch.sh:92.

Verdict: MUST_FIX: the architecture-check exemption still lacks the required dated PIN.

Must fix

1. Date the architecture-check exemption

tools/check-arch.sh:98: the added Metal-bin exclusion relaxes rule 2. The comment at line 92 explains why, but lacks the PIN(YYYY-MM-DD): required for a gate relaxation. This is a kind B defect with a mechanical fix: date the existing reason.

Replace the added comment with:

  # PIN(2026-10-22): Metal gate/probe bins name fixture tensors, like gpu-gates bins; exempt those binaries from rule 2.

Checked

Duplicates: 1 new item checked (Quant::ggml), none duplicated; metadata and delta checks now reuse their owners. No dryer pairs were available.

Complexity: no crapper results. Both matvec kernels add an error branch; norm_on_load adds cases to its existing loop.

Silent failure: both norm epilogues raise NormQuant and write NaN for a non-finite scaled row; the gain cases check the fault and output.

Tests: removing either new row-fault guard makes the added gain cases fail expect_fault. Changing production BLOCK_VALUES to 128 makes block_shape fail. These are source-level mutation checks; hardware gates were not run here.

Gates: no numeric bands moved; the Metal-bin exclusion still lacks its dated PIN. The unsafe ratchet updates retain dated reasons.

Escape catalog: the retained finding does not match C1–C4.

Notes

The diagnostics job did not finish; dryer and crapper did not produce results.

The body lacks model paths and full gate commands with output required by CONTRIBUTING.md's GPU evidence list.

Card check: needs-gpu. This pull request changes crates/gpu-gates/Cargo.toml, crates/gpu-gates/src/bin/gate_gpu_device.rs, crates/gpu-gates/src/record.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)

Comment thread tools/check-arch.sh Outdated
[ -z "$hits" ] || cross="${cross:+$cross$'\n'}$hits"
}
scan_lits() { # scan_lits <path…>: rule ②'s hits into lits
# The gpu-gates and metal bins are exempt: they are gates and probes, and naming the fixture's tensors is their job.

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.

The added Metal-bin exemption at line 98 relaxes rule 2; this reason still needs the required dated PIN.

Suggested change
# The gpu-gates and metal bins are exempt: they are gates and probes, and naming the fixture's tensors is their job.
# PIN(2026-10-22): Metal gate/probe bins name fixture tensors, like gpu-gates bins; exempt those binaries from rule 2.

github-actions[bot]
github-actions Bot previously approved these changes 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.

Since the last review:

  • Architecture-check exemption: fixed at tools/check-arch.sh:92. The existing reason now carries the required dated PIN.

Verdict: CLEAN: the remaining finding is resolved, and this increment changes only comments.

Checked

Duplicates: 0 new items. The 15 listed dryer pairs concern previously reviewed Rust outside this increment.

Complexity: no functions changed; crapper's listed functions are outside this increment.

Silent failure: 0 changed sites; executable shell code is unchanged.

Tests: no tests added or changed, so no mutation check applies. bash -n passed; hardware gates were not run.

Gates: the Metal-bin exemption now has PIN(2026-10-22): and its reason. No gate logic or numeric bands changed.

Escape catalog: no C1–C4 pattern matches the changed comments. Both added lines remain shell comments.

Notes

The PR body still lacks model paths and full gate commands with output required by CONTRIBUTING.md's GPU evidence list.

Card check: needs-gpu. This pull request changes crates/gpu-gates/Cargo.toml, crates/gpu-gates/src/bin/gate_gpu_device.rs, crates/gpu-gates/src/record.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)

github-actions[bot]
github-actions Bot previously approved these changes Oct 23, 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.

Since the last review:

  • Architecture-check exemption: remains fixed at tools/check-arch.sh:92; the dated PIN and reason remain present.

Verdict: CLEAN: the rebase preserves the reviewed behavior and keeps the unsafe ratchet at the source counts.

Checked

Duplicates: 0 new items in the interdiff. The 15 dryer pairs concern unchanged, previously reviewed code.

Complexity: no function bodies changed in this interdiff; crapper's listed functions are outside its scope.

Silent failure: 0 new fallback sites. The resident-type lookup retains named errors for missing and unsupported weights.

Tests: no new or changed tests, so no mutation check applies. Shell syntax checks passed. Hardware gates were not run.

Gates: the rebased GPU unsafe pin matches 2,178 blocks, 261 functions and 10 impls counted at this head. Dated reasons remain present.

Rebase context: BY_NAME retains its visibility and five types; resident_type retains its body and crate-local callers. Unsupported resident forms remain errors.

Escape catalog: no C1–C4 pattern matches the interdiff.

Notes

The PR body still lacks model paths and full gate commands with output required by CONTRIBUTING.md's GPU evidence list.

Card check: needs-gpu. This pull request changes crates/gpu-gates/Cargo.toml, crates/gpu-gates/src/bin/gate_gpu_device.rs, crates/gpu-gates/src/record.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)

@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 Metal timing probe can block before submitting any work.

Must fix

1. Bound the trial count before allocating command buffers

crates/metal/src/bin/metal_matvec_time/mac.rs:136 --trials 63 is accepted and requests 65 uncommitted buffers including warmups [derived]. The queue uses newCommandQueue(), whose default capacity is 64. begin() calls commandBuffer(); the 65th request blocks, and the submit loop at line 164 is never reached. Each sample also needs a signal buffer. Bound the count so recording and signal buffers fit.
A named refusal now prevents hung measurement runs. Replace trials_of with:

fn trials_of(value: Option<&String>) -> Result<usize, String> {
    // Each sample needs a recording and a signal buffer on the default 64-slot queue.
    const MAX_TRIALS: usize = 64 / 2 - WARMUPS;
    match value.map(|v| (v, v.parse::<usize>())) {
        None => Err("--trials takes a value".to_string()),
        Some((_, Ok(n))) if (1..=MAX_TRIALS).contains(&n) => Ok(n),
        Some((value, _)) => Err(format!(
            "--trials takes a whole number in 1..={MAX_TRIALS}, not {value:?}"
        )),
    }
}

Non-blocking

⚠ Construct the embedding error lazily: crates/gpu/src/arch/qwen3moe/program.rs:203. ok_or constructs GpuError::shape even for a nonempty chain: one added String allocation per eager decode token [derived]. Removing this work now keeps it out of subsequent timing comparisons. Use:

            .ok_or_else(|| GpuError::shape(WHAT, "a chain of no layer"))?;

Checked

Validated the trial parser, queue creation, command-buffer allocation and submit order. Traced the eager decode walk to Program::embed and GpuError::shape, which converts the error detail into a String. The inline suggestion replaces an added line and preserves the error. Diagnostics lists time_shape as new at complexity 27. Validation was static; hardware gates were not run. No ledger lessons apply; escape patterns C1–C4 do not match these findings.

Notes

The PR gives card lines and commit hashes, but summarizes gate results without the model-file paths and complete gate command output required for GPU evidence.

Card check: needs-gpu. This pull request changes crates/gpu-gates/Cargo.toml, crates/gpu-gates/src/bin/gate_gpu_device.rs, crates/gpu-gates/src/record.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)

Comment thread crates/gpu/src/arch/qwen3moe/program.rs Outdated
dispatch::ffn(&lc, &lc.p.ffn, s, *m, out)?;
}
.first()
.ok_or(GpuError::shape(WHAT, "a chain of no layer"))?;

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.

Build this error lazily to avoid allocating its String on each successful eager decode step.

Suggested change
.ok_or(GpuError::shape(WHAT, "a chain of no layer"))?;
.ok_or_else(|| GpuError::shape(WHAT, "a chain of no layer"))?;

@midagedev

Copy link
Copy Markdown
Owner Author

Review fixes in dbb5d35: --trials is bounded to 64 / 2 - WARMUPS (refused by name past it), and the empty-chain error is built with ok_or_else.

Rebased onto main twice today. Evidence for the landing:

  • Fixture batch on the first rebase (box, both cards, --ledger): 240 items, 17 red. All 17 are main's: the same reds reproduce on an origin/main tree (78c3680) — stale recorded fixture budgets (glm5next family, solar2), gate-gpu-mxfp8 (resident_sel_f32 refusal), gate-ds41-load, gate-gpu-qwen38-serve, gate-fixture-budget — plus the known qwen35moe-leg@q35iq3s6 red. gate-serve went red once under load and is 3/3 green alone (crates/serve is untouched here).
  • The second rebase brings main commits that share no file with this branch except tools/unsafe-ratchet.txt (counts shifted by the branch's own +13/+1, -1). Box just check, check-unsafe, check-recipes, mac-lint, fmt, comments and arch are green on the new head.

@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: one proven duplicate in the new chain crate; no behavior failure path survived.

Must fix

1. The header shape check has two copies in the new chain crate

read.rs:106 (stack_ty) and site.rs:127 (file_site) both add the same 12 lines: find the tensor, read got_k and got_rows, compare with (rows, k), build the shape refusal. Only the word in the message differs ("stack" or "site"). The base had the same pair in placed.rs and site.rs; this PR moves both into one crate, so this is the cheapest point to give the fact one owner. A third reader of a header would make a third copy.
Fix: add one function to crates/chain/src/site.rs, use it in file_site and in stack_ty. It removes both 12-line bodies and adds one 12-line body, about 7 lines fewer with the doc. No test pins the words "the stack takes".

/// The header entry of `name`, a matrix of `rows` rows of `k` values: a missing tensor or
/// another shape is refused by name.
pub(crate) fn shaped<'a>(
    file: &'a Split,
    what: &'static str,
    name: &str,
    (rows, k): (usize, usize),
) -> Result<&'a gguf::TensorInfo, ChainError> {
    let (_, t) = file
        .find(name)
        .ok_or_else(|| ChainError::tensor(what, name, "in the file"))?;
    let got_k = t.dims.first().copied().unwrap_or(0);
    let got_rows: u64 = t.dims.iter().skip(1).product();
    if usize::try_from(got_k).ok() != Some(k) || usize::try_from(got_rows).ok() != Some(rows) {
        return Err(ChainError::shape(
            what,
            format!("{name} is {:?} in the file; it takes {rows} rows of {k}", t.dims),
        ));
    }
    Ok(t)
}

Then file_site starts with let t = shaped(file, what, name, (rows, k))?; and keeps its match SiteTy::of_ggml(...). stack_ty becomes Ok(shaped(file, what, name, (rows, k))?.ty).

Non-blocking

⚠ Misplaced doc text: dispatch.rs:642 and dispatch.rs:905. The old whole-half text was pasted under attn_in and route. attn_in's doc now says it also does the rope, the flash and the output projection. Keep each op's own sentence and move the half's description to the walk.

Checked

  • Duplicates: about 40 new items checked. Hit: item 1. Dryer pairs read: ChainError::shape/tensor against DeviceError/GpuError constructors (separate error types by design, device-free crate); the Buffer::window impls in gpu and metal (one impl per backend, each with its own SAFETY text); Window::cast and WindowMut::cast (a shared and an exclusive window type); the gate bins' main stubs. None is a finding.
  • Complexity: from_code and the conformance functions are new and even (match arms, clause tables). dispatch::route is the old ffn front split in two, with identical launches (canon-check identical in the PR body). Kernel bodies are read for correctness only.
  • Silent failure: 6 sites followed. unwrap_or(0) on dims.first() is compared with Some(k), and k > 0, so it refuses. The Q4_K kernel keeps all reads defined, raises the norm site and writes NaN. The rest are test-only.
  • Tests: sync_two_waiters protects the lock held through the poll. Mutant: release the lock before the poll. The second waiter then sees an empty list, returns Ok early, and at < opened turns red. Metal kernel clauses and mutants run only on a Mac and were not checked here.
  • Gates: pins moved are dated (check-arch.sh, recipes.py, ratchet, model-tax rows removed with the table moved to bloomery-device).
  • Escape catalog: no shell pipes or heredocs in the diff; none matched.
  • Performance: the walk is static generics over ChainOps with no allocation per op. The proof for the "move, split, rename" class (canon-check, identical PTX) is in the PR body.

Notes

  • The PR body names tips (e53cabebb, 1ddfc4661) that are not the head dbb5d35. Say which gates ran at the head, or that the commits since touch no gate's closure.
  • gate-gpu-qwen35moe-leg@q35iq3s6 and gate-ptx-spill are red on main as the body states. This review did not re-run them.

Card check: gpu-evidence. This pull request changes crates/gpu-gates/Cargo.toml, crates/gpu-gates/src/bin/gate_gpu_device.rs, crates/gpu-gates/src/record.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 23, 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 refusal gate hides encoded writes, and K-quant membership has two test owners.

Must fix

1. Let the refusal gate observe work encoded before an error

crates/metal/src/bin/gate_metal_qwen35moe_kernels/mac.rs:181 returns before submitting the recording when the launcher refuses. The side-effect assertion in clauses.rs:933 therefore cannot detect a dispatch encoded before that error.

A concrete mutant delays the x-length check at crates/metal/src/kernels/matvec.rs:135 until after dispatch. The short-x case still returns its expected error; its allocation contains all 512 input values, and the zero-writing dispatch is discarded. The “nothing written” assertion stays green. This is a proven gate defect with a mechanical fix. Correct the harness before more refusal clauses reuse it: submit before returning the encode result.

pub fn encode(
    &self,
    encode: impl FnOnce(&mut bloomery_metal::encode::ComputeEncoder<'_>) -> Result<(), DeviceError>,
) -> Result<(), String> {
    let mut recording = self.stream.begin().map_err(why)?;
    let result = {
        let mut encoder = recording.compute_encoder().map_err(why)?;
        let result = encode(&mut encoder);
        encoder.end();
        result
    };
    self.stream.submit(recording).map_err(why)?;
    result.map_err(why)
}

2. Keep one test owner for K-quant membership (R14)

crates/chain/src/site.rs:190 pins exactly the four K-quant members. crates/gpu/src/site.rs:1587 checks the same membership for every SiteTy::ALL entry against its expected table. GPU re-exports the chain's SiteTy, so both assertions test the same implementation.

Two pins require coordinated edits when membership changes. Keep the pin in the device-free crate and remove the redundant GPU assertion, retaining the dated reason required for removing a gate assertion:

--- a/crates/gpu/src/site.rs
+++ b/crates/gpu/src/site.rs
@@ -1584,5 +1584,5 @@
             assert_eq!(s.ggml(), ty);
             assert_eq!(s.to_string(), label);
             assert_eq!(gemm_weight(s), grouped);
-            assert_eq!(s.kquant(), grouped.is_some());
+            // PIN(2026-10-23): K-quant membership is pinned in chain::site.
             assert_eq!(kgemv_order(s).is_some(), s.reads() == Form::Q8x128);

Non-blocking

⚠ Dispatch timing evidence: crates/gpu/src/arch/qwen3moe/program.rs:154 changes host orchestration. The PR body defers its same-lease A/B until after landing. Attach the base/head A/B required by AGENTS.md “Measuring” for dispatch-path changes and R20 before merge. Identical PTX and node counts do not supply that timing evidence.

Checked

Duplicates: both membership tests and the SiteTy re-export confirmed.
Complexity: the host walk now delegates layer stages through ChainOps.
Silent failure: encode errors bypass submission; readback waits only for submitted work.
Tests: the short-x mutant was traced statically, not executed.
Gates: the refusal assertion's missing observation is finding 1; the duplicate pin is finding 2.
Escape catalog: C1–C4 do not match the retained findings. No ledger lessons are in force.

Notes

CUDA and Metal gates were not run during this review. The PR body supplies gate summaries but omits the full selected just gate-* commands and their output requested by CONTRIBUTING.md.

Card check: needs-gpu. This pull request changes crates/gpu-gates/Cargo.toml, crates/gpu-gates/src/bin/gate_gpu_device.rs, crates/gpu-gates/src/record.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)

@github-actions github-actions Bot added needs-gpu Changes code a card must check, and carries no gate run on a card and removed gpu-evidence Verified on the author's card: the pull request carries the gate run and its output labels Oct 23, 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 Metal mat-vec launcher accepts widths that overflow kernel arithmetic.

Must fix

1. Refuse column counts beyond signed 32-bit indexing

Kind A. crates/metal/src/kernels/matvec.rs:128 derives the block count without bounding columns; the later conversion checks only that the block count fits u32.

For Q6_K with rows=1 and cols=2147483904, correctly sized windows pass validation. The loop reaches i=8388608, where signed i * QK_K overflows at crates/metal/kernels/matvec_q6k.metal:81, invalidating the input address [derived].

For Q4_K norm with rows=1 and cols=4294967552, the unsigned norm divisor wraps to 256 at crates/metal/kernels/matvec_q4k.metal:157. Finite inputs can therefore produce an incorrect scale without a fault [derived].

The Q6_K buffers fit the documented Mac limits. The Q4_K case also fits when the read-only gain and input windows share one buffer: its largest buffer is 17,179,870,208 bytes and its weights, input and output total 19,595,789,460 bytes [derived], below the buffer and working-set limits in docs/contrib/mac.md:44.

One bound at the launch owner protects both families before callers depend on this API. Replace line 128 with:

    i32::try_from(p.cols).map_err(|_| refuse(format!("{} columns exceed i32::MAX", p.cols)))?;
    let nblocks = p.cols / BLOCK_VALUES;

Checked

Bounds: traced launch validation, buffer allocation, binding and dispatch through both kernels; no intervening column bound prevents either case.
Tests: matvec_refusals covers window lengths, alignment, block divisibility and empty shapes, but omits overflowing widths. Metal gates were not run here.
Escape catalog: C1–C4 do not apply to this finding. No ledger lessons are in force.

Notes

The PR body omits the model-file path for its reported real-tier gates.

Card check: needs-gpu. This pull request changes crates/gpu-gates/Cargo.toml, crates/gpu-gates/src/bin/gate_gpu_device.rs, crates/gpu-gates/src/record.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)

p.cols
)));
}
let nblocks = p.cols / BLOCK_VALUES;

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.

Bound columns before deriving blocks: accepted widths overflow Q6_K's signed column offsets and Q4_K norm's 32-bit count.

Suggested change
let nblocks = p.cols / BLOCK_VALUES;
i32::try_from(p.cols).map_err(|_| refuse(format!("{} columns exceed i32::MAX", p.cols)))?;
let nblocks = p.cols / BLOCK_VALUES;

@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 Metal timing probe can spin forever after a device failure.

Must fix

1. Bound the timing probe's event poll

crates/metal/src/bin/metal_matvec_time/mac.rs:170: a device failure that prevents the final signal command buffer from executing leaves the event counter below its target. MetalEvent::done then keeps returning Ok(false). This loop spins forever and never reaches stream.sync() at line 175 to report the command-buffer failure.
Bound the poll so a failed probe terminates with a diagnostic. Replace the event loop with:

    for event in &events {
        let deadline = Instant::now() + std::time::Duration::from_secs(60);
        while !event.done().map_err(why)? {
            if Instant::now() >= deadline {
                return Err("timing event was not signalled within 60 s".to_string());
            }
            std::hint::spin_loop();
        }
        ends.push(Instant::now());
    }

Checked

Validation confirmed that the poll is added by this diff, record() submits a separate signal buffer, and the stream's bounded error check follows the poll. No enclosing probe timeout was found. The retained finding matches no exclusion or escape-catalog pattern; no ledger lessons are in force. No builds or hardware gates were run during validation.

Notes

GPU evidence is incomplete. The PR supplies card lines and batch summaries, but omits the model file paths and exact gate commands with output tied to the compared commits.

Card check: needs-gpu. This pull request changes crates/gpu-gates/Cargo.toml, crates/gpu-gates/src/bin/gate_gpu_device.rs, crates/gpu-gates/src/record.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)

midagedev and others added 3 commits October 23, 2026 18:03
…o f64 with atomic twins, spans and casts, device read/write/copy, ordered shared pages, a device's stream, a typed error), one fault table, and one set of contract clauses for every backend

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… a re-export of the device crate's

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…es on a card; its class and owner rows, the narrow self-test's carrier pair and the unsafe ratchet

Co-Authored-By: Claude Opus 5.5 <[email protected]>
midagedev and others added 18 commits October 23, 2026 18:03
…load, the residual epilogue and the embed, with their launches

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nsors (f64 oracle, derived band, --mutant), its run in lab-metal, and the mat-vec timer

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The fault word's layout has named constants (LAYER_SHIFT, CODE_MASK,
LAYER_MAX) with const asserts, and a layer past the word's bits is refused
by name instead of wrapping. The step-order tables move from the contract to
the CUDA engine, which owns them; the contract keeps StepOrder. split_at
reuses check_window, the Elem impls are one macro, HostPages gains copy_from,
the CUDA side has one own_stream and one read_words for both DtoH paths, and
a test holds the range rules' success paths to no allocation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The kernels' gate uses bloomery_device::conformance's verdicts. MetalRaw::base
goes (no sub-allocation exists); alignment reads the window's byte offset.
row_tail_reads runs the row-tail launches in a child under Metal's shader
validation, with the tail_read mutant as its positive control, and lab-metal
runs --mutants-all so each mutant must turn its own clause red. The sentinel
is a quiet NaN, the norm band is re-derived, block_shape holds the launch's
block arithmetic to gguf's rows, and the generated header takes the fault
word's shift from the one table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…shrinks

The register/require, line_under and reader tests used gate kinds only as
samples; they move into bloomery-record with kinds of their own, so
gate-record runs them. Prints, Needs, require_in, register_in and line_under
become private.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…alk over ChainOps as the one owner of its layer order

bloomery-chain holds what every backend reads of the qwen3moe family: the
layer plans, the file's site types (SiteTy, derived from the kernel table),
the card leg and FFN read, and the walk. ChainOps has the ten ops a backend
enqueues (embed, attn_in/core/out, delta_in/core/out, route, experts, head);
each op picks its gemv or wide arm from the unit's rows, and its output
buffer from LayerCtx::last and the backend's tail. The CUDA Program and
Body35's slot pass implement the ops; the composed orders
(dispatch::{layer, mixer, ffn, attention}, delta::delta, Program::layer/end,
Tapping) are deleted and their callers run the walk. The walk's doc names
what it does not cover: the placed FFN half around the host leg, the placed
common card leg, Body38, the whole-card GEMM prefill. CUDA facts stay in
gpu: the gemv arm predicates, Order/kgemv_order, of_resident and BY_NAME,
the GEMM slot cap. UBATCH has one owner, model's UBATCH_PLANNED. Every PTX
entry is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nd hf-arch-check reading the chain's tables

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…/step_order.rs)

The per-architecture fault-site tables and their map left fault.rs, which
now names no model; crates/gpu/src/arch/step_order.rs is a registry file,
and fault.rs's model-tax rows go.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… the fixture reader is the gate's

bin/shared/oracle.rs holds the band, the f64 reference and the check; the
kernels' gate's fixture.rs opens the qwen35moe trunk. The timer no longer
names the gate's directory.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…vice pages' test threads

crates/metal/src/bin/ holds the Mac's gate bins, so the blk.* literals rule
skips it as it skips crates/gpu-gates/src/bin/. spawn-allow lists the two
test threads of crates/device/src/pages.rs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…the queue; gpu: the empty-chain error is built lazily

Every timed buffer is encoded before any commits, each with a signal buffer beside it, so more
than 64 / 2 - WARMUPS trials blocked in begin() on the default 64-buffer queue: now refused by
name. Program::embed built its shape error on every token; ok_or_else builds it only on refusal.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TG5hgJqn38MRwLefZHyHCJ
`shaped` reads a tensor's header entry and refuses a missing tensor or another
shape by name; `file_site` and `stack_ty` both go through it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TG5hgJqn38MRwLefZHyHCJ
…ore returning the refusal

The harness returned before the submit when the launcher refused, so the
refusal clause's "nothing written" read could not see a dispatch encoded
before the error. FAIL-first: a mutant that checks x's length after the
dispatch now reddens matvec_refusals ("a refused launch wrote").

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TG5hgJqn38MRwLefZHyHCJ
Removed 2026-10-23: the table test's `kquant()` assertion. `SiteTy` is the
chain crate's, re-exported, and chain::site's the_kquant_sites_are_the_four_kquants
pins the same membership on the same implementation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TG5hgJqn38MRwLefZHyHCJ
…signed 32-bit index

The kernels index the input as a block index times its values in signed 32-bit
arithmetic and divide the norm's sum by the column count in 32 bits; a width
past i32::MAX with correctly sized windows passed the launch's checks. The
refusal clause gains the case; FAIL-first: without the bound it is refused by
the weights window instead, not by name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TG5hgJqn38MRwLefZHyHCJ
…r the stream's sync bound

A device failure that stops a buffer's signal left the poll spinning
forever, before the stream.sync that reports the failure. Past 60 s the loop
syncs the stream (a failed buffer's error first) and refuses by name.

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

Copy link
Copy Markdown
Owner Author

Same-lease A/B on the RTX A6000. just depth-gpu-qwen3moe, 6 rounds, interleaved, rotated arm order. Base is b75c065 (origin/main). Head is 844bed9. Card: docs/cards/macport-q3moe-noninf.card (noninf, margin 1.5 %).

depth base tok/s ours tok/s effect (paired, 95 % lower bound)
6 210.58 210.08 −0.235 % (−0.644 %)
4096 176.41 176.50 +0.051 % (−0.121 %)

card.py verdict: pass at both depths. Both effects are inside the predicted band −0.3..+0.3. Prefill P=4096: 9169 vs 9151 tok/s. Every row is tagged cpu-busy: another track's rustc held one core during the lease, the same for both arms.

@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 CUDA write error path can release the host-source borrow before its asynchronous copy finishes.

Must fix

1. Wait for the copy without fallible event setup

crates/gpu/src/device.rs:473 Kind A. Pass a pinned host slice to Device::write: line 468 queues the copy, then record_event(None) can fail during event setup. Its ? returns before line 474 waits, releasing the source borrow while DMA can still read it. A caller can then reuse the source, causing a CPU/DMA race. The wait at line 460 precedes this copy and cannot protect it.

Fix the public borrow boundary before more callers depend on it. Synchronize the stream directly, removing the fallible event setup after enqueue:

fn write<T: Elem>(
    &self,
    s: &GpuStream,
    to: WindowMut<'_, T, Gpu>,
    from: &[T],
) -> Result<(), DeviceError> {
    check_len("write", from.len(), to.len())?;
    self.own_stream(&s.0)?;
    let (ptr, bytes) = self.address(*to.raw(), to.byte_range()?)?;
    host::await_done("Device::write", || s.0.query())?;
    self.ctx.bind_to_thread().map_err(cuda)?;
    // SAFETY: the destination covers the checked window in this context;
    // from covers bytes bytes and remains borrowed through the stream wait.
    // The context is current on this thread.
    let rc = unsafe {
        sys::cuMemcpyHtoDAsync_v2(
            ptr,
            from.as_ptr().cast(),
            bytes,
            s.0.cu_stream(),
        )
    };
    graph::cu(rc, "cuMemcpyHtoDAsync_v2 (Device::write)")?;
    s.0.synchronize().map_err(cuda)
}

Checked

Confirmed the enqueue, early return, source-borrow contract, and pinned shared-memory access. The existing upload ring drains its stream when event recording fails. The inline replacement covers added lines 473–474 and uses an existing stream API. No escape-catalog pattern or ledger lesson applies.

Notes

Validation was static; no builds or GPU gates were run. The PR body lacks complete gate commands/output and model-file identity for GPU evidence.

Card check: needs-gpu. This pull request changes crates/gpu-gates/Cargo.toml, crates/gpu-gates/src/bin/gate_gpu_device.rs, crates/gpu-gates/src/record.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)

Comment thread crates/gpu/src/device.rs Outdated
Comment on lines +473 to +474
let copied = s.0.record_event(None).map_err(cuda)?;
copied.synchronize().map_err(cuda)

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.

Event setup can fail after the copy starts, returning before DMA finishes reading the borrowed source. Synchronize the stream directly.

Suggested change
let copied = s.0.record_event(None).map_err(cuda)?;
copied.synchronize().map_err(cuda)
s.0.synchronize().map_err(cuda)

…step between the enqueue and the wait

An event record that failed after the async copy was queued returned before the wait, and released `from` while the
copy could still read it. The stream's own synchronize is now the only step after the enqueue.

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

@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 merge-blocking defect was found in the reviewed changes.

Non-blocking

⚠ Establish the rsqrt error bound: crates/metal/src/bin/shared/oracle.rs:73.
The norm band assumes a maximum error of 2 ulp; its derivation marks that premise unverified.
Cite Metal's precise-mode guarantee or provide a calibration on the supported Mac before using this term to explain a gate failure.

Checked

Duplicates: 704 added or moved Rust/Python declarations searched against both trees; 15 reported dryer pairs read. They are distinct contracts, backend adapters or short constructors whose extraction adds elements.
Complexity: conformance::{copies, window_range, event_wait_holds, fault_clause, window_binding}, the Metal kernel gate's {main, Harness::matvec, norm_on_load, embed}, time_shape and kernels::embed are new check/launch pipelines. FaultSite::from_code is an exhaustive map. dispatch::route and Slots35::{attn_core, delta_core} are extracted stages.
Silent failure: 18 added default/error-discard sites followed. Invalid shapes and disconnected waiter results reach named failures; the other defaults select explicit modes, diagnostic text or test expectations.
Tests: static mutation checks covered range/cast bounds, fault decoding, walk order, record refusals and allocation checks. The ten Metal mutants still target their production instructions; fault, numeric, residual and tail assertions reject those defects.
Gates: moved tests retain their contracts; the numerical band and changed exemptions/ratchets carry dated PINs.
Adversarial checks: invalid norm inputs, odd row tails, concurrent stream waiters, slot-pass bounds and the MTP layer's nonzero index have guards or dedicated assertions. The CUDA walk preserves the launch sequence; no added per-token allocation, copy or synchronization was found.
Escape catalog: no changed code matches C1–C4.

Notes

Static review; builds and hardware gates were not rerun. The PR's GPU summaries omit the model file and full gate command/output transcripts, so GPU evidence is incomplete.

Card check: needs-gpu. This pull request changes crates/gpu-gates/Cargo.toml, crates/gpu-gates/src/bin/gate_gpu_device.rs, crates/gpu-gates/src/record.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)

@midagedev
midagedev merged commit 6c5cc34 into main Oct 23, 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 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.

1 participant