Skip to content

metal: run a prompt ahead with known ids, skip the head on inner rows - #762

Merged
midagedev merged 3 commits into
mainfrom
mac-ahead
Oct 24, 2026
Merged

midagedev merged 3 commits into
mainfrom
mac-ahead

Conversation

@midagedev

Copy link
Copy Markdown
Owner

What and why

On Metal a prompt stepped every id host-fed: commit, wait, then the head. The prompt's ids are known, so each id but the last now commits the next id before it waits, and a row whose pick nobody reads encodes no head. Part of #593.

Release notes: Changed — Metal: a prompt runs about 13 % faster per id.

Code shape

  • No second copy. The ahead step reuses the chain step's record slots, keep rule and discard rule; the step-time clock reuses GpuStamps.
  • Model code holds only architecture facts.
  • Dead code is gone.
  • No silent failure. A token ahead whose id the next call does not name is counted and discarded, as the chain's is.
  • Comments state what is true now.
  • No relaxed gate. tools/unsafe-ratchet.txt: metal 22 -> 25 blocks, new code (libSystem's host clock), with its PIN(2026-10-24) line.
  • cargo fmt and cargo clippy are clean; the lint count did not go up.

Duplication found or removed (path:line), or "none": none

What I ran

On an M1 Pro (the Metal gates):

just lab-metal       gate_metal_device: PASS; gate_metal_qwen35moe_kernels: PASS; --mutants-all: PASS (63 mutants)
just lab-metal-e2e   clause h_prompt: PASS; gate_metal_qwen35moe_e2e: PASS; --mutants-all: PASS (7 mutants)
just mac-metal-lint  0 warnings
tools/check-comments.sh ok; tools/check-unsafe.sh ok

Hardware (if the change is for a machine)

M4 Pro 48 GB, Qwen3.6-35B-A3B MLX 4-bit split, generate_metal, development-loop numbers (no timing runner on a Mac). Prompt seconds against prompt ids give the per-id cost as the slope:

1 id 205 ids 621 ids per id (slope)
before 2.585 s 4.490 s 8.87–9.11 s ≈ 10.1 ms
after 2.525 s 4.189 s 7.88–8.05 s ≈ 8.8 ms

Decode is unchanged (102.1–105.2 tok/s). The ~2.5 s at one id is a first-step cost after open; it is not in this change.

This change was written with AI help (GLM-5.3 for the code, Claude for review).

🤖 Generated with Claude Code

https://claude.ai/code/session_01Q5zTV27LbaVZFTjnkdmTjJ

The prompt stepped every id host-fed: commit, wait, head. Every id but the
last now steps StepMode::Ahead, which commits the next known id before the
current token is waited, and encodes no head for a row whose pick nobody
reads. The last row steps host-fed and runs the head. Checkpoint marks
take their copies as before, after the token ahead is waited out.

generate_metal --step-times [N] prints the host encode, commit to GPU
start, GPU and wake times per step mode, from the command buffers' GPU
stamps on the host clock.

The e2e gate's h_prompt clause holds the ahead prompt to the host-fed
prompt bit for bit (position, pick, logits row, delta lanes, KV rows, 8
greedy picks), with and without a mark crossed, and pins the step's
group and dispatch counts; three mutants turn it red.

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

@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 timing probe misreports phases, and option parsing and refusal handling change CLI behavior.

Must fix

1. Use the GPU timestamps' host clock (kind A)

crates/metal/src/arch/qwen3moe/session.rs:691 A delay D from probe completion to host_secs() shifts every start by +D and every wake by −D. A probe delay longer than a later wake produces a negative wake duration.
Fix this before tuning against incorrect phases. Use mach_absolute_time in host_secs (the GPU timestamps' timebase), remove the probe, and update the clock comments. Replace its FFI declaration and final expression respectively:

fn mach_absolute_time() -> u64;
// SAFETY: libSystem's argument-free clock read writes nothing.
(unsafe { mach_absolute_time() } as f64) * per_tick
pub fn start_step_clock(&mut self) -> Result<(), SessionError> {
    self.clock = Some(StepClock::new(0.0));
    Ok(())
}

2. Skip option values when reading optional counts (kind A; R14)

crates/metal/src/bin/generate_metal.rs:252 scans the prompt text as an option: --prompt '--step-times' -n 1 enables 32 timing steps per mode without a timing option. It also copies crates/metal/src/bin/generate_metal.rs:219.
One parser fixes the bug and removes the duplicate scan. Replace both scans with let profile_n = count_flag("--profile"); and let step_times = count_flag("--step-times");:

fn count_flag(name: &str) -> Option<usize> {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let mut out = None;
    let mut i = 0;
    while i < args.len() {
        if VALUE_FLAGS.contains(&args[i].as_str()) {
            i += 2;
            continue;
        }
        if args[i] == name {
            out = Some(args.get(i + 1)
                .and_then(|v| v.parse::<usize>().ok())
                .unwrap_or(PROFILE_DEFAULT));
        }
        i += 1;
    }
    out
}

3. Return failure when the timing run cannot start (kind A)

crates/metal/src/bin/generate_metal.rs:488 --tokens 0 -n 1 --ctx 1 --step-times 1 fills the cache, prints “refused”, and exits successfully without timing a token.
Return an error so callers detect the missing measurement. Replace this line:

return Err("step_times: fewer than three context rows remain".into());

4. Reuse the gate's prompt and greedy readers (kind B; R14)

crates/metal/src/bin/gate_metal_qwen35moe_e2e/ahead.rs:140 and ahead at line 152 repeat crates/metal/src/bin/gate_metal_qwen35moe_e2e/keep.rs:59; after at line 86 repeats keep.rs:66's greedy loop.
Reuse these owners to remove the copies. Make prompt_bits and greedy pub(super). Replace the two prompt matches and the greedy loop respectively:

let (logits, pick) = super::keep::prompt_bits(s, ids)?;
let picks = super::keep::greedy(s, pick, GREEDY)?;

5. Keep one pending-token removal (kind B; R14)

crates/metal/src/arch/qwen3moe/session.rs:327 repeats the signal lookup and removal in crates/metal/src/arch/qwen3moe/session.rs:319.
Reuse the existing owner now so registry changes have one implementation:

fn dropped(&self, value: u64) {
    drop(self.take(value));
}

6. Keep raw GPU timestamps internal (kind B; R13)

crates/metal/src/stream.rs:208 has only two callers, both in session.rs; GpuTimes also gains an unused root re-export.
Keep this API internal before callers depend on it. Use pub(crate) for GpuTimes and times, and replace the root export:

pub use stream::{GpuInterval, GpuStamps, HostEvent, MetalEvent, MetalStream, Recording};

Non-blocking

⚠ Timing evidence: ops.rs:552 removes one head dispatch per inner prompt ID; the prompt also changes host/GPU overlap. Attach the launch-count prediction, both hashes, exact model file and reproducible A/B commands with output on the contributor's Mac. The body lacks these.

Checked

Duplicates: scans, gate readers and registry removals confirmed; dryer reported 0 pairs.
Complexity: h_prompt is new; step/parse/generate add branches; gate main adds a clause arm.
Silent failure: traced option values and timing refusal through the CLI exit code.
Tests: source assertions reject restored inner heads, incorrect final-row output and retained checkpoint tokens.
Gates: unsafe count 22→25 has a dated PIN and named operations. Escape catalog: no matches.

Notes

Metal gates were not run here. Validation used source review; Mac runs are author-reported.

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

Comment thread crates/metal/src/bin/generate_metal.rs Outdated
rows,
s.pos()
);
return Ok(());

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 timing refusal must return an error so the CLI exits unsuccessfully when no measurement ran.

Suggested change
return Ok(());
return Err("step_times: fewer than three context rows remain".into());

… parser

A command buffer's GPUStartTime and GPUEndTime are seconds on
mach_absolute_time, so host_secs reads that clock and the offset probe
is gone: a probe delay shifted every start and wake. generate_metal reads
its bare and count flags through one walk that skips value flags' values,
so a prompt text is never read as a flag, and a step-times run that
cannot time a token ends in an error. ahead.rs uses keep.rs's prompt and
greedy readers.

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

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

  • Host clock and offset probe: fixed.
  • Optional-count parsing: fixed.
  • Timing refusal exit status: fixed.
  • Gate prompt and greedy readers: fixed.

Verdict: MUST_FIX: value parsing rejects valid prompt text, and profiling refusal still returns success.

Must fix

1. Consume option values in the value reader (kind A)

crates/metal/src/bin/generate_metal.rs:123 scans values as flags. --prompt '--ctx' -n 1 reads -n as the context value and exits 2; --prompt '--tokens' -n 1 reports two prompt sources. The new flag walk leaves this reader unchanged.
Fix the remaining reader so arbitrary prompt text survives parsing. Replace it:

fn flags(name: &str) -> Result<Vec<String>, String> {
    let mut args = std::env::args().skip(1);
    let mut out = Vec::new();
    while let Some(a) = args.next() {
        if !VALUE_FLAGS.contains(&a.as_str()) {
            continue;
        }
        let value = args.next()
            .ok_or_else(|| format!("{a} needs a value"))?;
        if a == name {
            out.push(value);
        }
    }
    Ok(out)
}

2. Return failure when profiling cannot start (kind A)

crates/metal/src/bin/generate_metal.rs:355 returns Ok(()) when no cache rows remain. On a Mac with a valid model, --tokens 0 -n 1 --ctx 1 --profile 1 consumes the only row during the prompt, prints “refused”, and exits 0 without profiling a token. generate propagates this success through run.
Fix this sibling refusal so callers detect missing measurements. Replace the zero-row branch:

if rows == 0 {
    return Err(format!(
        "prof: no row past position {}; give --ctx more rows",
        s.pos()
    ));
}

Checked

Duplicates: dryer reported 0 candidate pairs; gate readers now reuse existing owners.

Complexity: diagnostics report h_prompt at 16, step 17→23, generate 14→17 and gate main 49→50; this growth predates the increment.

Silent failure: value parsing and profiling refusal were traced to CLI exit codes 2 and 0 respectively.

Tests: helper reuse retains the gate comparisons. Static mutation check: restoring the inner head at ops.rs:552 violates the counts checked by count_is.

Gates: no pins moved in this increment. Escape catalog: no patterns matched.

Notes

Validation used source review. Metal gates require a Mac and were not run here; gate runs in the PR body are author-reported.

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

Filed outside this PR: #764

flags() walked every argument, so a prompt text such as `--ctx` was read
as that flag. It now takes the next argument of each value flag as its
value, as flag_words() does. A profile run with no cache row left ends in
an error, as a step-times run does.

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

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

Verdict: CLEAN: both earlier findings are fixed, and no defect remains in the increment.

Checked

Duplicates: 0 new definitions; dryer reports 0 candidate pairs.

Complexity: crapper lists h_prompt 16, Session::step 17→23, generate 14→17 and gate main 49→50 from earlier changes. This increment adds one value-skipping guard in flags.

Silent failure: 2 paths followed. Missing option values reach exit status 2; a full cache during profiling reaches exit status 1.

Tests: no tests changed, so no test mutation applies. Source checks cover flag-like prompt values, trailing value flags, repeated values and the full-cache refusal.

Gates: no pins or tests moved. Escape catalog: no patterns matched.

Notes

Validation used source review. Metal gates require macOS and were not run here. Reported Mac runs lack the complete hardware and commit evidence required for gpu-evidence.

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

@midagedev
midagedev merged commit 7761004 into main Oct 24, 2026
7 checks passed
@midagedev
midagedev deleted the mac-ahead branch October 24, 2026 09:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant