Skip to content

metal: Q8_0 and Q5_K owners; the census's free bytes are the host's room - #834

Merged
midagedev merged 5 commits into
mainfrom
mac-mtrain
Oct 26, 2026
Merged

midagedev merged 5 commits into
mainfrom
mac-mtrain

Conversation

@midagedev

Copy link
Copy Markdown
Owner

Two Metal pieces toward more models on a Mac.

Q8_0 and Q5_K owners. These are the quant types Unsloth's UD files use for the embedding, the head and some routed gate/up stacks. Every body (mat-vec, embed, head, experts, GEMM, tensor GEMM) is instantiated with them. 30 new clauses and 30 new mutants. Nothing calls them from the session yet; the wiring is a later change. A4's fold band counts A4's own groups now (G(51), was G(45)), with a dated PIN and the derivation.

Census host room. On a Mac the device's free bytes are now min(working set left, host available), so a load does not count on memory other processes hold. The gates that ask what this process allocated read MetalDevice::allocated_bytes() instead of total − free. A failed host read is a named error.

Evidence:

  • On an M1 Pro (source path): clippy -D warnings for both feature sets, 43 lib tests, just lab-metal PASS (155 mutants, each red on its clause).
  • just metal-compare origin/main: added 66, removed 0, changed 9, same 106. Decode trace equal to depth 600, ids differ 0. The 9 changed pipelines are embed_a4 and the gemm_routed_* entries: the embed kernel became one template over the quant, and the Q4_K scale unpack is one helper. Their kernel clauses pass.
  • The fixture-tier landing batch on the box (the Cargo.lock change selects every gate) is running; the result follows in a comment.
  • Not run: the Metal e2e gate. It is barred on the maintainers' Macs until a kernel panic it triggered on macOS 27.0 is isolated.

AI use: written and checked with Claude Code.

🤖 Generated with Claude Code

midagedev and others added 3 commits October 26, 2026 19:36
…heir clauses and mutants

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eft, host available); gates read this process's allocation by allocated_bytes

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

@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 census change corrupts the plan's allocation report, and two shared rules remain duplicated.

Must fix

1. Update the plan's allocation reader (kind A)

crates/metal/src/census.rs:43 changes the meaning of free bytes, but crates/metal/src/arch/qwen3moe/plan.rs:133 still subtracts them from total. With a 24 GiB working set, zero process allocations and 9 GiB host availability, generate_metal --plan reports 15 GiB under allocated_bytes [derived]. Other processes' memory becomes this process's allocation.
Cost: fix the remaining consumer while changing this accounting contract.
Replace device_room with:

pub fn device_room() -> Result<DeviceRoom, String> {
    let default = MTLCreateSystemDefaultDevice()
        .ok_or_else(|| "this machine has no Metal device".to_owned())?;
    let id = default.registryID().to_le_bytes();
    let infos = MetalCensus::census().map_err(|e| e.to_string())?;
    let info = infos
        .into_iter()
        .find(|i| i.uuid[..8] == id)
        .ok_or_else(|| "the default device is not in the driver's device list".to_owned())?;
    Ok(DeviceRoom {
        name: info.name,
        recommended: info.total_bytes,
        allocated: MetalCensus::allocated_of(&default).map_err(|e| e.to_string())?,
    })
}

2. Make the scale unpack helper serve Q4_K too (kind B)

crates/metal/kernels/quant.metal:814 duplicates the packing rule still embedded at crates/metal/kernels/quant.metal:213, and again in Q4K::partial_head and Q4K::dequant16 (R14). Q4_K and Q5_K share this exact scale layout.
Cost: use the new owner before another format extends these independent copies.
Move the existing k4_scale_words definition before struct Q4K. In each of those three Q4_K methods, remove the three kmask declarations and replace the four sc16 assignments with:

k4_scale_words(sc, sc16);

This removes repeated masks and assignments without adding an owner.

3. Reuse the shared synthetic matrix builder (kind B)

crates/metal/src/bin/metal_matvec_time/mac.rs:323 extends the probe's copy of crates/metal/src/bin/shared/synthetic.rs:46 (R14). Both own random block filling and scale placement; this change already gives their Q5_K scales different ranges.
Cost: one existing owner prevents the probe and gates from drifting further.
Delete the probe's entire local matrix function and put this in its place:

#[path = "../shared/synthetic.rs"]
mod synthetic;
use synthetic::matrix;

Remove the shared module's introductory statement that the probe holds its own copy. Existing quant inputs retain their construction; Q5_K uses the shared builder's finite scale range.

Checked

Duplicates: both reported shared-rule copies confirmed. All five dryer pairs read: distinct quant labels or pipeline fields.
Complexity: pair_faults (22) combines id and norm scenarios. with_geometry (28→38) adds pipeline initialization. The remaining diagnostic entries add quant arms or an accounting check.
Silent failure: a full working set reports zero room; host-read errors propagate through free_of.
Tests: census assertions cover both memory limits, a full working set and host-read failure. Removing the host minimum, working-set subtraction or error propagation defeats these assertions. Metal execution was not run.
Gates: A4's fold band moves G(45)→G(51) with a dated PIN and the corrected block-count derivation.
Escape catalog: no matching patterns. No new unsafe blocks.

Notes

The PR reports M1 Pro runs but omits raw lab/compare output and both commit hashes. Hardware results were not independently verified.

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

…his process's allocation, not the census's room

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@midagedev

Copy link
Copy Markdown
Owner Author

Review fixes in 030b02a:

  • --plan's device_room reads this process's allocation by MetalCensus::allocated_of, not total − free.
  • Q4_K's three scale unpacks call k4_scale_words; the helper sits before struct Q4K. My earlier body said this was already one helper. That was wrong.

Evidence:

  • M1 Pro: clippy -D warnings for both feature sets, 43 lib tests, just lab-metal PASS (155 mutants).
  • just metal-compare origin/main: added 66, removed 0, changed 38, same 77. The 38 are the Q4_K-reading pipelines (the helper's text moved into them) plus the earlier 9. Decode trace equal at depth ~0 and 600, ids differ 0.
  • Box fixture-tier landing batch on 64b4b00: total 261, red 0. The fix touches only crates/metal; just affected selects 0 gates for it.

@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 earlier must-fix is still open: the probe keeps its own copy of the synthetic matrix builder.

Since the last review:

  • Must fix 1 (plan allocation reader): fixed. plan.rs:133 now reads MetalCensus::allocated_of, and an error is returned, not defaulted.
  • Must fix 2 (scale unpack helper): fixed. quant.metal:116 is defined before Q4K, and all three Q4_K methods plus both Q5_K sites call it. No sc16[2] = copy remains.
  • Must fix 3 (probe copy of the matrix builder): still open, see below.

Must fix

1. Reuse the shared synthetic matrix builder (kind B)

metal_matvec_time/mac.rs:302 is a copy of synthetic.rs:17 (R14). Both own random block filling and scale placement. This PR already made them differ: the shared one gives Q5_K an f16 range of [0.0001, 0.0008], the probe's copy keeps [0.0005, 0.004]. The shared file's header (synthetic.rs:4) still says the probe holds its own copy.
Cost: metal_gemm_time and the gate already share the builder. Fixing it now removes about 35 lines and stops a third range from drifting.
Fix: delete the probe's whole local matrix function (lines 298 to 338, with its doc comment). After the mod oracle; item at line 101, add:

#[path = "../shared/synthetic.rs"]
mod synthetic;
use synthetic::matrix;

In synthetic.rs, replace lines 4 and 5 with:

//! finiteness checks take them.

Every other quant arm in the shared builder is the same as the probe's. Only the Q5_K scale range changes, and the probe has no gate on it.

Checked

Duplicates: 2 new items checked (k4_scale_words callers, allocated_of caller); the probe matrix copy is the one hit. Dryer pairs: unchanged from the last review, not re-read in these commits.
Complexity: no changed function in these commits is on the crapper list; the helper extraction lowers Q4_K body size.
Silent failure: 1 site followed (allocated_of error in device_room); it maps to Err(String), and the plan prints the error.
Tests: no test changed in these commits. Metal execution was not run here.
Gates: none moved in these commits.
Escape catalog: no matching patterns. No new unsafe blocks.

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

…c builder, not its own copy

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@midagedev

Copy link
Copy Markdown
Owner Author

Review fix in 43756f0: metal_matvec_time builds its matrices with the shared synthetic::matrix. Its local copy is gone, so the probe's Q5_K scale range is now the shared [0.0001, 0.0008]. M1 Pro: clippy -D warnings for both feature sets, just lab-metal PASS (155 mutants), metal_matvec_time builds. The probe has no gate; just affected selects 0 box gates for this change.

@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: the last open must-fix is fixed, and the new commit adds no failure path.

Since the last review:

  • Must fix 1 (probe copy of the matrix builder): fixed. mac.rs:103 now includes shared/synthetic.rs and uses its matrix. The local copy is deleted. The header of synthetic.rs:1 no longer says the probe holds a copy.
  • Earlier must-fix 1 and 2 (plan allocation reader, scale unpack helper): stay fixed; these commits do not touch them.

Checked

Duplicates: 0 new items in this commit; Grep finds one fn matrix builder left under crates/metal/src/bin, in synthetic.rs. Dryer pairs: the clauses_q5k/clauses_q8_0 and experts.rs/routed.rs pairs are in code the earlier reviews saw; not re-raised.
Complexity: no function in this commit is on the crapper list.
Silent failure: 0 sites in this commit. The synthetic module resolves super::oracle::Rng to the probe's mod oracle (both are siblings in mac.rs), and gguf was already used by the probe.
Tests: no test changed. The probe's Q5_K matrices now use the f16 range [0.0001, 0.0008] from the shared builder. The probe's oracle band check (mac.rs:622) takes finite smaller scales.
Gates: none moved in this commit.
Escape catalog: no matching patterns. No unsafe code added.

Notes

Metal execution was not run in this review. The PR body's evidence is from an M1 Pro; the maintainers' fixture-tier run is still pending.

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

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