Skip to content

fix(paged-attn): apply review suggestions - #8

Merged
Brooooooklyn merged 3 commits into
mainfrom
paged-attn-fix
Dec 25, 2025
Merged

Brooooooklyn merged 3 commits into
mainfrom
paged-attn-fix

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Dec 25, 2025 •

Copy link
Copy Markdown
Contributor

Note

Strengthens correctness and clarifies dtype handling across paged attention and cache management.

  • Copy-on-write safety: SequenceBlockTable::replace_block now returns bool; handle_cow checks bounds and errors on out-of-range; remove_sequence only untracks tokens when a block’s last ref is dropped.
  • Token tracking fixes: Prevents accidental removal of unrelated prefix_index entries by verifying ownership on updates/removals; copy_block is a no-op if source missing and preserves destination index; cleans up old destination entry only if owned. Adds regression tests for shared-hash, overwrite, and nonexistent-source cases.
  • Metal I/O dtype standardization: V1/V2 raw dispatch always allocates/output as Float16; V2 temp tmp_out uses Float16. Return PagedAttentionOutput with dtype=Float16 regardless of cache dtype.
  • Kernel naming/API: Kernel-name builders now treat I/O as half and vary cache dtype (half or uchar for FP8); V2 reduce kernel always half. Tests updated to reflect new names.

Written by Cursor Bugbot for commit 3a54e63. This will update automatically on new commits. Configure here.

Summary by CodeRabbit

  • Bug Fixes

    • Added explicit failure reporting for block replacement to prevent silent out-of-bounds updates; copy-on-write now aborts on replacement failure.
    • Avoids removing token-tracker entries for shared blocks; more robust cleanup of stale token-index entries on updates, copies, and removals.
  • Refactor

    • Kernel I/O and intermediate buffers standardized to float16; cache dtype treated separately from I/O in kernel naming and selection.
  • Tests

    • Added regression tests for token-tracker copy, overwrite, shared-hash, and non-existent-source scenarios.

✏️ Tip: You can customize this high-level summary in your review settings.

Copilot AI review requested due to automatic review settings December 25, 2025 04:19
@coderabbitai

coderabbitai Bot commented Dec 25, 2025 •

Copy link
Copy Markdown

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

📝 Walkthrough

Walkthrough

Standardizes kernel outputs and host buffers to Float16, changes Metal kernel-name APIs to take cache dtype, makes replace_block return a boolean with callers checking it, and tightens token-tracker prefix_index updates for copy-on-write and removals.

Changes

Cohort / File(s) Summary
Block replacement & callers
crates/mlx-paged-attn/src/block_table.rs, crates/mlx-paged-attn/src/paged_kv_cache.rs
replace_block signature changed to return bool (success). Call sites check the return and propagate Err on out-of-bounds replacement during COW and update paths.
Kernel naming API (Metal)
crates/mlx-paged-attn/src/metal/state.rs
Kernel-name helpers now take cache_dtype (not input dtype); input/output type is fixed to Float16 while cache type derives from cache_dtype. Tests updated for FP8 (UChar) cache naming.
Paged attention buffers & outputs (Metal)
crates/mlx-paged-attn/src/metal/paged_attention.rs
Output and temporary buffers are sized using Float16 element size regardless of input dtype; returned PagedAttentionOutput reports dtype Float16; comments updated to reflect kernel outputs are Float16.
Token tracker & cache cleanup
crates/mlx-paged-attn/src/token_tracker.rs, crates/mlx-paged-attn/src/paged_kv_cache.rs
prefix_index updates now remove entries only when they map to the affected block; remove_sequence clears token tracking only when block refcount == 1. Copy-block path pre-cleans destination stale entries; new tests added for shared-hash and copy semantics.

Sequence Diagram(s)

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐇 I hop through kernels, nibble bits of gold,

Float16 trails where secrets unfold.
A boolean tells me if a swap took flight,
I tidy tokens in the soft moonlight,
Copy-on-write keeps sharing bold.

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'fix(paged-attn): apply review suggestions' is vague and generic, using non-descriptive language that does not convey the specific nature of the changes. Consider a more specific title that highlights a key aspect of the fix, such as 'fix(paged-attn): standardize output dtype to float16 and improve copy-on-write handling' or similar.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch paged-attn-fix

📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c729329 and 3a54e63.

📒 Files selected for processing (1)
  • crates/mlx-paged-attn/src/token_tracker.rs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Build & cargo test
  • GitHub Check: Cursor Bugbot
🔇 Additional comments (4)
crates/mlx-paged-attn/src/token_tracker.rs (4)

87-125: Excellent fix for stale prefix_index cleanup!

The ownership verification before removing the old hash entry correctly prevents the bug where modifying one block would incorrectly remove another block's prefix_index entry when they share the same hash. The three-part check (old exists, hash changed, entry belongs to this block) ensures correctness.

Based on past review comments, this successfully addresses the shared-hash collision issue.


164-169: Correct ownership check prevents incorrect removal!

The ownership verification ensures that when removing a block, we only delete its prefix_index entry if it actually owns that entry. This prevents accidentally removing an entry belonging to a different block with identical token content.

Based on past review comments, this successfully addresses the shared-hash issue during block removal.


184-205: Excellent fix for copy-on-write consistency!

The critical fix here is the ordering: the source existence check and early return (lines 186-188) occur before any destination cleanup (lines 192-199). This ensures that when the source block doesn't exist, the function returns immediately without modifying the destination's state or prefix_index entry.

Additionally, the destination cleanup correctly includes ownership verification to avoid removing entries belonging to other blocks with the same hash.

Based on past review comments, this successfully addresses the "destination prefix entry removed when source block missing" issue.


578-701: Comprehensive regression test coverage!

The four new tests provide excellent coverage of the ownership and consistency issues that were fixed:

  1. test_shared_hash_after_copy_block_track_tokens: Validates that modifying one block doesn't affect another with the same hash
  2. test_shared_hash_after_copy_block_remove_block: Validates that removing one block doesn't affect another with the same hash
  3. test_shared_hash_copy_block_overwrites: Validates proper cleanup when overwriting a block with different content
  4. test_copy_block_nonexistent_source_preserves_destination: Validates no-op behavior when copying from non-existent source

These tests directly verify the fixes and will prevent regression of the bugs identified in past reviews.


Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor Author

This stack of pull requests is managed by Graphite. Learn more about stacking.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR applies review suggestions to improve the paged attention implementation, focusing on better prefix cache management, error handling, and clarifying dtype semantics for FP8 quantization support.

Key Changes:

  • Enhanced prefix_index cleanup to remove stale entries when block tokens change
  • Added ref_count checking before removing token tracking in shared blocks
  • Clarified that Metal kernels always use float16 for input/output regardless of cache dtype
  • Added error handling for out-of-bounds block replacement operations

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
crates/mlx-paged-attn/src/token_tracker.rs Adds proactive cleanup of stale prefix_index entries when block tokens change or are copied
crates/mlx-paged-attn/src/paged_kv_cache.rs Adds ref_count check before token tracker cleanup and error handling for replace_block
crates/mlx-paged-attn/src/metal/state.rs Renames parameters to clarify cache_dtype vs io_dtype semantics, adds FP8 mode tests
crates/mlx-paged-attn/src/metal/paged_attention.rs Updates buffer allocation and output dtype to always use Float16
crates/mlx-paged-attn/src/block_table.rs Changes replace_block to return bool indicating success/failure

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
crates/mlx-paged-attn/src/metal/paged_attention.rs (1)

269-272: Inconsistent tmp_out sizing in non-raw V2 dispatch.

The non-raw dispatch_paged_attention_v2 function still uses dtype.size() for tmp_out_size (line 269-271), while the raw variant correctly uses MetalDtype::Float16.size(). This inconsistency could cause buffer size mismatches when using FP8 cache.

🔎 Proposed fix
     let tmp_out_size = (params.num_seqs * params.num_heads * max_num_partitions * params.head_size)
         as usize
-        * dtype.size();
+        * MetalDtype::Float16.size();
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 11080b1 and 50f2560.

📒 Files selected for processing (5)
  • crates/mlx-paged-attn/src/block_table.rs
  • crates/mlx-paged-attn/src/metal/paged_attention.rs
  • crates/mlx-paged-attn/src/metal/state.rs
  • crates/mlx-paged-attn/src/paged_kv_cache.rs
  • crates/mlx-paged-attn/src/token_tracker.rs
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to crates/mlx-core/src/transformer/*.rs : Maintain functional forward pass architecture in transformer components to enable automatic differentiation through MLX computation graphs

Applied to files:

  • crates/mlx-paged-attn/src/metal/paged_attention.rs
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to crates/mlx-core/src/transformer/*.rs : Implement KVCache, BatchKVCache, and RotatingKVCache as separate transformer components with different memory management strategies

Applied to files:

  • crates/mlx-paged-attn/src/paged_kv_cache.rs
  • crates/mlx-paged-attn/src/metal/state.rs
🧬 Code graph analysis (1)
crates/mlx-paged-attn/src/metal/state.rs (4)
crates/mlx-paged-attn/src/config.rs (1)
  • use_fp8 (110-112)
crates/mlx-paged-attn/src/attention_layer.rs (1)
  • head_size (179-181)
crates/mlx-paged-attn/src/metal/swap_blocks.rs (1)
  • block_size (59-61)
crates/mlx-paged-attn/src/block_allocator.rs (1)
  • block_size (228-230)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Agent
  • GitHub Check: Cursor Bugbot
  • GitHub Check: Build & yarn test
  • GitHub Check: Build & cargo test
  • GitHub Check: Rust Lint
🔇 Additional comments (12)
crates/mlx-paged-attn/src/token_tracker.rs (3)

87-93: Good addition for prefix index consistency.

Computing the old hash before modifying block_tokens ensures stale entries can be properly cleaned up from prefix_index. The .filter(|t| !t.is_empty()) guard correctly avoids computing a hash for empty vectors.


179-185: Proper cleanup before copy-on-write.

The destination block's old hash is correctly removed from prefix_index before the copy occurs. This prevents stale mappings when a block is overwritten during COW operations.


119-124: Let-chains syntax is fully supported in this project. The MSRV is 1.89.0 and edition is 2024, both well above the 1.76+ requirement where let-chains was stabilized. No changes needed.

crates/mlx-paged-attn/src/block_table.rs (1)

42-54: LGTM - Good defensive API change.

Returning a boolean allows callers to detect and handle out-of-bounds replacement attempts. The implementation is correct and the documentation clearly describes the return semantics.

crates/mlx-paged-attn/src/paged_kv_cache.rs (2)

141-147: Correct handling of shared block token tracking.

The ref_count check ensures token tracking is only removed when the block is no longer shared. This properly handles the forked sequence case where multiple sequences reference the same block.


1515-1520: Good defensive error handling for block replacement.

Checking the replace_block return value and propagating an error prevents silent failures during copy-on-write. The error message is descriptive and includes both the block index and sequence ID for debugging.

crates/mlx-paged-attn/src/metal/paged_attention.rs (2)

609-613: Correct standardization of output dtype to Float16.

The output buffer sizing and reported dtype are correctly changed to always use Float16. The comments clearly explain that the kernel dequantizes FP8 internally, so outputs are always Float16.

Also applies to: 726-732


755-773: LGTM - V2 raw variant correctly uses Float16 sizing.

Both the output buffer and tmp_out intermediate buffer correctly use Float16 sizing, ensuring consistent buffer allocation regardless of cache dtype.

crates/mlx-paged-attn/src/metal/state.rs (4)

117-130: Clear separation of input and cache dtypes.

The refactor correctly documents and implements that input KV tensors are always float16 from the model, while the cache dtype varies. The kernel name format accurately reflects the template parameters.


141-155: Consistent I/O and cache dtype handling across V1/V2 kernels.

Both kernel name generators correctly use Float16 for I/O operations and parameterize only the cache type. The comments explaining the design decision are helpful.

Also applies to: 166-180


185-195: Unused parameter kept for API consistency.

The _cache_dtype parameter is intentionally unused since the reduce kernel always works with Float16 partition outputs. The underscore prefix correctly signals this.


277-294: Comprehensive test coverage for FP8 cache mode.

The test cases correctly verify:

  • FP8 cache kernel names use half for I/O and uchar for cache storage
  • Reduce kernel uses Float16 regardless of cache dtype

All kernel names in the assertions are properly instantiated in the Metal source files.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
crates/mlx-paged-attn/src/token_tracker.rs (1)

122-122: Optional: Consider extracting ownership check pattern.

The ownership check pattern self.prefix_index.get(&hash).map(|(id, _)| *id) == Some(block_id) appears in three locations (track_tokens, remove_block, copy_block). While the current code is clear and correct, you could optionally extract this into a helper method for improved maintainability:

fn owns_prefix_entry(&self, hash: u64, block_id: u32) -> bool {
    self.prefix_index.get(&hash).map(|(id, _)| *id) == Some(block_id)
}

However, given the pattern is only used three times and is already quite readable, this is purely a stylistic preference.

Also applies to: 167-167, 188-188

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 50f2560 and a412d6f.

📒 Files selected for processing (1)
  • crates/mlx-paged-attn/src/token_tracker.rs
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to crates/mlx-core/src/grpo/**/*.rs : GRPO training components (loss, advantages, entropy filtering) must include comprehensive Rust test suites (minimum 10+ tests per component)

Applied to files:

  • crates/mlx-paged-attn/src/token_tracker.rs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Cursor Bugbot
  • GitHub Check: Build & yarn test
  • GitHub Check: Build & cargo test
🔇 Additional comments (5)
crates/mlx-paged-attn/src/token_tracker.rs (5)

87-92: LGTM! Old hash computation is correct.

The code correctly computes the old hash before modifying the block's tokens, which is essential for detecting hash changes and cleaning up stale prefix_index entries. The filter for empty token vectors is appropriate.


119-125: LGTM! Ownership check correctly prevents incorrect removal.

The implementation correctly verifies that the stale prefix_index entry belongs to the current block_id before removing it. This prevents the bug where modifying one block would incorrectly remove another block's prefix_index entry when they share the same hash after copy-on-write.

The three-condition check is appropriate:

  1. Old hash exists
  2. Hash changed
  3. Entry belongs to this block

164-169: LGTM! Consistent ownership check in remove_block.

The ownership verification before removing the prefix_index entry is implemented consistently with the track_tokens changes. This ensures that when multiple blocks share the same hash, removing one block doesn't incorrectly remove another block's prefix_index entry.


183-191: LGTM! Destination cleanup with ownership check is correct.

The implementation correctly removes the destination block's old prefix_index entry (if it owns it) before copying new content. This ensures that:

  1. The destination's old hash entry is cleaned up when the content changes
  2. If another block shares the same hash, its entry is not incorrectly removed

573-657: LGTM! Comprehensive regression tests.

The three new tests provide excellent coverage of the shared-hash scenarios that were causing prefix_index corruption:

  1. test_shared_hash_after_copy_block_track_tokens: Verifies that modifying one block after a copy doesn't remove the other block's prefix_index entry
  2. test_shared_hash_after_copy_block_remove_block: Verifies that removing one block after a copy doesn't affect the other block's entry
  3. test_shared_hash_copy_block_overwrites: Verifies that copying to a block with different content correctly removes the old entry

The tests are well-documented and include helpful assertion messages. They directly validate the ownership-check logic implemented in the production code.

…ex entries

When multiple blocks share identical tokens (after copy_block), they have
the same hash but only one block's entry exists in prefix_index. The cleanup
code was incorrectly removing entries based solely on hash without checking
if the entry belonged to the block being modified.

Fixes:
- track_tokens: Check block_id ownership before removing stale entry
- copy_block: Check dst_block_id ownership before removing old entry
- remove_block: Check block_id ownership before removing entry

Added 3 regression tests to verify the fix.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
…in copy_block

If src_block_id doesn't exist, copy_block was removing dst_block_id's
prefix_index entry but leaving its tokens unchanged, causing an
inconsistent state.

Now copy_block checks if source exists first and returns early if not,
ensuring destination state is never modified when there's nothing to copy.

Added regression test for this scenario.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@Brooooooklyn
Brooooooklyn merged commit 3a6b8db into main Dec 25, 2025
@Brooooooklyn
Brooooooklyn deleted the paged-attn-fix branch December 25, 2025 07:52
Brooooooklyn added a commit that referenced this pull request Apr 11, 2026
<!-- CURSOR_SUMMARY -->
> [!NOTE]
> Strengthens correctness and clarifies dtype handling across paged
attention and cache management.
> 
> - **Copy-on-write safety**: `SequenceBlockTable::replace_block` now
returns `bool`; `handle_cow` checks bounds and errors on out-of-range;
`remove_sequence` only untracks tokens when a block’s last ref is
dropped.
> - **Token tracking fixes**: Prevents accidental removal of unrelated
`prefix_index` entries by verifying ownership on updates/removals;
`copy_block` is a no-op if source missing and preserves destination
index; cleans up old destination entry only if owned. Adds regression
tests for shared-hash, overwrite, and nonexistent-source cases.
> - **Metal I/O dtype standardization**: V1/V2 raw dispatch always
allocates/output as `Float16`; V2 temp `tmp_out` uses `Float16`. Return
`PagedAttentionOutput` with `dtype=Float16` regardless of cache dtype.
> - **Kernel naming/API**: Kernel-name builders now treat I/O as `half`
and vary cache dtype (`half` or `uchar` for FP8); V2 reduce kernel
always `half`. Tests updated to reflect new names.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
3a54e63. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Bug Fixes**
* Added explicit failure reporting for block replacement to prevent
silent out-of-bounds updates; copy-on-write now aborts on replacement
failure.
* Avoids removing token-tracker entries for shared blocks; more robust
cleanup of stale token-index entries on updates, copies, and removals.

* **Refactor**
* Kernel I/O and intermediate buffers standardized to float16; cache
dtype treated separately from I/O in kernel naming and selection.

* **Tests**
* Added regression tests for token-tracker copy, overwrite, shared-hash,
and non-existent-source scenarios.

<sub>✏️ Tip: You can customize this high-level summary in your review
settings.</sub>
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude <[email protected]>
Brooooooklyn added a commit that referenced this pull request Jun 2, 2026
Wires the MTP draft+verify+accept cycle into Qwen3.5 dense chat
sessions. Uses W1-W5 building blocks: MTP weights (W1), W5 dense
compiled FFI, accept_with_residual (W4). W3 snapshot/restore is NOT
used on the compiled path — the live K/V is in the C++ globals and
the rollback primitive is mlx_qwen35_compiled_adjust_offset.

Architecture:
- New small FFI: mlx_qwen35_export_last_hidden, stashed BEFORE lm_head
  in qwen35_decode_fn so MTP draft step 0 can seed prev_hidden.
- forward_compiled_with_hidden returns (logits, hidden) — only used
  in the MTP path.
- decode_loop_mtp! macro in chat_common.rs mirrors decode_loop!'s
  structure (EOS, repetition cutoff, ReasoningTracker, penalties,
  streaming, cancellation, profiler, 256-step cache clear). Each
  outer iteration runs Step A (one main forward, captures hidden)
  then one MTP cycle (D draft + 1 verify + accept loop + optional
  bonus on full-accept). Emits 1..=D+2 tokens per outer iteration.
- 3 dispatch sites in model.rs (sync, stream-delta, stream-session)
  gate on `enable_mtp && self.has_mtp_weights()`. Default is off
  pending W7 plumbing.
- Rollback formula at each dispatch site:
    delta = accepted_drafts as i32 - depth as i32;
    if delta != 0 { adjust_offset(delta) for both main and MTP }.
  Derivation: verify writes D+1 K/V slots (committed_id + D drafts);
  we keep K accepted draft slots; correct rewind is K - D (residual
  has no K/V — it gets one at NEXT cycle's Step A).
- Adaptive depth EMA is OUT OF SCOPE. Fixed mtp_depth = 3.

Known caveat — chained cycles not implemented:
- Each outer iteration always runs Step A (one main forward). MTPLX
  skips this on the hot path by seeding the next cycle's prev_hidden
  from verify_hidden[:, -1:, :], which would require a new FFI to
  export the verify graph's last hidden state.
- This costs roughly +150ms per cycle on M3 Max bf16 (one extra
  main decode step). On all-accept depth=3, MTPLX measures ~2.24×
  on Qwen3.6-27B; W6's chained-cycle deficit reduces that estimate
  to ~1.43× — possibly under the plan's 1.6× target. If the W6 path
  measurement in the manual smoke (task #8) misses the bar, a W6.5
  follow-up will add the verify-hidden export and chain cycles.

Tests:
- chat_common::mtp_cycle_tests: 4 cycle tests (all-accept emits D+1,
  depth=1 degenerates, all-reject emits 1 residual, partial-reject
  regression that asserts (accepted_drafts, depth) callback values).
- chat_common::mtp_params_tests: 3 ChatParams extraction tests.
- mtp::compiled_ffi_tests::export_last_hidden_null_without_main_forward.
- All 120 qwen3_5 unit tests pass (14 ignored on non-Metal).

The MoE-side model.rs edit is only ChatConfig field plumbing
(enable_mtp: None, mtp_depth: None) to keep MoE chat sessions
compiling. W6 MoE comes next.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Jun 2, 2026
Mirrors W6 dense (77da687) for the Qwen3.5 MoE variant. Reuses the
dense `decode_loop_mtp!` macro from `qwen3_5/chat_common.rs` 100%
via the generic `MtpOps` struct — no generalization needed.

C++ design difference from dense:
- Dense's main path calls `qwen35_decode_fn` directly (no compile
  wrap), so `g_last_hidden = h` inside the function body fires every
  call.
- MoE's main path runs through `mlx::core::compile(moe_compiled_decode_fn)`,
  so a body-level assignment would only fire at trace time. Instead,
  `last_hidden` is emitted as graph output slot 2 (caches shift to
  start at slot 3) and stashed by `mlx_qwen35_moe_forward` after the
  compiled call. A defensive `outputs.size()` check guards against
  silent stride drift in future edits.

4 MoE dispatch sites (sync, stream, sync-delta, stream-delta) each
acquire `MOE_COMPILED_MUTEX` before entering `decode_loop_mtp!` and
call `mlx_qwen35_moe_mtp_compiled_reset()` immediately after.

Same caveat as W6 dense — chained cycles not implemented (each
outer iteration runs Step A's main forward). The W6.5 follow-up
will add `mlx_qwen35_moe_mtp_verify_compiled_with_hidden` if the
manual smoke (task #8) shows the 1.6× target missed.

Tests: 22/22 MoE unit tests pass (7 Metal-gated ignored), including
the new `export_last_hidden_null_without_main_forward` smoke. No
dense regressions (121/121 dense unit tests pass).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Jun 18, 2026
…n-defaults, lfm2 leak)

Adversarially verified all 11 inline review comments (control-flow traced;
the P1 #5 was a false alarm — qwen3_5 flat uses the decode_loop! macro that
forwards EOS before the stop check). Five were real; this fixes them.

Multi-turn flat KV/history alignment (#8 qwen3, #9 lfm2, + gemma4 sibling):
the shared `run_decode_loop` forward gate (`step+1 < max && !is_terminal`)
skips the final committed token's forward on EVERY exit, so the physical
flat cache holds P+N-1 tokens — but the per-family save persisted P+N,
leaving cached_token_history one token ahead of the cache. The next
chatSessionContinue prefills only the delta onto a cache one short →
multi-turn corruption. The two families violated on OPPOSITE axes (qwen3/
gemma4 keep-all-on-length; lfm2 keep-all-on-EOS) and need OPPOSITE fixes:
- qwen3/gemma4 are pure-KV → add a flat `materialize_final` override + an
  engine call on LENGTH exits that records the final token's K/V (mirrors
  each family's existing paged sibling; keep-all-on-length preserves the
  content token, NOT the bot-suggested drop which re-introduces a prior
  Codex-HIGH content truncation).
- lfm2 is conv-state (cannot re-run a forward) → drop-last ALWAYS, mirroring
  its own paged `save_paged_history`.
Removed the now-dead `SaveStateArgs.last_token_in_cache` field (lfm2 was its
only consumer; the shared loop makes it always-false). Added 2 negative-
controlled regression tests asserting cached_token_history.len() ==
physical_cache_len after both a LENGTH exit and an EOS early-stop.

generation_config.json defaults on VLM/MTP routes (#6 dense, #7 moe): the
qwen3_5 dense_whole_turn / paged-MTP and moe_whole_turn legacy cores
re-ran extract_chat_params on the RAW config, bypassing the engine-resolved
args.params, so omitted sampling fields fell back to builtins instead of the
checkpoint's generation_config.json. Fold apply_generation_defaults into the
config before the cores re-extract (no-op when the checkpoint ships none).

lfm2 compiled-weight leak on drop (#3): Lfm2Inner::drop erased only the
compiled-graph slot, never `mlx_clear_weights(model_id)` — so each dropped
compiled-capable lfm2 leaked its full C++ weight copy (+ 2-D transposes +
quant_info) until process exit, OOMing servers that reload models. Free it
under the write lock already held.

Gates (M5 Max): build + clippy -D warnings + fmt --check clean; engine::cmd
20/20 incl 2 new regression tests; full lib 1776 pass / 3 pre-existing flaky
Metal-f32 (banded_attention / attention_vjp, untouched files).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Jul 22, 2026
…t ranks/bands, guards

Adversarial-review reconciliation for the Tier-1 gallery (all 8 verified against
the committed frames + control flow before fixing):

P1 #1  DROP eiffel-capital: 'Paris' IS the ℓ24 greedy output, a SPOKEN answer —
       violates the 'unspoken word' invariant. Gallery now 7 tiles (5 STRONG+2 WEAK).
       New bake assertion: no pinned concept may equal the ℓ24 argmax.
P1 #2  self-test: reject invalid live rank <=0 so a collapsed rank path can't pass
       the fuzzy low-rank delta on the french-season oracle.
P2 #3  grammar caption 'both lenses raise incorrect to rank 1-2' was false for logit
       (pinned 79034 is rank ~20 there) → rewrite to the honest J-vs-logit framing.
P2 #4  openStarter race: monotonic runIntent token; run/mode-change continuations
       bail after their awaits instead of painting a live frame over the tile.
P2 #5  rank captions were 0-based vs the 1-based API — fix inner-sum 2->3 (logit 6->7),
       precedence 0->1, few-shot 2->3, int-cast 1->2 (en+zh).
P2 #6  band drift: grammar peak ℓ18(rank4)->ℓ17(rank2), giza {16,17}->{17,18} to match
       the rank-2 plateau; tighten the bake to require band.peak on a min-rank layer.
P2 #7  cold-URL guard drops the mode check so opening a tile keeps the URL clean.
P2 #8  LandingPage persists storeLocale(useLocale()) so a direct /zh visitor's
       'Open J-Space' inherits zh (the standalone /jspace reads only localStorage).

Frames re-baked (7 byte-identical, eiffel-capital.json removed); +2 committed-data
regression tests encode the unspoken-word and band-peak invariants.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Jul 25, 2026
…udit

Audit found via 7-surface workflow, each finding independently re-verified
(source + live-measured) before fixing.

Contrast (root causes, hit every page):
- #1 --text-muted #6a6168 (~2.9–3.2:1, failed WCAG AA) → #9a908a; now
  5.6–6.2:1 on breadcrumbs, chapter numbers, problem statements, placeholders
  (1260 text-muted-foreground uses + a few raw color: uses).
- #2 `@custom-variant dark` gated every `dark:` utility on a `.dark` ancestor
  that nothing added → intended dark callout/button colors were inert (light
  base rendered: amber/violet chips 2.3–3.6:1). Add `.dark` at boot
  (index.html shell + seo-head, captured by the prerender serialization).
  Callouts now render amber-300/violet-300/emerald-400 at 8.9–12:1.

Responsive:
- #3 no cross-chapter nav below 1024px (sidebar is `hidden lg:block`, no
  drawer/pager) → ChapterPager prev/next at every chapter foot, order from the
  `localizedChapters` registry, locale-prefixed `<a href>` + SPA-intercept,
  first/last handled, sub-chapters threaded (en+zh strings added).
- #4 /chapters hub header collided at 375px (Back over free-chat 8px, 中文
  wrapped) → labels collapse to icon+sr-only below sm (mirrors LessonLayout),
  groups shrink-0, switcher whitespace-nowrap.
- #8 landing locale toggle overlapped the hero badge at 375px (68×23px) →
  corner toggle hidden below sm; mobile in-flow toggle rides above the badge;
  hero top-anchored so the non-scrolling overlay never clips it.

Controls / a11y:
- #5 four widgets (TeacherForcingAnimation/GenerationLoop/LmHeadWalkthrough/
  WeightTyingVisual) auto-animated ignoring prefers-reduced-motion, unlike 48
  siblings → seed `playing` from matchMedia (verbatim sibling idiom) + gated
  aria-live on the step caption.
- #6 dead enabled "Voice input" mic button (no handler) → removed + dropped
  the unused Mic import.
- #7 shared <Button> stayed 32–40px on touch (the coarse-pointer 44px rule
  only matched chat classes) → min-height:44px for [data-slot=button] (+ icon
  min-width) under pointer:coarse.

Verified: build green (vite+prerender), `.dark` in all prerendered pages,
desktop unchanged, mobile pager/headers/landing confirmed live at 375px.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…loc; add persist env override

D (REGRESSION): the cold-cache restore bound used a flat +4096 header allowance,
but the safetensors header carries 1+2*num_layers tensor descriptors and grows
O(layers), overrunning 4096 at ~24 layers (block_size=16). Every real Qwen3
depth (28/32/40/64) had its persisted blocks rejected as oversized "corruption"
on restart, silently disabling persistence. Replace the flat constant with a
shared header_overhead(num_layers) = (1+2*num_layers)*256 + 1024 + 15 helper,
mirrored by both encoded_len and max_encoded_len_for_pool (256 B/descriptor
upper-bounds the ~140 B worst case). Also guard decode_block: reject when
(2*num_layers+1) != tensors.len() before Vec::with_capacity, closing the
~206 GB forged-metadata OOM (the read cap alone didn't bound a metadata-driven
allocation). Deep-layer bound-mirror + tensor-count-guard regression tests added.

#8: implement the spec-mandated persistence env override (spec:80 "config + env
override"). Read MLX_PERSIST_PAGED_CACHE at the native load boundary with
precedence env > config aliases > false, so a direct library caller can enable
persistence without a config field. Documented in docs/perf.md.

#10 (doc): correct the load-window comment — the three identity snapshots close
the atomic-rename race but a coordinated local ABA swap remains an accepted
residual (the sound fix needs fd-coupled fingerprinting, out of scope).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…nload identity, session safety

Six confirmed defects from the final whole-branch review (each control-flow
verified + probed before fixing); one finding refuted, one documented residual.

- #6 metrics (regression from R11): the trace-only token UNION projected GROSS
  traces.prompt_tokens into the `input` column while turns store NET
  (prompt-cacheRead), double-counting cached tokens. Clamp the trace side to
  MAX(prompt-cached,0) in tokensByDay + turnTotals; fixture totals corrected.
- #4 downloads: gate the install-skip on the completion marker's repo+revision
  (new readCompletion helper), not mere presence — a different revision of the
  same slug no longer reports a false `done`; mismatch falls through to the
  owned-swap.
- #7 trace ingest: move the vanished-file row reconciliation BEFORE the ingest
  loop so a renamed trace file's globally-unique rows are freed before the new
  name is ingested (were permanently dropped); watermark reconcile stays after.
- #8 session ingest: reject a non-object top-level entry (a `header\nnull\n`
  file) in isValidSessionTopology before dereferencing .type, routing it to the
  existing quarantine path instead of a warn-only catch that retained stale rows.
- #3 session rename: refuse (409) renaming a session whose file was modified
  within a liveness window — pi has no cross-process lock, so appending to a
  file a live agent is extending would race that turn. Documented best-effort.
- #5 cold cache: publish the index entry before the directory fsync so a
  post-rename dir-fsync failure keeps in-process accounting consistent with the
  on-disk file (rebuild_index already self-heals on restart).
- #2 cold-tier fingerprint→materialize window: documented as an accepted v1
  residual (off-by-default, adversary-owns-files; fd-coupled hashing out of scope).
- #1 (train KV poisoning): refuted — training never uses the paged/cold path.

Gate: typecheck exit0 · cold_cache 33/0 · dashboard 8 suites/175 · lint 0-err.
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…sion discovery, cold-cache durability

Seven confirmed defects from the final whole-branch review (each control-flow
verified + probed); one documented as an accepted fail-open residual.

- #8 (ui): resume commands interpolated the session path into a shell string
  raw — a real injection ($()/backticks/&& fired in a probe) and a break on any
  path with a space. Added a shared POSIX shQuote used at both resume sites.
- #5 (models): walkDirStats followed symlinks with statSync and recursed into
  symlinked directory targets unbounded — two links to '.' hit ~2^31 stats and
  froze the synchronous /api/models. Now recurses only real dirs (Dirent lstat
  semantics), with a dev:ino visited-set and an entry budget.
- #4 (ingest): pi with an explicit --session-dir writes sessions flat as
  <dir>/*.jsonl, but the scanner only accepted <root>/--cwd--/*.jsonl, so the
  documented shared --session-dir flow produced an empty dashboard. Now scans
  both layouts (cwd read from each file's header).
- #6 (download): an unowned (marker-less) install was refused only inside
  publish, after a full multi-GB download+hash. Preflight ownership up front
  (after staging recovery, before any hub work) so a doomed job moves no bytes;
  reworded errors to drop the unexposed overwrite advice.
- #7 (metrics): per-session metrics omitted delegated (subagent) turns —
  session-scoped trace-only union with MAX(prompt-cached,0) net clamp + trace_id
  dedup, mirroring the global overview fix, so counts/tokens match the shown
  child badge + throughput.
- #2 (cold cache): the capture loop kept blitting Metal + persisting descendants
  after a queue-drop; now stops on the first non-Ok(true), keeping the enqueued
  set a contiguous restorable prefix.
- #3 (cold cache): mlx agent -p exited with accepted blocks still queued (no
  drain). Added a bounded native drain barrier (WriteJob::Barrier +
  ColdCacheManager::drain -> #[napi] cold_cache_drain) invoked on clean shutdown.
- #1 (docs): documented that LRU eviction is chain-unaware and can strand prefix
  chains under quota pressure (fail-open; common case unaffected) — chain-aware
  eviction is a follow-up.

Gate: cold_cache 35/0 · typecheck exit0 · dashboard 187 tests/9 files · lint
0-err · UI build 0. (build:native's metallib floor gate fails on a known
toolchain/env hazard, independent of this branch — no shader/build files touched.)
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…loc; add persist env override

D (REGRESSION): the cold-cache restore bound used a flat +4096 header allowance,
but the safetensors header carries 1+2*num_layers tensor descriptors and grows
O(layers), overrunning 4096 at ~24 layers (block_size=16). Every real Qwen3
depth (28/32/40/64) had its persisted blocks rejected as oversized "corruption"
on restart, silently disabling persistence. Replace the flat constant with a
shared header_overhead(num_layers) = (1+2*num_layers)*256 + 1024 + 15 helper,
mirrored by both encoded_len and max_encoded_len_for_pool (256 B/descriptor
upper-bounds the ~140 B worst case). Also guard decode_block: reject when
(2*num_layers+1) != tensors.len() before Vec::with_capacity, closing the
~206 GB forged-metadata OOM (the read cap alone didn't bound a metadata-driven
allocation). Deep-layer bound-mirror + tensor-count-guard regression tests added.

#8: implement the spec-mandated persistence env override (spec:80 "config + env
override"). Read MLX_PERSIST_PAGED_CACHE at the native load boundary with
precedence env > config aliases > false, so a direct library caller can enable
persistence without a config field. Documented in docs/perf.md.

#10 (doc): correct the load-window comment — the three identity snapshots close
the atomic-rename race but a coordinated local ABA swap remains an accepted
residual (the sound fix needs fd-coupled fingerprinting, out of scope).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…nload identity, session safety

Six confirmed defects from the final whole-branch review (each control-flow
verified + probed before fixing); one finding refuted, one documented residual.

- #6 metrics (regression from R11): the trace-only token UNION projected GROSS
  traces.prompt_tokens into the `input` column while turns store NET
  (prompt-cacheRead), double-counting cached tokens. Clamp the trace side to
  MAX(prompt-cached,0) in tokensByDay + turnTotals; fixture totals corrected.
- #4 downloads: gate the install-skip on the completion marker's repo+revision
  (new readCompletion helper), not mere presence — a different revision of the
  same slug no longer reports a false `done`; mismatch falls through to the
  owned-swap.
- #7 trace ingest: move the vanished-file row reconciliation BEFORE the ingest
  loop so a renamed trace file's globally-unique rows are freed before the new
  name is ingested (were permanently dropped); watermark reconcile stays after.
- #8 session ingest: reject a non-object top-level entry (a `header\nnull\n`
  file) in isValidSessionTopology before dereferencing .type, routing it to the
  existing quarantine path instead of a warn-only catch that retained stale rows.
- #3 session rename: refuse (409) renaming a session whose file was modified
  within a liveness window — pi has no cross-process lock, so appending to a
  file a live agent is extending would race that turn. Documented best-effort.
- #5 cold cache: publish the index entry before the directory fsync so a
  post-rename dir-fsync failure keeps in-process accounting consistent with the
  on-disk file (rebuild_index already self-heals on restart).
- #2 cold-tier fingerprint→materialize window: documented as an accepted v1
  residual (off-by-default, adversary-owns-files; fd-coupled hashing out of scope).
- #1 (train KV poisoning): refuted — training never uses the paged/cold path.

Gate: typecheck exit0 · cold_cache 33/0 · dashboard 8 suites/175 · lint 0-err.
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…sion discovery, cold-cache durability

Seven confirmed defects from the final whole-branch review (each control-flow
verified + probed); one documented as an accepted fail-open residual.

- #8 (ui): resume commands interpolated the session path into a shell string
  raw — a real injection ($()/backticks/&& fired in a probe) and a break on any
  path with a space. Added a shared POSIX shQuote used at both resume sites.
- #5 (models): walkDirStats followed symlinks with statSync and recursed into
  symlinked directory targets unbounded — two links to '.' hit ~2^31 stats and
  froze the synchronous /api/models. Now recurses only real dirs (Dirent lstat
  semantics), with a dev:ino visited-set and an entry budget.
- #4 (ingest): pi with an explicit --session-dir writes sessions flat as
  <dir>/*.jsonl, but the scanner only accepted <root>/--cwd--/*.jsonl, so the
  documented shared --session-dir flow produced an empty dashboard. Now scans
  both layouts (cwd read from each file's header).
- #6 (download): an unowned (marker-less) install was refused only inside
  publish, after a full multi-GB download+hash. Preflight ownership up front
  (after staging recovery, before any hub work) so a doomed job moves no bytes;
  reworded errors to drop the unexposed overwrite advice.
- #7 (metrics): per-session metrics omitted delegated (subagent) turns —
  session-scoped trace-only union with MAX(prompt-cached,0) net clamp + trace_id
  dedup, mirroring the global overview fix, so counts/tokens match the shown
  child badge + throughput.
- #2 (cold cache): the capture loop kept blitting Metal + persisting descendants
  after a queue-drop; now stops on the first non-Ok(true), keeping the enqueued
  set a contiguous restorable prefix.
- #3 (cold cache): mlx agent -p exited with accepted blocks still queued (no
  drain). Added a bounded native drain barrier (WriteJob::Barrier +
  ColdCacheManager::drain -> #[napi] cold_cache_drain) invoked on clean shutdown.
- #1 (docs): documented that LRU eviction is chain-unaware and can strand prefix
  chains under quota pressure (fail-open; common case unaffected) — chain-aware
  eviction is a follow-up.

Gate: cold_cache 35/0 · typecheck exit0 · dashboard 187 tests/9 files · lint
0-err · UI build 0. (build:native's metallib floor gate fails on a known
toolchain/env hazard, independent of this branch — no shader/build files touched.)
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…loc; add persist env override

D (REGRESSION): the cold-cache restore bound used a flat +4096 header allowance,
but the safetensors header carries 1+2*num_layers tensor descriptors and grows
O(layers), overrunning 4096 at ~24 layers (block_size=16). Every real Qwen3
depth (28/32/40/64) had its persisted blocks rejected as oversized "corruption"
on restart, silently disabling persistence. Replace the flat constant with a
shared header_overhead(num_layers) = (1+2*num_layers)*256 + 1024 + 15 helper,
mirrored by both encoded_len and max_encoded_len_for_pool (256 B/descriptor
upper-bounds the ~140 B worst case). Also guard decode_block: reject when
(2*num_layers+1) != tensors.len() before Vec::with_capacity, closing the
~206 GB forged-metadata OOM (the read cap alone didn't bound a metadata-driven
allocation). Deep-layer bound-mirror + tensor-count-guard regression tests added.

#8: implement the spec-mandated persistence env override (spec:80 "config + env
override"). Read MLX_PERSIST_PAGED_CACHE at the native load boundary with
precedence env > config aliases > false, so a direct library caller can enable
persistence without a config field. Documented in docs/perf.md.

#10 (doc): correct the load-window comment — the three identity snapshots close
the atomic-rename race but a coordinated local ABA swap remains an accepted
residual (the sound fix needs fd-coupled fingerprinting, out of scope).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…nload identity, session safety

Six confirmed defects from the final whole-branch review (each control-flow
verified + probed before fixing); one finding refuted, one documented residual.

- #6 metrics (regression from R11): the trace-only token UNION projected GROSS
  traces.prompt_tokens into the `input` column while turns store NET
  (prompt-cacheRead), double-counting cached tokens. Clamp the trace side to
  MAX(prompt-cached,0) in tokensByDay + turnTotals; fixture totals corrected.
- #4 downloads: gate the install-skip on the completion marker's repo+revision
  (new readCompletion helper), not mere presence — a different revision of the
  same slug no longer reports a false `done`; mismatch falls through to the
  owned-swap.
- #7 trace ingest: move the vanished-file row reconciliation BEFORE the ingest
  loop so a renamed trace file's globally-unique rows are freed before the new
  name is ingested (were permanently dropped); watermark reconcile stays after.
- #8 session ingest: reject a non-object top-level entry (a `header\nnull\n`
  file) in isValidSessionTopology before dereferencing .type, routing it to the
  existing quarantine path instead of a warn-only catch that retained stale rows.
- #3 session rename: refuse (409) renaming a session whose file was modified
  within a liveness window — pi has no cross-process lock, so appending to a
  file a live agent is extending would race that turn. Documented best-effort.
- #5 cold cache: publish the index entry before the directory fsync so a
  post-rename dir-fsync failure keeps in-process accounting consistent with the
  on-disk file (rebuild_index already self-heals on restart).
- #2 cold-tier fingerprint→materialize window: documented as an accepted v1
  residual (off-by-default, adversary-owns-files; fd-coupled hashing out of scope).
- #1 (train KV poisoning): refuted — training never uses the paged/cold path.

Gate: typecheck exit0 · cold_cache 33/0 · dashboard 8 suites/175 · lint 0-err.
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…sion discovery, cold-cache durability

Seven confirmed defects from the final whole-branch review (each control-flow
verified + probed); one documented as an accepted fail-open residual.

- #8 (ui): resume commands interpolated the session path into a shell string
  raw — a real injection ($()/backticks/&& fired in a probe) and a break on any
  path with a space. Added a shared POSIX shQuote used at both resume sites.
- #5 (models): walkDirStats followed symlinks with statSync and recursed into
  symlinked directory targets unbounded — two links to '.' hit ~2^31 stats and
  froze the synchronous /api/models. Now recurses only real dirs (Dirent lstat
  semantics), with a dev:ino visited-set and an entry budget.
- #4 (ingest): pi with an explicit --session-dir writes sessions flat as
  <dir>/*.jsonl, but the scanner only accepted <root>/--cwd--/*.jsonl, so the
  documented shared --session-dir flow produced an empty dashboard. Now scans
  both layouts (cwd read from each file's header).
- #6 (download): an unowned (marker-less) install was refused only inside
  publish, after a full multi-GB download+hash. Preflight ownership up front
  (after staging recovery, before any hub work) so a doomed job moves no bytes;
  reworded errors to drop the unexposed overwrite advice.
- #7 (metrics): per-session metrics omitted delegated (subagent) turns —
  session-scoped trace-only union with MAX(prompt-cached,0) net clamp + trace_id
  dedup, mirroring the global overview fix, so counts/tokens match the shown
  child badge + throughput.
- #2 (cold cache): the capture loop kept blitting Metal + persisting descendants
  after a queue-drop; now stops on the first non-Ok(true), keeping the enqueued
  set a contiguous restorable prefix.
- #3 (cold cache): mlx agent -p exited with accepted blocks still queued (no
  drain). Added a bounded native drain barrier (WriteJob::Barrier +
  ColdCacheManager::drain -> #[napi] cold_cache_drain) invoked on clean shutdown.
- #1 (docs): documented that LRU eviction is chain-unaware and can strand prefix
  chains under quota pressure (fail-open; common case unaffected) — chain-aware
  eviction is a follow-up.

Gate: cold_cache 35/0 · typecheck exit0 · dashboard 187 tests/9 files · lint
0-err · UI build 0. (build:native's metallib floor gate fails on a known
toolchain/env hazard, independent of this branch — no shader/build files touched.)
Brooooooklyn added a commit that referenced this pull request Aug 17, 2026
…EOS union

Reviewer findings #8 and #9, verified before applying:

- convert.rs (#8, P1): when the caller omitted -m and the config declared
  the family, is_nemotron_h_ingest was true but the recipe dispatch matched
  the unchanged None model_type and skipped NemotronHRecipe::sanitize —
  saving un-repacked U8/F8 tensors and modelopt sidecars. Resolve an
  effective recipe_model_type from the config detection and use it in the
  dispatch, so a config-detected Nemotron always runs the ingest sanitizer.
- model.rs (#9, P2): extra_eos_ids() returned only config.eos_token_ids,
  but the released checkpoint declares eos 2 in config.json and {2, 11} in
  generation_config.json — EOS 11 was missed by every chat path. Now a
  UNION of both (engine contract: union, never override).
- mtp.rs test hardening: mtp_turn_runs_draft_verify_cycles panicked on the
  zero-cycle expect before its own retry check (random-weights EOS exits
  are valid); the retry is now reachable.

Verified: cargo fmt --check, cargo clippy --all-targets -D warnings,
nemotron 37/37, convert 212 clean.
Brooooooklyn added a commit that referenced this pull request Aug 19, 2026
…EOS union

Reviewer findings #8 and #9, verified before applying:

- convert.rs (#8, P1): when the caller omitted -m and the config declared
  the family, is_nemotron_h_ingest was true but the recipe dispatch matched
  the unchanged None model_type and skipped NemotronHRecipe::sanitize —
  saving un-repacked U8/F8 tensors and modelopt sidecars. Resolve an
  effective recipe_model_type from the config detection and use it in the
  dispatch, so a config-detected Nemotron always runs the ingest sanitizer.
- model.rs (#9, P2): extra_eos_ids() returned only config.eos_token_ids,
  but the released checkpoint declares eos 2 in config.json and {2, 11} in
  generation_config.json — EOS 11 was missed by every chat path. Now a
  UNION of both (engine contract: union, never override).
- mtp.rs test hardening: mtp_turn_runs_draft_verify_cycles panicked on the
  zero-cycle expect before its own retry check (random-weights EOS exits
  are valid); the retry is now reachable.

Verified: cargo fmt --check, cargo clippy --all-targets -D warnings,
nemotron 37/37, convert 212 clean.
Brooooooklyn added a commit that referenced this pull request Oct 22, 2026
…, MTP draft banks, flag purge, device-route MTP verify, draft-side levers, pack stream pool (Phase 3 + Phase 4 + Phase 5 L2) (#297)

> **Ready for review.** Stacked on #294 (`perf/qwen4-sparse-prefill`,
`912eda8c9`, 5 commits over main). Head `c1ac42df3`, rebased onto main
`61a706829` on 2026-10-22, 80 commits over #294. Stack #309: #294 → #297
→ #295, all three ready for review. The timing build is `a706d8058`
(pre-rebase). Later commits changed no mapped-path bits: the unit
digests and D3 6k were rerun on every later head (P5/X/A, P5/Z,
CLEANUP/PART2). Stage III adds L2c (MTP draft bank built at load), #8
(PLE key/value rows four per row-kernel call), #7 (mixer activation K
walk over eight simdgroups, split8) and c2 (a cold prompt runs
layer-major over the streaming pack). Text is unchanged: the same 6k /
16k shas, AR == MTP. The slot residency path now gives the same tokens
as the mapped path (P5-X), which closes the Codex Stage III finding. The
indirect expert prefill runs eagerly (closes Codex pass 2, compile-cache
growth); five MTP draft-bank tests pass on the 7 GB CI runner; the
cleanup drops the finished A/B switches and research-only tests. Stage
II (FINAL4, 2026-10-21) is ahead of llama.cpp b11717 on every decode row
and every warm or 16k prefill row. With c2 the immediate cold 6k request
drops from 11.7-12.4 s to 6.9-7.1 s, at the top of llama.cpp's 6.0-7.0 s
band. FINAL5 (2026-10-22, `a706d8058`) ran 10 timing rows + 1 trace row,
all still loaded-host (foreign GPU 31.4-44.5 % mean; one row 10.6 %).
Stage III cold 6k TTFT: AR 6.92 s (0.87x ; 0.92x, behind), MTP-2 6.92 s
(1.01x ; 0.94x, parity).

## Goal

Qwen3.8 Flash Next must run from SSD streaming on a single 128 GB Mac at
llama.cpp speed or better, with identical text and no experiment flags.

## Design in one picture

```
load:   dense banks -> MTP draft bank (L2c) -> pack stream starts (8 workers, 4 MiB preads, layer order)
cold turn over a streaming pack (c2):
        layer 0: window 1 .. window N   <- the stream reads layer 1, 2, ... meanwhile
        layer 1: window 1 .. window N      each expert bank binds once per prompt
        ...                                tail under 256 rows: its own pass after the group
warm turn / resident pack:  window-major as before (1024-token windows)
decode: mapped banks, R-row exact kernels for MTP-2 verify (#8 PLE rows, #7 split8 mixer)
```

Same windows, kernels and per-window shapes in both orders, so the bits
do not depend on the loop order (D3 group vs window: max_ulp 0).

## Result vs llama.cpp b11717 (Stage III `a706d8058`, addon
`7ac1d006e53b`, FINAL5; Stage II `9cd299141`, FINAL4)

Same machine, page cache evicted before every run (a cold request reads
the whole 73 GiB pack), one process per run, empty `MLX_*` environment,
no addon swap, 0 in-request Metal compiles in all 12 timing runs. Three
requests per process: cold 6k, 16k, warm 6k. Ranges over 2 AR + 3 MTP-2
accepted runs. llama.cpp is not re-run per round: the reference rows are
the stored clean runs of 2026-10-20 and 2026-10-21 on this machine
(`LLAMA-REFERENCE.md`); each ratio gives the 2026-10-21 row first. In
FINAL4 a foreign-load gate (> 300 % foreign CPU or a compiler alive in >
50 % of a request window) re-ran 7 attempts and kept them out of every
number.

FINAL5 (2026-10-22) adds a wired-drop gate per request, a 20 s GPU
sample before launch (idle = every sample < 10 %), and 40 s idle after
the last turn with the process loaded.

Caveat for Stage III: 0 of 10 rows had an idle GPU (foreign GPU mean
31.4-44.5 %, one row 10.6 %); vm pressure normal and thermal nominal on
every sample; 3 load-gate reruns (OrbStack, a foreign rustc, Firefox +
XProtect), each rerun passed all gates.

| Metric | Stage III (FINAL5), range (mean) | Stage II (FINAL4) | Stage
I (`9a8d1e220`) | llama.cpp AR (`FINAL4-llama-off-1` ;
`FINAL3-llama-off-1`) | llama.cpp MTP-2 (`FINAL4-llama-on-1` ;
`FINAL3-llama-on-2`) | Stage III ratio (2026-10-21 ref ; 2026-10-20 ref)
| Stage II ratio (2026-10-21 ref ; 2026-10-20 ref) |
|---|---|---|---|---|---|---|---|
| Warm 6k prefill, tok/s | AR 1,323.7-1,360.7 (1,342.2); MTP
1,201.8-1,285.0 (1,254.5) | AR 1,197-1,215; MTP 1,231-1,298 | AR
1,112-1,161; MTP 1,116-1,241 | 896 ; 853 | 843 ; 852 | AR **1.50x ;
1.57x**, MTP **1.49x ; 1.47x** | AR **1.35x ; 1.41x**, MTP **1.50x ;
1.48x** |
| 16k prefill, tok/s | AR 1,107.0-1,139.0 (1,123.0); MTP 1,079.6-1,116.9
(1,094.0) | AR 1,086-1,122; MTP 985-1,103 (1,070-1,103 without the
host-event row, see gaps) | AR 909-1,001 (both rows disturbed by foreign
load); MTP 1,088-1,146 | 946 ; 872 | 863 ; 907 | AR **1.19x ; 1.29x**,
MTP **1.27x ; 1.21x** | AR **1.17x ; 1.27x**, MTP **1.22x ; 1.16x** |
| Cold 6k prefill, tok/s | AR 897.5-899.8 (898.6); MTP 897.6-900.0
(899.1) | AR 539-541; MTP 515-521 | AR 473-476; MTP 442-459 | 1,034 ;
975 | 889 ; 955 | AR 0.87x ; 0.92x (behind), MTP 1.01x ; 0.94x (parity)
| AR 0.52x ; 0.55x, MTP 0.58x ; 0.54x |
| AR decode, steady tok/s (cold 6k / 16k / warm 6k) | 48.09-49.55 /
47.42-48.69 / 49.79-50.87 (48.82 / 48.05 / 50.33) | 52.5-55.0 /
51.2-52.3 / 52.5-53.4 | 51.2-51.8 / 44.0-49.7 / 50.4-51.7 | 45.0 / 43.5
/ 43.6 ; 42.0 / 40.7 / 42.6 | – | **1.08x / 1.10x / 1.15x ; 1.16x /
1.18x / 1.18x** (worst run 1.07 / 1.09 / 1.14 ; 1.14 / 1.16 / 1.17) |
**1.19x / 1.19x / 1.21x ; 1.28x / 1.27x / 1.24x** |
| MTP-2 decode, steady tok/s (cold 6k / 16k / warm 6k) | 73.71-74.12 /
70.38-71.61 / 74.72-75.68 (73.97 / 70.95 / 75.28) | 72.7-78.4 /
75.9-76.6 / 77.5-79.8 | 74.0-76.3 / 70.5-74.8 / 73.8-79.0 | – | 72.0 /
67.6 / 68.7 ; 71.7 / 69.4 / 71.5 | 1.03x / 1.05x / **1.10x** ; 1.03x /
1.02x / **1.05x** (worst run 1.02 / 1.04 / 1.09 ; 1.03 / 1.01 / 1.04) |
**1.05x / 1.13x / 1.15x ; 1.05x / 1.10x / 1.10x** (worst run 1.01 / 1.12
/ 1.13) |
| Cost per step, ms (AR step / MTP-2 cycle) | 20.4 / 36.6 | 18.9 / 34.9
| 20.1 / 35.2 | 22.7 ; 23.9 | 39.4 ; 38.6 | AR 1.11x ; 1.17x, MTP 1.08x
; 1.06x | |
| 16k TTFT, per request | AR 16.47-16.94 s (16.70); MTP 16.79-17.37 s
(17.15) | AR 16.7-17.3 s; MTP 17.0-19.1 s | AR 18.7-20.6 s; MTP
16.4-17.2 s | 19.8 ; 21.5 s | 21.7 ; 20.7 s | **1.19x ; 1.29x** /
**1.27x ; 1.21x** faster | **1.17x ; 1.27x** / **1.22x ; 1.16x** faster
|
| Cold 6k TTFT, per request | AR 6.91-6.93 s (6.92); MTP 6.91-6.93 s
(6.92) | AR 11.50-11.54 s; MTP 11.94-12.08 s | AR 13.1-13.2 s; MTP
13.6-14.1 s | 6.01 ; 6.38 s | 7.00 ; 6.51 s | AR 0.87x ; 0.92x (behind),
MTP 1.01x ; 0.94x (parity) | 0.52x ; 0.55x / 0.58x ; 0.54x |
| Warm 6k TTFT, per request | AR 4.57-4.70 s (4.63); MTP 4.84-5.17 s
(4.96) | AR 5.12-5.20 s; MTP 4.79-5.05 s | | 6.94 ; 7.30 s | 7.38 ; 7.30
s | AR **1.50x ; 1.58x**, MTP **1.49x ; 1.47x** | |
| Cold 6k TTFT, request 8 s after load (1 run per arm) | AR 6.94 s; MTP
6.16 s | AR 7.38 s; MTP 8.41 s | not run | 6.01 ; 6.38 s | 7.00 ; 6.51 s
| AR 0.87x ; 0.92x, MTP **1.14x ; 1.06x** (1 run, lighter foreign GPU:
10.6 %) | 0.81x ; 0.86x / 0.83x ; 0.77x |
| Cold 6k TTFT, from load start | AR 9.73-9.94 s (9.83); MTP 9.74-9.89 s
(9.81) | AR 13.7-14.0 s; MTP 14.0-14.3 s | 15.1-15.2 / 15.5-16.1 s |
36.1 ; 34.4 s | 39.1 ; 35.6 s | AR **3.67x ; 3.50x**, MTP **3.98x ;
3.62x** faster | **2.5-2.6x / 2.5-2.8x faster** |
| Peak footprint | AR 10.7-12.1 GiB; MTP 11.3-12.1 GiB (L2c bank in both
arms) | AR 7.9-9.2 GiB; MTP 11.3-11.4 GiB | 7.9-9.2 / 11.4-11.7 GiB |
1.5-1.6 GiB footprint + 78 GiB mmap | 2.4-2.5 GiB + 82 GiB mmap | | |
| 16k + 40 GiB touching hog, MTP-2 | not run in FINAL5 (c2 gates: slots
225, 64/64) | completes 64/64 on the slot fallback (174 slots at 54.6
GiB available; 11.0 tok/s, 39/46 drafts accepted) | 64/64 (218 slots,
14.7 tok/s) | not run | | | |

- Text is identical in every run, AR == MTP (6k `bfb8e8bb3bd0c768`, 16k
`6a63463a98644df6`); none of the Stage II changes moved one token. MTP-2
acceptance 0.823 -> 0.847 (2.656 -> 2.684 tokens per cycle; by position
0.905 / 0.787 at 6k, 0.926 / 0.766 at 16k). FINAL5: the same two shas on
all 30 requests of the 10 rows, MTP 95 / 189 / 160 on every MTP request,
the same acceptance by position.
- Stage III vs llama: ahead on warm 6k and 16k prefill / TTFT in both
arms and on AR decode (1.08-1.18x). MTP-2 decode: cold 6k and 16k parity
(1.03x ; 1.03x and 1.05x ; 1.02x), warm 6k ahead (1.10x ; 1.05x). Cold
6k TTFT: AR behind (6.91-6.93 s = 0.87x ; 0.92x, llama 6.01 ; 6.38 s),
MTP-2 parity (1.01x ; 0.94x).
- Stage II -> Stage III (FINAL4 -> FINAL5): cold 6k TTFT AR -39.9 % /
MTP -42.3 %; warm 6k TTFT AR -10.2 %. AR decode 7-9 % lower (cold 6k
-9.2 %, 16k -7.1 %), MTP-2 16k decode -7.1 %; AR step 18.9 -> 20.4 ms,
MTP cycle 34.9 -> 36.6 ms. Load AR +25.1 %, MTP +34 % (L2c builds the
bank at load). AR peak +2.5-2.9 GiB (the AR arm holds the 2.83 GiB MTP
bank). The decode drop is open (see gaps).
- Stage I -> Stage II under the same protocol: cold 6k TTFT -1.6 s (AR)
/ -1.9 s (MTP), MTP-2 decode +0.3 / +4.3 / +2.3 %, MTP cycle 35.2 ->
34.9 ms, load 2.0 -> 2.3 s (the pack stream starts at load). The AR 16k
and AR decode differences come from foreign load on the Stage I rows,
not from code.
- Wired memory: Stage II 87-91 GiB in a turn, 6-8 GiB within 5-55 s
after exit (all 8 mapped runs). Stage III (FINAL5): 87.6-90.6 GiB in a
turn, 6.7-7.3 GiB 1 s after exit, 6.7-7.4 GiB at turn end + 35 s with
the process loaded (no hold).

## Phase 5 Stage III (`c2e7bba65`, `2fc0426c5`, `ca51f4692`,
`bfa046494`, `a41bf6a7a`, `2e12d1beb`, `3bdca3614`, `8cfc05371`,
`e98d4c733`, `0df94ece6`, `142cff3e0`, `734430a6f`, `299b4defb`,
`071588e44`, `12f7fdb74`, `3c0d8a5a1`)

Headings and commit columns name commits at `3c0d8a5a1`. Result rows
name the measured pre-rebase trees: L2c `313430e52`, #8 `4e7b3608b`, #7
`52611c9d2`, c2 `829f474cf` / `57512c0b9` / `748389987`, T11
`a706d8058`, P5-X `a95cb2492` / `1b90c2e62`, Stage II `9cd299141`, Stage
I `9a8d1e220`.

All timing below is loaded-host (foreign GPU ~40 % mean before launch;
the GPU-idle rule failed on every row, FINAL5 included). Rows marked
REJECT also failed the CPU load gate. Text shas 6k `bfb8e8bb3bd0c768` /
16k `6a63463a98644df6` on every mapped run, AR == MTP, MTP 95 / 189 /
160 on every request.

| Commit | What | Measured effect (run tag) |
|---|---|---|
| L2c `c2e7bba65` | The Q8 MTP draft bank (2.83 GiB) is built at load,
after the dense banks and before the pack stream. No turn builds
anything. A declined build warns and the load goes on. | MTP request 8 s
after load: 6k TTFT 8.41 -> 7.32 s, request SSD 5.77 -> 1.07 GiB. MTP
immediate: 11.94-12.08 -> 11.62 s, request SSD 77.2 -> 72.5 GiB (FINAL4
MTP rows -> `L2C-after-d8-on-1`, `L2C-after-on-1`, both loadcheck OK).
Cost: with the aux attached the AR arm also holds the 2.83 GiB bank and
reads 4.7 GiB more at load (+0.5-1.0 s load). |
| #8 `2fc0426c5` | A prefill window projects PLE key and value through
the exact row kernel in 4-row groups (256 calls per 1024-token window)
instead of one M=1 gather GEMV per token. MTP verify projects all rows'
PLE in one call. | 16k TTFT AR 17.50 -> 17.08 s (last interleaved pair),
MTP 17.68-17.95 -> 17.40-17.47 s; warm 6k TTFT AR 4.97 -> 4.57 s, MTP
4.86 -> 4.60 s (`PLEHC-*`, see the table below). Bit-identical: probe
B-8 0 differing values; 2 new bitwise tests. |
| #7 `ca51f4692` | The decode mixer activation (HC down, Q8 320 x 10240)
runs eight simdgroups per output. Each stores its block terms; simdgroup
0 adds all 40 in the old order. The partial-sum form is not exact and is
not used. | MTP-2 decode 70.65 -> 71.51 tok/s, cycle 38.15 -> 37.71 ms
(ranges do not overlap). AR decode 49.17 -> 49.39 tok/s: ranges overlap,
not measurable (`PLEHC-*`). Kernel alone: 12.21 / 18.25 -> 10.37 / 11.79
us at 1 / 3 rows (probe B-7, 0 differing values). |
| c2 engine `bfa046494` | The scheduler can give a cold turn one
whole-prompt prefill step (per-family hook, default off). A K/V write
entry takes chunks anywhere above a recorded floor; the strict suffix
entry stays. Row fetch: 32 readers (was 4), pending limit 1 << 20 (was 1
<< 16). | Enables c2; no timing on its own. |
| c2 qwen4 `a41bf6a7a` | A turn that opens over a streaming mapped pack
prefills as one group: every 1024-token window at layer 0, then at layer
1, and so on. A trip between sweeps evaluates the group first, then
leaves the mapped path. | Immediate cold 6k AR 12.43 / 16.03 -> 6.98 /
7.05 s, MTP 11.73 / 11.94 -> 7.09 / 6.89 s (`C2G-G1*`, `C2G-G1b*`).
Rebased head: AR 6.93 s, MTP 6.94 / 6.90 s (`C2INT-*`). See the c2
table. |
| c2 tests `2e12d1beb` | New unit tests in tests.rs (8), weights.rs (2),
scheduler.rs, hybrid_scheduler.rs and paged_kv_cache_adapter.rs; 2
real-model tests (T10 group == window at a time, T11 forced trip), D3
goes through the group path, docs. `draft_history_appends_in_place` now
synchronizes after each eval (it failed 25 of 500 runs on a loaded host,
0 of 500 after). | D3 cold 6k / 16k as one group: 256 / 256,
group-vs-window max_ulp 0. T10 6k: 221 arrays byte-equal (`C2INT` d3 /
t10 logs). |
| T11 `3bdca3614` | The forced-trip test no longer compares a slot run's
text with the mapped reference (a slot run's text follows its slot count
and resident expert set). It keeps the structural asserts on the switch
and reruns the prompt on the same decoder, now on slots, printing both
texts. | Passes at slots 454 and 461. The two trees `6d86a6ad8` and
`748389987` give the same tripped text and the same plain-slot text at
454 slots, so #8 / #7 do not change the bits after a trip
(`P5/C2/T11X`). P5-X below makes slot text equal to the mapped text. |

Op trace (`FINAL5-trace-on-1`, MTP-2, traced addon `7709d2ec79eb`, not a
timing row): PLE GatherQMM count 0 at `a706d8058` (104 at `234f4bdd1`);
expert-bank GatherQMM 663. The 2560x2560 dense-decode kernels are not
attributed to a projection.

### c2: immediate cold 6k request (every cold request reads the whole 73
GiB pack)

| Arm | before (`313430e52` addon) | after (`85874b357` addon) | rebased
head (`748389987` addon) | llama.cpp b11717 reference (2026-10-21 ;
2026-10-20) |
|---|---|---|---|---|
| AR, req0 TTFT | 12.43 s (REJECT) / 16.03 s (REJECT) | **6.98 / 7.05
s** (both OK) | **6.93 s** (OK) | 6.01 s (`FINAL4-llama-off-1`) ; 6.38 s
(`FINAL3-llama-off-1`) |
| MTP-2, req0 TTFT | 11.73 s (OK) / 11.94 s (REJECT) | **7.09 s**
(REJECT) / **6.89 s** (OK) | **6.94 / 6.90 s** (rows REJECT, req0
passed) | 7.00 s (`FINAL4-llama-on-1`) ; 6.51 s (`FINAL3-llama-on-2`) |
| Speed vs llama (llama TTFT / ours) | AR 0.48x ; 0.51x (12.43 s row) |
AR 0.85-0.86x ; 0.90-0.91x; MTP 0.99-1.02x ; 0.92-0.94x | AR 0.87x ;
0.92x; MTP 1.01x ; 0.94x | |
| From load start (load + req0 TTFT) | AR 16.0 s; MTP 14.6 s (12.43 /
11.73 s rows) | AR 10.2 s; MTP 9.8-10.7 s | AR 10.0 s; MTP 9.8-9.9 s |
AR 36.1 ; 34.4 s, MTP 39.1 ; 35.6 s (FINAL4 table) |
| Request SSD | 71.5-72.4 GiB | 71.9-72.3 GiB | 72.3 GiB | 0.87 GiB
(llama reads the 78-82 GiB GGUF at load) |

- From load start we lead: AR 3.4-3.6x, MTP-2 3.3-4.0x faster than the
llama rows. FINAL5: AR 9.73-9.94 s = 3.67x ; 3.50x, MTP-2 9.74-9.89 s =
3.98x ; 3.62x.
- Per request we are at the top of llama's band: MTP-2 at parity, AR
8-15 % behind, on a loaded host.
- Other cold cases, after arm (`C2G-G2*`, `C2G-G8*`): request 3 s after
load AR 5.95 / 6.63 s (before 8.81 s; all three REJECT); request 8 s
after load AR 7.37 -> 6.96 s, MTP 7.00 -> 6.87 s; cold 16k as the first
request 16.92 s vs llama 19.82 ; 21.52 s (1.17x ; 1.27x faster).
- GATES held: G1 bar 8.0 s met by 0.95-1.02 s; wired back to 6.6-7.8 GiB
after exit on every row; load 2.81-3.56 s inside the before range.

### #8 + #7: one interleaved A/B (`PLEHC-*`, before `313430e52` addon,
after `52611c9d2` addon, loadcheck-OK rows only)

| Mode | Metric | before mean (n) | after mean (n) | after - before |
before range | after range |
|---|---|---|---|---|---|---|
| AR | 16k TTFT s | 18.09 (3) | 17.28 (2) | -0.82 | 17.50-18.98 |
17.08-17.47 |
| AR | 16k prefill tok/s | 1,037.8 (3) | 1,085.7 (2) | +47.9 |
988.3-1,071.8 | 1,073.7-1,097.7 |
| AR | warm 6k TTFT s | 4.97 (3) | 4.57 (2) | -0.40 | 4.68-5.18 |
4.53-4.61 |
| AR | decode tok/s (mean req0-2) | 49.17 (3) | 49.39 (2) | +0.22
(overlap) | 48.96-49.54 | 49.05-49.73 |
| MTP-2 | 16k TTFT s | 17.81 (2) | 17.44 (2) | -0.38 | 17.68-17.95 |
17.40-17.47 |
| MTP-2 | 16k prefill tok/s | 1,052.9 (2) | 1,075.5 (2) | +22.6 |
1,045.1-1,060.7 | 1,073.3-1,077.6 |
| MTP-2 | warm 6k TTFT s | 4.86 (2) | 4.60 (2) | -0.26 | 4.71-5.00 |
4.58-4.63 |
| MTP-2 | decode tok/s (mean req0-2) | 70.65 (2) | 71.51 (2) | +0.86 |
70.38-70.93 | 71.44-71.58 |
| MTP-2 | ms per cycle | 38.15 (2) | 37.71 (2) | -0.45 | 38.00-38.30 |
37.67-37.75 |

- The AR 16k mean includes a slow before row (18.98 s); the last
interleaved pair is -0.41 s. Per PLE window that is -19.7 ms (MTP) /
-21.7 ms (AR) over 19 windows.
- At the rebased head (`C2INT-after-off-1`, loadcheck OK): AR 16k TTFT
17.30 s, 16k prefill 1,083.8 tok/s, decode 48.24 tok/s, all within 2.3 %
of the better parent. The two MTP rows at the head are REJECT (foreign
compiles): 16k TTFT 18.14 / 19.15 s, decode 67.45 / 71.31 tok/s; not
counted.
- The decode tok/s here is the mean of each request's decode rate, not
the steady rate of the Stage II table.

### P5-X: slot path == mapped path bits

| Commit | What |
|---|---|
| `8cfc05371` test | `slot_groups_match_the_whole_window_bit_for_bit`:
slot groups on capacity-row banks vs the whole 512 bank, bf16 value for
value. T11 asserts tripped == plain == reference. |
| `e98d4c733` fix | `ExpertKernel::for_window` picks the kernel class
once per window; every slot group uses it. Hosts keep shape guards and a
1..=65536 row range. |
| `0df94ece6` fix | `route_sort` takes 1..=65536 rows (was 256..), so a
Tiles group of any size runs `prefill_indirect`. |

Root cause: a slot run splits a window's experts into groups of
`capacity` (454, 461, ...). The kernel class was chosen per group from
its rows and the bank's rows, so a remainder group under 4 rows per slot
fell from NAX tiles to QMV (gemv / gather_qmv). QMV sums K over 32 lanes
with `simd_sum`; NAX accumulates K in BK steps in `matmul2d`; the bits
differ. The mapped path runs one indirect call over all 512 experts. The
remainder set follows the slot count, so the slot text did too.

```
ExpertKernel::for_window(rows, 512)   // rows = window tokens x 10; 512 = model experts, not bank rows
  256 <= rows <= 65536 && rows / 512 >= 4  -> Tiles   NAX prefill_indirect, every group
  rows > 80                                -> Gather  sorted rows, gather_qmv (right_sorted = false)
  else                                     -> Rows    expert_rows gemv
```

Mapped windows keep their class (<= 80 Rows, 81-2047 Gather, >= 2048
Tiles before and after).

| Check | Result |
|---|---|
| `slot_groups_match_the_whole_window_bit_for_bit`, 21 splits (windows
1024 / 2000 / 200 / 75 / 20 tokens; capacities 454, 461 and one per
remainder band) | 13 differ before the fix, 0 after |
| Whole-bank FNV digests, old tree vs new tree | unchanged:
`61699f30731fef84`, `945858c1ffd5b137`, `42e2d760d60b10cd`,
`dcf1e56baefe4fb0`, `de18448f7e14176a` |
| D3 cold 6k / 16k, mapped 512 | 256 / 256, max_ulp 0 |
| T11 6k | tripped == plain == reference `[22916, 310, 635, ...]` at
slots 427 / 420 / 277 |
| T10 6k | 221 arrays byte-equal |
| Scoped `models::qwen4_exp` | 242 pass / 0 fail / 11 ignored |
| `cargo clippy -p mlx-core --all-targets`, `cargo fmt --check` | clean
|

- Real-model rows ran on the pre-rebase trees (`a95cb2492`; T11 at 277
slots on `81ea6f965`). The rebase is 3 x `=` in range-diff with an empty
qwen4 / mlx-sys diff. D3 6k, the unit gates and the digests were rerun
on the rebased P5-X head and on every later head.
- Timing: interleaved T11, old vs new binary on the same loaded host,
plain slot prefill new / old = 1.23x then 0.91x: NOISE. No mapped window
changed kernel class. No further slot-mode timing (P5-Y stopped, see
gaps).
- Codex Stage III finding (slot path bits): closed by `e98d4c733` +
`0df94ece6`; the Codex thread is resolved with the commits.

### Compile cache and CI fixes (`142cff3e0`, `734430a6f`)

- **Codex pass 2 (medium): compile-cache growth.**
`qwen4_indirect_prefill` ran through `mlx::core::compile`, which keeps
one trace per input shape and never evicts. Each trace holds its own
copy of the two kernel sources, ~309 KB (estimated from the measured
148,980 B header). P5-X sends the slot remainder groups to this path
too, so one 32k prompt at 454 slots makes 542 keys instead of 271
(Codex's harness, reproduced), and 814 after 4 prompts. The wrapper and
the base growth come from main (#154); the doubling is ours.
- **Fix `142cff3e0`:** the indirect expert prefill runs eagerly. Its
graph is two custom kernels with nothing to fuse, so the bits are the
same by construction (an earlier eager arm was also exact at D3 6k /
16k). 1 file, +3 / -7. Unit digests unchanged, scoped 242 / 0 / 11, D3
6k 256 / 256, max_ulp 0. The Codex bot found nothing on the fixed head.
- Out of scope: the dense prefill wrapper on main
(`qwen4_dense_prefill_dispatch`) has the same growth, one key per
distinct window length. Left for a separate item.
- **CI `734430a6f`:** five MTP draft-bank tests failed on the 7 GB
macos-26-arm64 runner. The fixture load asks for the fixed 4 GiB
first-request working reserve (`WORKING_BYTES`), not for its few-KB
bank; the runner had 2.7 GiB free. Production degrades as designed (warn
and load on). Test-only fix: fixture helpers pass an always-yes
admission; the decline calls pass one that panics, so the decline still
comes before any host admission. On a simulated 7 GB host: old tests 0 /
5 with the CI message, new 5 / 5, scoped 242 / 0 / 11. CI green on
`e3503adc0` (this commit before the final rebase).

### Cleanup (`299b4defb`, `071588e44`, `12f7fdb74`, `3c0d8a5a1`)

- The four decoder A/B switches (`batch_prefill`, `window_carry`,
`async_prefill`, `batch_rotary`) are gone with their losing arms. The
prefill oracles now compare against `step()`; the rotary test is
bit-exact against per-row `rope`.
- `fold_rows` is gone, with the research-only tests (row-batched GPU
time, forced-stream acceptance, two fold-cost timings).
- D3 is cut to the greedy expected-argmax gate:
`real_model_greedy_argmax_matches_expected`. Env vars renamed: `D3_*` /
`T10_CASE` -> `QWEN4_EXP_REAL_STEPS` / `_CASES` / `_EXPECTED` / `_OUT`
(documented in `docs/qwen38-flash-next.md`).
- Phase labels, mutation codes, dates and shas are stripped from
comments. Docs corrected: 73 GiB pack, 32 readers, cache paths.
- Gates (on `4455353de`, this stack before the final rebase; the rebase
diff is the openai bump only): scoped 239 / 0 / 9. The delta from 242 /
0 / 11: 2 passing tests removed, 1 moved to ignored (release
microbenchmark), 3 ignored research tests removed. Clippy, fmt and
typecheck clean; unit digests unchanged; D3 6k `EXPECTED OK: 256
positions`, mapped 512.

## Phase 4 Stage II + Phase 5 L2 + v3 pack policy (`e00bb6e3f`,
`f6a35ca4c`, `9f52a1c3d`, `29bff1850`, `67fe0f15c`, `32e7a3faa`,
`5a7c5fdea`, `c003150d0`)

| Step | Change |
|---|---|
| M3 `e00bb6e3f` | A draft pass submits the attention hyper-connection
rows and their injection gate as soon as they exist, so the GPU starts
while the host builds the rest of the pass. Same graph and kernels.
Propose wall at 6k 4.86-5.17 -> 4.75-4.80 ms. |
| C5 `f6a35ca4c` | The draft K/V history is a capacity buffer written in
place instead of six full-history concatenations per MTP cycle (12 MiB
each at 6k). Cache clones share the buffer and keep their own row
counts. Draft GPU per cycle 6k 4.21 -> 4.04 ms, 16k 4.54 -> 4.14 ms. |
| L2 `9f52a1c3d` | Stream pool: eight workers read the whole pack with 4
MiB buffered preads in layer order (12.3 GiB/s over the evicted pack;
the old depth-3 walker did 9.3), kernel read-ahead off, one `mincore`
per file to skip resident chunks. The stream starts at load after the
dense banks and at any turn over a pack that is not fully resident; it
yields to the model's row reads and stops within one chunk on the switch
to slots or on unload. Cold 6k TTFT -1.6..-1.9 s; a request 8 s after
load reaches 7.4 s. |
| L3 `29bff1850` | The draft head normalizes the target hidden per
hyper-connection stream (as the target's own `hc_norm` and llama.cpp's
MTP graph do) instead of one RMS over the joined streams (mlx-vlm's
drafter). Teacher-forced on llama.cpp's committed text it reproduces
llama's per-position acceptance (0.914, 0.817); f32 head / router, f16
draft K/V and a zero first row moved nothing. Draft side only: verify
path and committed text unchanged. |
| B1 `67fe0f15c` | Test only: fixture GGUF loads in unit tests resolve
to a fresh temp root instead of
`~/Library/Caches/mlx-node/qwen4-packed`, so `cargo test` no longer
sweeps the developer's real cache; a regression test with a fake HOME
proves it. Codex: approve. |
| v3 policy `32e7a3faa` `5a7c5fdea` | Pack identity no longer includes
`st_dev`, so a volume renumber keeps the 73 GiB pack. The manifest
records the canonical path and the mount point of every source file. A
pack is removed only on proof: its source is present with another
fingerprint, or a source file is gone from a volume that is mounted. An
unmounted or unreadable source keeps the pack. A real-model load after
the change reused all 144 files and matched the shas. |
| manifest fix `c003150d0` | Codex S2 (medium): a truncated `.manifest`
read as a fingerprint change and deleted a healthy pack. The manifest
ends with an `end=<hex file count>` record and is written to
`.manifest.tmp` then renamed; a manifest without a valid end record is
incomplete and keeps its pack; the load heals the opened pack's manifest
and no other. 4 mutations red, module tests 223/0, real-model load
reused the pack and healed its manifest with the shas unchanged. |

## Phase 4 Stage I: MTP-2 cycle (`fffd47666`, `98861f447`, `f765187d9`)

Warm 6k MTP-2 cycle 50.6 -> 37.8 ms in the quiet A/B (-25 %); traced
cycle 33.1 ms = draft 2.5 + 2.3 + verify 28.0 + accept/commit 0.3.

| Step | Change |
|---|---|
| A1 `98861f447` | On the mapped pack the verify pass keeps its routes
on the device: one route tape joined into the final eval and one
readback replace 48 per-layer GPU-to-host waits; the tripwire is told
after the route commit. Slot mode keeps the host routes. Real-model
test: 32 three-row verifies match the AR step bit for bit. |
| M1 `f765187d9` | The MTP gate_up draft bank keeps its scales and
biases as f32 copies, so `gather_qmm` no longer casts 2 x 52.4 M values
on every draft; the f16 layout stays where the f32 one does not fit the
mapped charge or the slot allowance. |
| v2 retire `fffd47666` | Legacy `.mlx-qwen4-packed-v2-<64 lowercase
hex>` directories are removed at load once idle for 1 h and their
`budget` lock is free. |

## What Phase 3 adds

| Step | Change |
|---|---|
| M5 | Mapped-or-slots chosen at load from live memory (wired +
compressor + anonymous), byte budget exported; thrash tripwire (SSD
reads > 2x mapped bytes, or 8 slow passes); decoded-row LRU
byte-bounded; no "free memory" advice, no override flag |
| M6 | A tripped turn leaves the mapped path at that pass and finishes
on slots (13 min -> 50 s under a 40 GiB hog); gate maps while live
non-reclaimable <= 42.85 GiB; slot fallback sized after the compressed +
swapped debt |
| D3 | Same-process teacher-forced A/B of every fusion/schedule flag:
none beats the noise band; decode is weight-stream bound; 21 flags and
their kernels deleted |
| S3-S6 | MTP verify runs the R draft rows layer by layer with shared
weight reads; Q8 g32 draft expert bank for the MTP head; draft prefill
merged into the first draft pass; 16k MTP admission counts only KV pages
|
| K16 | Prefill QSA kernel serves two GQA heads per K/V read (-14 %,
bit-identical) |
| INT2 | Integration; fixes the S3 regression that sent prefill through
the row-exact R <= 4 wrappers (1.58 M single-row GEMV dispatches per 6k
prompt -> 9.5 k) |
| C1 | Flag purge: 89 `MLX_QWEN4_*` names, the runtime flag module, the
residency selection knobs and the v2 per-expert chunk cache are gone;
one code path |
| Review fixes | Slot sizing keeps room for MTP draft banks
(`163a0f9c1`, `6698e47b6`) |

## How to verify

Cleanup head = `4455353de` (`3c0d8a5a1` before the final rebase).

| Check | Command or test | Result at |
|---|---|---|
| Scoped unit tests | `cargo test -p mlx-core --lib models::qwen4_exp` |
248 run / 239 pass / 0 fail / 9 ignored (cleanup head) |
| | `cargo test -p mlx-core --lib engine::scheduler` /
`engine::hybrid_scheduler` / `transformer::paged_kv_cache_adapter` |
26/26, 51/51, 174 run / 170 pass / 4 ignored (`a706d8058`) |
| Bitwise tests (`--exact`) |
`ple_projection_row_kernel_matches_gather_and_single_rows_bit_for_bit`,
`ple_window_runs_four_rows_per_row_kernel_call_bit_for_bit`,
`mixer_act_split_keeps_the_one_simdgroup_chain_bit_for_bit`,
`row_batched_decode_kernels_match_single_row_calls_bit_for_bit`,
`a_group_of_windows_matches_one_window_at_a_time_bit_for_bit` | each 1
passed (P5-X); in the scoped run on every later head |
| Slot == mapped (`--exact`) |
`slot_groups_match_the_whole_window_bit_for_bit` | 21 / 21 splits equal
(13 differed before the fix); 5 whole-bank digests unchanged (P5-X,
P5-Z, cleanup head) |
| Kernel class rule (`--exact`) |
`expert_kernel_follows_the_window_not_the_bank` | ok (P5-X, P5-Z,
cleanup head) |
| Lint | `cargo clippy -p mlx-core --all-targets`, `cargo fmt --check`,
`yarn typecheck`, `vp fmt --check docs/qwen38-flash-next.md` | clean
(cleanup head) |
| Real model, exactness (ignored tests; `QWEN4_EXP_REAL_MODEL`,
`QWEN4_EXP_REAL_INPUTS`, `QWEN4_EXP_REAL_CASES`,
`QWEN4_EXP_REAL_EXPECTED`; page cache evicted first) |
`real_model_greedy_argmax_matches_expected` | cold 6k `EXPECTED OK: 256
positions`, mapped 512 (cleanup head, P5-Z); cold 6k / 16k as one group
256 / 256, max_ulp 0 (`a706d8058`, P5-X) |
| Real model, group vs windows |
`real_model_group_matches_window_at_a_time_on_a_cold_pack` | 221 arrays
byte-equal (`a706d8058`, P5-X) |
| Real model, trip |
`real_model_forced_trip_between_sweeps_switches_after_the_frontier_eval`
| asserts tripped == plain == reference, plus commit -> frontier -> trip
-> switch order, store off the mapped path, stream gone, fallback index
0, history == prompt; passes at slots 427 / 420 / 277 (P5-X trees) |
| Real model, text | R0 benchmark, cold 6k + 16k + warm 6k, 256 tokens,
AR and MTP-2 | shas `bfb8e8bb3bd0c768` / `6a63463a98644df6` on every
request, AR == MTP, MTP 95 / 189 / 160 (`a706d8058`) |
| FINAL5 measurement | `FINAL5/driver.sh` + `FINAL5/trace.sh` (research
dir), R0 benchmark, page cache evicted per run | 10/10 timing rows + 1
trace row; the same 6k / 16k sha on all 30 requests (`rows-all.txt`), AR
== MTP; mapped/512 on every row; wired-drop gate 10/10 (largest fall 4.3
GiB); MTP c/d/a 95/189/160 on every MTP request (`a706d8058`) |

## Known gaps and open items

- **FINAL5 still loaded-host.** 0 of 10 rows had an idle GPU (foreign
GPU mean 31.4-44.5 %, one row 10.6 %). Interleaved A/B deltas hold;
absolute rows carry the caveat. The trace row is above (op trace).
- **Decode below Stage II.** AR decode 7-9 % and MTP-2 16k decode 7.1 %
below Stage II on every Stage III loaded-host row since `313430e52`.
Cause not separated: the L2c bank in the AR arm vs foreign GPU load. The
interleaved Stage II vs Stage III A/B (P5-Y) was stopped at the user's
request after 5 rows, with no analysis.
- **Cold 6k per request, AR, behind.** 6.91-6.93 s vs llama 6.01 ; 6.38
s = 0.87x ; 0.92x (FINAL5, loaded host). MTP-2 is at parity (1.01x ;
0.94x). From load start: AR 3.67x ; 3.50x, MTP-2 3.98x ; 3.62x faster.
- **#7 on AR.** The AR gain (target -0.5 ms per step) is below the
noise; only the MTP-2 decode delta separates.
- **c2 follow-ups, accepted and not coded:** SF2 (the row queue's
`take()` scans under the lock; late rows 995-1,698 per cold 6k request;
trace the wait first), SF3 (no cadence trace; the 3-layer submit cadence
stays), SF4 after-trip half (the 1024-row window is not re-sized after a
switch; every growing byte is still admitted; tight host untested), SF5
native-state half (a failed group's lazy tail costs the next request GPU
time, not bits).
- **Slot-mode prefill timing.** Not measured on a quiet host with the
window kernel class rule. The only pair (T11, loaded host) is NOISE.
- **Dense prefill compile cache (out of scope).** The dense prefill
wrapper on main (`qwen4_dense_prefill_dispatch`) keeps one compile trace
per distinct window length, the same growth as the indirect one fixed
here. Left for a separate item.
- **MLX fork item.** The Synchronizer's `retain_inputs` keeps an eval's
output buffers until its completion handler runs, so `append_draft_kv`
can copy instead of writing in place. It is a copy, never a wrong value.
- **First launch after a kernel change** pays in-request Metal compiles
once (AR 1.07 s + 0.07 s, MTP 24 compiles in the first process per
mode); 0 from the second process on.
- **MTP 16k prefill spread.** Slow MTP 16k rows trace to a host event:
40-55 GiB of wired memory released and re-taken within 1-3 s
mid-prefill, GPU to ~18 %. FINAL5's wired-drop gate passed 10/10
(largest fall 4.3 GiB); no host-event row this time.
- **Busy posture.** Above ~43 GiB of live non-reclaimable memory from
other apps the load picks the slot path, which is ~5x slower (11-15
tok/s MTP-2 decode); it completes, it does not crash or thrash. c2 hog
row (40 GiB hog, 16k, MTP-2): slots 225, 64 / 64 tokens.
- Pre-existing: kquant golden gate fails on the g17s/g17d/g17g NAX
routes at the base pin (identical bits on the source and prebuilt
builds).

## Submodule

`crates/mlx-sys/mlx` -> fork branch `fn-d1` (`e68b9ba77`: two patches on
`bcad39304`). `mlx-prebuilt.json` pins the matching prebuilt release
`mlx-prebuilt-e68b9ba778fc-6d601cad`; golden gates are digest-identical
between the source and prebuilt builds. Stage III does not move the pin;
#7's kernel is a new
`crates/mlx-sys/src/metal/qwen4/mixer_act_decode.metal.inc`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
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.

2 participants