Repository navigation
chore: remove dead code across inference control flow - #57
Conversation
Deep audit of the inference control flow (TS surface → NAPI → Rust models
→ transformer/cache/paged → C++ compiled forward → MLX) surfaced
~15k lines of dead code: legacy NAPI surfaces with no JS consumers,
self-contained dead modules, scaffolding never adopted by any model,
and the legacy continuous-batching paged-attention chain that was
superseded by the block-paged adapter.
Major removals:
- Qwen3 legacy paged NAPI (forwardPaged/prefillPaged/addPagedRequest/
stepPagedGeneration/getCompletedSequences/hasPagedWork/pagedCacheStats/
schedulerStats) + Qwen3Inner.{paged_cache,scheduler} fields +
use_paged_attention/use_fp8_cache config flags. All zero JS callers.
- mlx-paged-attn legacy chain: scheduler.rs (ContinuousBatchingScheduler),
paged_kv_cache.rs, cache_engine.rs, token_tracker.rs, attention_layer.rs,
input_metadata.rs, metal/swap_blocks.rs. Superseded by PagedKVCacheAdapter.
- Gemma4 GEMMA4_USE_COMPILE env-gated branches + mlx_gemma4.cpp.
Unreachable under paged-default-on; no tests/docs set the env var.
- transformer/ scaffolding: BatchKVCache, FusedAttention,
HybridKVCacheManager, QuantizedKVCache+UnifiedKVCache. Zero model callers.
- C++ FFI superseded shims: mlx_qwen3_generate, mlx_qwen3_forward_step_batched,
mlx_compiled_{categorical_sample,top_k,top_p,min_p,apply_temperature},
mlx_sample_and_logprobs, mlx_fused_attention_forward{,_cached},
mlx_fused_transformer_block_forward_cached, plus orphans
(mlx_version, mlx_export_to_dot, mlx_array_scatter, etc.).
- qwen3/speculative.rs (392 lines, no callers).
- qwen3_5/prompt_cache.rs + takeCache/setCache/initCaches NAPI (no consumers).
- PaddleOCR-VL pure-Rust forward stack (ERNIELanguageModel::forward,
forward_with_cache, PaddleOCRDecoderLayer/Attention forward variants,
init_kv_caches, reset_kv_caches) — superseded by C++ forward_fused.
- PaddleOCR-VL dead NAPI: getInputEmbeddings, forward, generate (NAPI
wrapper), ocrBatch, setTokenizer, hasTokenizer, loadConfig,
getExpectedWeightKeys. VLModel.chat() preserved (deliberate single-turn).
- Sampling: sample_uncompiled + apply_sampling + apply_top_k/top_p/min_p/
apply_temperature (~190 lines, no callers). sample_compiled inlined into
sample (no longer needed as separate symbol).
- tools/parseToolCallsFromText NAPI + legacy XML format
(no model emits <name>/<arguments>).
- TypeScript surface trimming: ~14 unused re-exports in @mlx-node/lm and
@mlx-node/vlm (no consumers via these packages; canonical imports from
@mlx-node/core remain). EmbeddingModel alias inlined to HarrierModel.
packages/vlm/src/models/{index.ts,paddleocr-vl-configs.ts} deleted.
- Stale doc / @deprecated JSDoc misattachment in session-registry.ts,
TTL constant reference fix, types-anthropic.ts paged-reuse note.
Refactoring:
- Three byte-identical tokio::spawn streaming-callback pumps in qwen3/model.rs
consolidated into pump_stream_to_callback helper.
- should_propagate_compiled_paged_error duplicated between qwen3_5 and
qwen3_5_moe models hoisted into qwen3_5/chat_common.rs.
- sanitize_messages_public wrapper merged into sanitize_messages (pub(crate)).
Visibility narrowing across qwen3_5, qwen3_5_moe, gemma4, lfm2, qianfan_ocr,
paddleocr_vl, tokenizer, kv_cache_spec, paged_kv_cache_adapter:
many pub items downgraded to pub(crate)/pub(super)/private,
or gated behind #[cfg(test)] where only test consumers exist.
Verification:
- cargo check --workspace --tests: clean
- cargo clippy --workspace --tests --no-deps: clean
- cargo fmt --all --check: clean
- yarn build:native: clean
- cargo test -p mlx-core --lib: 1287 passed, 18 ignored, 0 failed
- cargo test -p mlx-paged-attn: 103 lib + 16 integration tests pass
- vp lint --type-aware --type-check: clean
- vp test: 1203 passed, 5 skipped, 0 failed
Net impact: 84 files changed, +318 / -15655 lines.
Architectural gaps flagged but NOT addressed (require product decisions):
- LFM2 paged delta dispatch gap (chat_session_continue always uses flat path)
- Decode profiler instrumentation only wired for Qwen3.5 dense
- outputTokenLimit asymmetry between /v1/responses and /v1/messages
Co-Authored-By: Claude Opus 4.7 <[email protected]>
Token counting is a millisecond-scale tokenize + chat-template render that was being routed through `sessionReg.withExclusive(...)`, the per-model generation FIFO. A launch-claude trace from 2026-05-12 showed five count_tokens requests taking 191-274 s each — they were stalled behind a multi-minute 27B Q8 decode pass. The dispatch lease already pins the model + binding for the call duration, and `modelWorkCoordinator.withInference` (shared reader vs model-load writer) is enough to keep the model from being swapped mid-tokenize. Drop the exclusive-FIFO wrap; keep the reader wrap and the binding-stable check around `applyChatTemplate`. The pre-fix "queued behind exclusive then binding swaps" race is no longer reachable; the remaining race surface (binding swap while applyChatTemplate is mid-flight) is still covered by the sibling running-counter test. Co-Authored-By: Claude Opus 4.7 <[email protected]>
Production trace from 2026-05-12 surfaced a 470-s SSE 'event: error' from
the Qwen3.5 dense paged path:
chat_stream_sync_core_paged: zero-delta prompt (every token cached) is
not yet supported on the block-paged path; flat path required for this
corner case
Trigger: a client retried the same 142 KB turn four times across 600-s
HTTP timeouts. By retry four the live cache covered every prompt token,
the prefill chunk had zero new tokens to forward, and the inner paged
loop bailed.
Apply the vLLM-style exact-prefix cap (`vllm/v1/core/kv_cache_manager.py
:202-208`) at every paged dispatch site: cap the cache lookup AND the
warm-continue precondition at `max_cache_hit_tokens = prompt.len() - 1`,
so at least one suffix token always survives for the prefill chunk.
- Promote `find_cached_prefix_with_max_tokens` from `#[cfg(test)] pub`
to `pub`; add `find_cached_prefix_per_block_with_max_tokens` for the
multimodal block-keyed lookup.
- Migrate Qwen3, Qwen3.5 dense, Qwen3.5 MoE, and LFM2 paged sync+stream
dispatch sites (8 sites total) to the capped lookup variant and gate
the warm-continue check on `live_tokens_len <= max_cache_hit_tokens`.
- Gemma4 already applied the cap inside `prepare_gemma4_paged_turn`;
remove the now-dead bail blocks there too.
- Replace all 10 `if suffix_len == 0 { return Err(...) }` blocks with
`debug_assert!(suffix_len > 0, ...)` documenting the invariant.
- Refresh the stale "Phase 2 caveat" doc comments on Qwen3 / LFM2 to
describe the new contract.
Add two adapter-level regression tests (`*_zero_delta_regression`) plus
a NAPI-surface TS regression test (`qwen3-paged-zero-delta.test.ts`)
that retries an identical prompt and asserts no error fires. The TS test
is gated on `QWEN3_PAGED_PARITY_MODEL_PATH` to match the existing parity
suite.
All 1289 mlx-core lib tests + 1202 TS tests pass; clippy + fmt clean.
Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 800ae7505e
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
The `PADDLEOCR_VL_CONFIGS` re-export was removed in 6ecc451 as part of the TypeScript surface trim (canonical imports now flow through `@mlx-node/core`, with `createPaddleocrVlConfig()` retained as the factory). The README's Configs table still advertised the symbol, which would surface as a module-export error for consumers upgrading without warning. Remove the stale row so the docs match the actual public API. Co-Authored-By: Claude Opus 4.7 <[email protected]>
Note
Medium Risk
Touches core generation/inference codepaths (Gemma4/LFM2/Qwen3 configs) and removes several public PaddleOCR-VL NAPI APIs, so regressions would impact runtime behavior and downstream consumers despite most changes being deletions/safety caps.
Overview
Block-paged KV cache dispatch is hardened and enabled by default for more models. LFM2’s
use_block_paged_cachenow defaults on and its paged chat paths cap cache hits toprompt.len() - 1(vLLM-style) so an exact prompt retry still leaves a suffix to prefill, replacing prior “zero-delta prompt” errors with debug-asserted invariants.Gemma4 decode is simplified by deleting the optional compiled C++ path (and its global mutex/FFI helpers), leaving only the lazy-eval decode loop and converting prior zero-delta runtime errors on the paged path into invariants enforced by
prepare_gemma4_paged_turn.Dead/unused surfaces are removed across models and VLM. Qwen3 drops legacy
use_paged_attention/FP8 cache flags and removes KV-quantization/speculative fields fromGenerationConfig; PaddleOCR-VL removes its Rust-side KV-cache forward implementation and multiple NAPI commands/APIs (set_tokenizer,forward,generate, embeddings helpers, weight-key listing), narrowing exports to only what’s used cross-module.Tests/docs are updated accordingly, including a new gated TS regression test for Qwen3 paged exact-retry (“zero-delta”) and minor test fixture/formatting fixes.
Reviewed by Cursor Bugbot for commit 800ae75. Bugbot is set up for automated code reviews on this repo. Configure here.