Skip to content

perf(cache,tokenizer,qwen3_5,dashboard): cross-session SSD prefix anchors, BPE drift history, and Qwen3.5 scheduled turn-end states - #459

Merged
Brooooooklyn merged 2 commits into
mainfrom
perf/ssd-prefix-anchors
Dec 1, 2026
Merged

Brooooooklyn merged 2 commits into
mainfrom
perf/ssd-prefix-anchors

Conversation

@Brooooooklyn

Copy link
Copy Markdown
Contributor

Summary

Eliminates unnecessary full prefills across both new chat sessions (same model + same workspace) and same-session multi-turn follow-ups after long replies.

flowchart LR
  S1["Session 1 (cold)"] -->|"BP1 (sys+tools) & BP2 (workspace)<br/>+ cache_control priority hints"| SSD["Persistent SSD Tier<br/>(LRU-touched, relabel-safe)"]
  S1 -->|"Scheduled DFlash2 decode<br/>rolling Checkpoint -> Ordinary"| SSD
  S1 -->|"Emitted token IDs<br/>+ lazy cold-restart seed"| TH["TurnTokenHistory<br/>(salt-isolated, seam-safe)"]
  S2["New Session / Follow-up"] -->|"Matches BP1/BP2 or Turn 1 end<br/>without BPE merge drift"| SSD
  TH --> S2
  SSD -->|"Skip ~90–99% prefill"| UI["Chat UI: '{cached} cached'"]
Loading

1. Cross-Session SSD Prefix Anchors (Phases 1–3)

  • Structural Jinja prefix breakpoints (crates/mlx-core/src/tokenizer/prefix_breakpoints.rs, tokenizer.rs): single BPE encode pass + bounded shadow Jinja LCP extracting BP1 (system+tools end) and BP2 (penultimate consecutive leading user message end), plus intra-message PrefixBreakpointHint { messageIndex, byteOffset, priority? } wired through both render_prompt_with_breakpoints and render_prompt_counted.
  • Multi-head SSD anchors across all hybrid/state-tiered models:
    • Qwen3.5 (Dense & MoE) (disk_tier/plan.rs, dflash2_turn.rs, dflash2_state/paged.rs, model/{chat_backend,commands,paged_backend,restore}.rs): configure_draft_state_plan_with_heads keeps explicit prompt heads protected from fast superseding, suppresses pinning prompt_replay when an explicit head sits strictly below it, and promotes exact rolling-checkpoint hits at explicit heads.
    • Qwen4 & Hy4-flash (disk_tier/prefix_disk.rs, models/qwen4_exp/*, models/hy_v4_flash/*): token-deterministic BP1/BP2 extraction + PrefixDisk::Point.head.
    • Inkling2 & Claude Code cache_control hints (packages/server/src/mappers/anthropic-request.ts, packages/core/index.d.cts, crates/mlx-core/src/tools/inkling.rs, models/inkling2/paged_forward.rs): maps Anthropic cache_control and leading-user multi-block splits into priority-tiered PrefixBreakpointHints shared by Jinja and Inkling2.
  • SSD LRU preservation & durability hardening (crates/mlx-paged-attn/src/cold_cache*, crates/mlx-core/src/disk_tier/state_disk.rs, dflash2_state/disk.rs, inkling2/state_disk.rs):
    • ColdKeyHold on queued writes & chain cursors + manager.touch() on RAM/SSD hits so shared BP1/BP2 KV blocks stay hot in LRU.
    • ColdCacheManager::verify_live_and_touch splits confirmed missing vs transient unverified errors (PermissionDenied/EIO) with per-entry verify_backoff and idle wakeups so transient stat errors never drop anchors or stall healthy writes.
    • Off-thread StateDiskEngine checkpoint relabeling (checkpoint: true → false) guarded by PersistCommitGuard::RequireLiveSource, StateRelabelLanded.committed_identity, ColdCacheManager::remove_if_identity, and close_cache drain of deferred cleanups.
  • Dashboard Chat UI (packages/dashboard/{src/chat,ui/src/lib}/chat-*): displays {cached} cached during prepare/prefill.

2. Multi-Turn BPE Re-Tokenization Drift Prevention

  • TurnTokenHistory (crates/mlx-core/src/tokenizer/turn_history.rs, tokenizer.rs, tools/inkling.rs, engine/*, all ChatBackend families):
    • Preserves exact emitted token IDs across stateless TurnKind::Start turns (/v1/messages & /v1/responses) for both Jinja models and Inkling2, preventing single BPE merges (e.g. '不' + '可' → '不可', '.' + '\n\n' → '.\n\n') from invalidating 6K–10K cached reply tokens.
    • Isolated by cache_salt, bypassed on one-shot renders (preserve_thinking == false), cleared on ResetScope::Command, guarded by RAII PendingPromptPin, full canonical added-token parity, normalizer segment commutation, and Metaspace checks, while keeping prefix_breakpoints offsets aligned.
    • Lazily seeds from SSD adopt_all across Qwen3.5, Inkling2, Hy4-flash, and Qwen4 using Arc<[u32]> + streaming prefix-only scoring so cold restarts recover split-BPE turn-end SSD anchors without startup decode cost.

3. Qwen3.5 Scheduled DFlash2 Turn-End State Publication

  • Design B: rolling decode StateClass::Checkpoint → StateClass::Ordinary at finalize (models/qwen3_5/{scheduled_dflash2,dflash2_turn,dflash2_state/paged,model/commands,model/paged_backend,model/lifecycle}.rs, paged_kv_cache_adapter.rs, mlx-paged-attn/src/{block_allocator,block_table}.rs):
    • Captures seq_windows through the end of scheduled draft prefill (plus exact-block-multiple prompts).
    • On decode block-boundary crossings, pre-leases same-wave dedups, claims governor budget before GdnStateBlobs::snapshot_after_prefix + DraftContextWindow::detach_snapshot, incrementally registers blocks via cache_full_blocks_from (with prefix_cache_removal_epoch rebuild), and maintains at most one evictable rolling Checkpoint per active lane (0 extra lane_state_bytes).
    • Promotes to Ordinary + SSD write-behind (is_prompt_head = false) in finalize_paged_turn (and hooks into existing long-reply preemption promotion); adds COW detach + pending-write drain in rollback_last_tokens and fault-isolated optional window flushing.

Verification

Rebased cleanly onto main (d1efe25ba) and verified:

  • cargo fmt --all -- --check — passed
  • cargo clippy -p mlx-paged-attn -p mlx-core --lib --tests -- -D warnings — passed (0 warnings)
  • cargo test -p mlx-paged-attn --lib — 249 passed, 0 failed
  • cargo test -p mlx-core --lib -- --test-threads=1 (all touched suites: disk_tier::*, tokenizer::*, tools::inkling, engine::{cmd,paged_turn,prompt_parts}, qwen3_5::{dflash2_turn,dflash2_state,prefix_anchor_tests,scheduled_turn_end_tests,preempt_reply_tests}, inkling2::state_disk, qwen4_exp, hy_v4_flash, rollback & DFlash2 lane regressions) — 1,291 passed, 0 failed
  • yarn build:native && yarn build:ts && yarn typecheck && yarn --cwd packages/dashboard build — passed
  • vp check (all 12 touched TS files) — passed
  • vp test run (anthropic-request-mapper.test.ts, chat-service.test.ts, chat-thread-libs.test.ts, chat-thread.test.ts) — 421 passed, 0 failed

@coderabbitai

coderabbitai Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0c60f8c5-9811-4a1d-a783-922fffcbd58e

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-01T05:46:07.117273Z c1f6cee PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

…hors, BPE drift history, and Qwen3.5 scheduled turn-end states
@Brooooooklyn
Brooooooklyn force-pushed the perf/ssd-prefix-anchors branch from c1f6cee to 8b31e66 Compare December 1, 2026 05:44
@Brooooooklyn
Brooooooklyn merged commit ce8adc9 into main Dec 1, 2026
39 of 41 checks passed
@Brooooooklyn
Brooooooklyn deleted the perf/ssd-prefix-anchors branch December 1, 2026 06:49
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