Repository navigation
feat: add Qianfan-OCR - #38
Conversation
Add the foundational module structure and configuration for the Qianfan-OCR model based on InternVL2.5 architecture (InternViT + Qwen3 LM). Defines InternVisionConfig, Qwen3LMConfig, and QianfanOCRConfig with defaults matching the baidu/Qianfan-OCR HuggingFace config. Includes factory function, helper methods, and 9 unit tests. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Implement the 24-layer InternViT vision transformer with learned absolute position embeddings, CLS token, fused QKV attention, GELU MLP, LayerNorm, and layer scale. Includes position embedding interpolation for non-default grid sizes. All 8 tests pass, clippy clean. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Implements the InternVL bridge that connects the InternViT vision encoder output [B, 1024, 1024] to the Qwen3 LM input [B, 256, 2560] via pixel shuffle v2 downsampling and a two-layer MLP projection. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Qwen3-4B language model using TransformerBlock with support for pre-computed embeddings (vision-text merge), tied word embeddings, and KV cache management. Includes 9 tests covering build, forward, embeddings, tied weights, and cache lifecycle. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Implements InternVL-style dynamic resolution tiling that splits images into 1-12 tiles of 448x448 plus an optional thumbnail, enabling the model to handle various resolutions and aspect ratios. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Transform HuggingFace InternVL weight keys to internal format across three prefixes (vision_model→vision, mlp1→bridge, language_model→lm) and transpose the patch embedding Conv2d weight from NCHW to NHWC. 29 tests covering all key categories and transposition. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
ChatML-style prompt builder with visual token replacement for InternVL-based Qianfan-OCR. Implements format_qianfan_chat (with auto-prepend of <image> placeholders, multi-image support, and thinking mode), count_images_in_messages, and extract_images_from_messages. Includes 20 tests covering text-only, single/multi image, system messages, multi-turn, and thinking mode. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…rate Integrates all Qianfan-OCR components (InternViT vision encoder, MLP bridge, Qwen3 language model) into a NAPI-exposed QianfanOCRModel class. Implements vision-text merging, KV cache prefix matching for multi-turn efficiency, streaming generation via ThreadsafeFunction callbacks, and removes dead_code suppressions from component modules now that they're consumed. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Add QianfanOCRModel wrapper class with AsyncGenerator-based chatStream, re-export types from @mlx-node/vlm, and NAPI binding smoke tests that verify config factory defaults and model construction. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The persistence module was renaming vision layer sub-keys (norm1→layer_norm1, attn.proj→attn.out_proj, ls1→layer_scale_1) but the vision encoder build functions expected the original HuggingFace names. Simplified persistence to pass through vision layer sub-keys unchanged. Also fixed cls_token→class_embedding to match the actual weight key in the model, and encoder.layers→layers prefix. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Critical: replace clear_cache() with synchronize_and_clear_cache(), fix finish_reason from "eos" to "stop", add missing presence/frequency penalties in chat_stream before first token. High: reuse extract_images_from_messages from qwen3_5, reuse get_tensor from pp_doclayout_v3, remove dead transform_vision_layer_suffix no-op, fix dead code in chat.rs, fix tokenizer path error handling. Medium: remove double token.eval() on first iteration, fix O(n*m) image placeholder replacement, use sequential memory access for pixel normalization. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Enables `mlx convert -m qianfan-ocr` to pre-transform HuggingFace InternVL weights to MLX format (key renaming + Conv2d NCHW→NHWC) with optional quantization. The load() method auto-detects whether keys are already transformed and skips the runtime transformation. Usage: mlx convert -i .cache/models/qianfan-ocr -o .cache/models/qianfan-ocr-mlx -m qianfan-ocr mlx convert -i .cache/models/qianfan-ocr -o .cache/models/qianfan-ocr-4bit -m qianfan-ocr -q --q-bits 4 Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…pipeline vlm-inference.ts is now a clean, general-purpose VLM inference example that supports Qianfan-OCR (and any future VLM) with CLI flags: --image, --prompt, --stream, --thinking, --max-tokens, --temperature The PaddleOCR-specific layout+OCR pipeline is moved to paddle-ocr-pipeline.ts (unchanged functionality). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The previous implementation used a 5D/6D factored decomposition with intermediate transposes, but the v2 permute on the factored form produced a completely different pixel arrangement than the Python's simple 4D spatial transpose. This caused vision features to be spatially scrambled, making the model read the title but then repeat it endlessly. The fix follows the Python exactly with 4D operations: 1. reshape [N,W,H,C] -> [N,W,H*s,C/s] (merge trailing H into C) 2. permute(0,2,1,3) (swap spatial axes) 3. reshape [N,H*s,W*s,C/s²] (merge trailing W into C) 4. permute(0,2,1,3) (v2: spatial transpose) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…rence Adds test_pixel_shuffle_v2_exact_order_4x4 that checks the exact output element ordering against the Python InternVL pixel_shuffle with ps_version=v2. Uses arange(1..49) as input and verifies the output matches the Python torch reference output element-by-element. This test would have caught the original spatial scrambling bug. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Adds TTFT, prefill tok/s, and decode tok/s metrics to QianfanChatResult and ChatStreamChunk (final chunk), matching the Qwen3.5 pattern. Timing is zero-overhead when disabled — Instant::now() is only called when reportPerformance: true. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- chat_stream: replace fire-and-forget spawn_blocking with tokio::spawn + napi spawn_blocking, propagating panics through callback - Disable KV cache reuse when images are present (IMG_CONTEXT tokens don't capture actual image content) - Replace unwrap_or_default() with error propagation in streaming decode - Add else branch for LM head fallthrough when tie_word_embeddings is false but lm_head is None - Validate pixel_shuffle_v2 seq_len is a perfect square - Add initialization guard at top of chat() and chat_stream() Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
… image association Four fixes from reviewer findings: 1. <think> placement: now appended to the last user message content (before <|im_end|>) matching chat_template.jinja, not after the assistant generation prompt. The old placement changed tokenization and broke Layout-as-Thought. 2. Per-message image association: auto-prepend <image> to EACH user message that carries images (not just the first). Multi-turn conversations with images in different turns now correctly associate visual tokens with their respective messages. Also validates that all images are consumed (errors if placeholders < images). 3. chatStream final event: text field now contains cleaned text and raw_text contains the raw decoded output, matching the Qwen3.5 contract that _createChatStream expects. Was emitting text:"" which made AsyncGenerator consumers get empty final text. 4. Tool/reasoning metadata: format_qianfan_chat now handles tool role (grouped <tool_response>), assistant tool_calls (<tool_call> JSON), and reasoning_content (<think> tags) — matching the upstream Jinja template. Previously all metadata was silently dropped. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Three fixes from reviewer findings: 1. Tools support: format_qianfan_chat now accepts tools parameter and formats the system block with tool schemas per the upstream Jinja template (<tools> XML block with function signatures). chat() and chatStream() forward config.tools to the formatter. 2. Repetition cutoff: both decode loops now call check_repetition_cutoff after the EOS check, matching Qwen3.5. Respects max_consecutive_tokens (default 16), max_ngram_repeats (default 3), and ngram_size (default 64). 3. Reasoning scope: reasoning_content is now only serialized for assistant turns AFTER last_query_index, matching the upstream Jinja template. Added fallback extraction of embedded <think>...</think> from content. Previously reasoning was always serialized regardless of position, which could bloat prompts in multi-turn conversations. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…rom older turns 1. Tool schema properties: format_tools_block now parses FunctionParameters.properties (stored as Option<String>) into a proper JSON object before serializing, matching tokenizer.rs:836. Previously serde_json::to_string double-escaped it as a string. 2. Embedded <think> stripping: extract_reasoning_and_content now ALWAYS extracts reasoning (from reasoning_content or embedded <think>) first, then only re-inserts for turns after last_query_index. Previously, turns before last_query_index returned content untouched, leaking embedded <think> blocks from older assistant turns into the prompt. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…ote tool_calls finish reason Three fixes from reviewer findings: 1. Cache reuse safety: when prefix_len < existing cache offset, KV caches are now trimmed via KVCache::trim() to discard stale suffix tokens from the previous generation. Previously only full reset or no-op was done, so branched prompts (shared prefix but different suffix) would generate on top of stale cache entries. 2. History sync: cached_token_history is now cleared on all non-reuse paths — chat(reuseCache:false), chatStream() (always fresh), and generate(). Previously only chat(reuseCache:true) wrote history, but other paths reset caches without clearing the metadata, causing stale prefix matches on subsequent reuse-enabled calls. 3. Tool call finish_reason: both chat() and chatStream() now promote finish_reason to "tool_calls" when parsed tool calls have status "ok", matching the Qwen3.5 pattern. Orchestration keyed on finishReason will now correctly handle Qianfan tool turns. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…k extraction 1. Cache history alignment: on "stop"/"repetition" exits, the terminal token is pushed to generated_tokens but never forwarded into the KV cache. The stored history now excludes that unforwarded token so prefix matching stays aligned with the live cache state. 2. Embedded reasoning extraction: now matches the upstream Jinja which splits on </think> anywhere in content (not just starts_with), and handles: leading whitespace before <think>, bare reasoning</think> without opening tag, and <think> in the middle of content. All forms are correctly stripped on older assistant turns. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Upstream Jinja (chat_template.jinja lines 47-50) emits a <think> block
for any assistant turn after last_query_index when it is the last
message, even if reasoning_content is empty. Our code was only emitting
it when reasoning was non-empty. This caused the last assistant turn in
history to tokenize differently from upstream.
Now emits <think>\n\n</think>\n\n{content} for the last assistant
message after the last user query, matching the upstream template.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The fallback extractor could produce Some("") for content like
"<think></think>\nA" or "</think>\nA". Upstream Jinja treats empty
reasoning_content as falsy (no <think> block on non-last turns).
Two changes:
- Extractor now returns None instead of Some("") when trimmed
reasoning is empty
- emit_think guard uses is_some_and(|r| !r.is_empty()) instead of
is_some() as a defense-in-depth check
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Upstream Jinja only appends the <think> marker when message.role == "user". Our code also did it in the "system" branch, and find_last_query_index fell back to the last message (even non-user) when no user turn existed. Two changes: - Removed <think> append from the system branch - find_last_query_index returns usize::MAX sentinel when no user message exists, so no message index can match it Co-Authored-By: Claude Opus 4.6 (1M context) <[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: e41408180f
ℹ️ 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".
loadModel() now supports model_type "internvl_chat" from config.json, routing to QianfanOCRModel. This allows examples/lm.ts and any code using loadModel() to work with Qianfan-OCR models automatically. Added LoadableModel type (union of TrainableModel | QianfanOCRModel) as the return type of loadModel(), since VLMs are inference-only. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
When prefix_len == seq_len (identical prompt resent with reuseCache), the condition `prefix_len < seq_len` was false, so the else branch forwarded the full merged_embeds. But the cache had been trimmed to prefix_len, causing the full prompt to be appended on top — doubling the cache and producing garbage output. Fix: clamp prefix_len to seq_len-1 so there is always at least 1 token to re-forward for logits. The trim also uses the clamped value so cache and prefill slice are consistent. For the exact-match case, this re-forwards only the last token (1 forward call vs full prefill). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e1ed603ae3
ℹ️ 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".
1. Model loader: detectModelType now accepts both "internvl_chat" (the HuggingFace model_type) and "qianfan-ocr" (used by the converter/CLI). Both route to QianfanOCRModel.load(). 2. Image processor: when dynamic_image_size is false, images are resized to a single image_size x image_size tile instead of running the multi-tile dynamic_preprocess pipeline. Previously the config flag was stored but never checked. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
mlx-node/packages/cli/src/commands/convert.ts
Lines 273 to 277 in de59a69
Auto-detection only recognizes paddleocr_vl, qwen3_5_moe, and qwen3_5. Qianfan configs (internvl_chat/qianfan-ocr) therefore leave modelType unset when --model-type is omitted, so conversion skips the Qianfan sanitizer (key remap + conv transpose) and produces weights the Qianfan loader cannot resolve correctly.
ℹ️ 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".
Three fixes from reviewer findings: 1. CLS token key: vision.rs now accepts both "class_embedding" (the actual HuggingFace key) and "cls_token" (common alias) with fallback lookup. Persistence test updated to use the real key name. 2. chatStream cache reuse: streaming now honors config.reuse_cache with the same prefix matching, trim, clamp, and history sync logic as chat(). Previously always reset caches, causing unnecessary re-prefill on repeated streaming calls. 3. chatStream history sync: stores forwarded tokens after generation (excluding unforwarded terminal tokens) and clears history on non-reuse paths, matching the chat() behavior. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Replace std::iter::repeat(X).take(N).collect() with X.repeat(N) in test assertions per clippy --all-targets. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f03b877d95
ℹ️ 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".
…lignment 1. Stateful streaming decode: replaced per-token decode_sync(&[token]) with DecodeStream (step_decode_stream) matching Qwen3.5. Handles multi-byte Unicode boundaries correctly — CJK, emoji, and byte-pair sequences now stream without garbled intermediate chunks. 2. Cancelled history alignment: "cancelled" breaks BEFORE pushing the current token, so all tokens in generated_tokens were forwarded. The forwarded calculation now correctly uses full length for "cancelled" and "length", only subtracting 1 for "stop" and "repetition" where the last pushed token was not forwarded. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 392211366a
ℹ️ 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".
…ream errors via error channel 1. Conv2d double-transpose guard: needs_conv2d_transpose now checks the actual shape layout (dim[1] < dim[2] = OIHW) to distinguish PyTorch OIHW from MLX OHWI. Re-running conversion on an already- converted checkpoint no longer corrupts the patch embedding. 2. Stream error propagation: runtime errors (image decode, tokenization, lock failures, etc.) now propagate via the IIFE return → outer callback_err.call(Err(...)) path, which _createChatStream surfaces as thrown exceptions. Previously errors were swallowed into a synthetic done chunk with finish_reason:"error", which consumers treated as a successful completion. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d9d9539dac
ℹ️ 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 repetition check was before decode+emit, so the triggering token was included in raw_text but never streamed as a delta chunk. Clients rendering only delta chunks saw truncated text on repetition stops. Moved decode+emit above the repetition check (but after EOS check, since EOS tokens should not be streamed). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7891c0c05f
ℹ️ 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".
format_qianfan_chat() produces a fully templated ChatML prompt with control tokens already embedded. Pass add_special_tokens=false to encode_sync to prevent the tokenizer post-processor from injecting BOS/EOS, which would shift the token sequence and misalign cache prefix matching. Fixes both chat() and chat_stream() paths. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
<!-- CURSOR_SUMMARY --> > [!NOTE] > **High Risk** > Large feature addition that introduces a new vision-language model pipeline (image preprocessing, prompt formatting, weight conversion, GPU inference, and KV-cache reuse), which can impact correctness and performance in core generation paths. > > **Overview** > Adds end-to-end support for the `qianfan-ocr` model, including a new `QianfanOCRModel` NAPI API (`load`, `chat`, `chatStream`, `generate`) that integrates InternViT vision encoding, a pixel-shuffle + MLP bridge, and a Qwen3-based language model with optional KV-cache reuse. > > Introduces Qianfan-OCR-specific building blocks: config + JS factory, InternVL chat template formatting (images, thinking, tools), dynamic image tiling/normalization, and HuggingFace→internal weight-key transformation (including Conv2D transposition). The conversion pipeline now recognizes `model_type: qianfan-ocr` for weight sanitization, and a small TS smoke test validates the new NAPI bindings. > > Updates docs to reflect the Vite+ CLI change from `vite` to `vp`, including new command grouping and CI setup guidance. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit cb82f14. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
…#38) vLLM out-of-box behavior: when a request leaves a sampling field unspecified, fall back to the checkpoint's generation_config.json value, and merge its eos_token_id list into the per-turn stop set. Precedence is request value > generation_config default > sampler builtin; an explicit request value always wins. Default-ON (backward-compat waived). Engine seam: - ModelGenerationDefaults (engine/params.rs) + parse_generation_defaults (engine/persistence.rs): graceful — a missing/unparseable file yields an empty Default, so every touched path is byte-identical when a checkpoint ships no generation_config.json. Scalar OR array eos_token_id; negatives and out-of-u32/i32-range values dropped via try_from (never wrapped). - New ChatBackend::generation_defaults() (default None); the default resolve_params folds it into any unspecified field before extraction, so qwen3_5/qwen3_5_moe/lfm2 get it via the inherited impl. qwen3 drops its now-redundant passthrough resolve_params override. - extra_eos_ids() returns the parsed eos list, unioned at the single decode stop site. gemma4 left untouched (already honors generation_config via its own make_sampling_config fold + multi-eos). Raw model.generate() (qwen3/qwen3_5/qwen3_5_moe generate_sync): folds the defaults into SamplingConfig and adds the eos list to the stop/finish check. qwen3's GenerationConfig::default() bakes Some(builtin) sampling values, so an OMITTED config captures the caller's actual fields (None when omitted) BEFORE unwrap_or_default, keeping the 3-tier precedence intact. The qwen3_5/qwen3_5_moe raw surface exposes only the four SamplingConfig fields (no penalty machinery), so repetition_penalty is honored on the ChatSession path but intentionally not on that minimal raw API. Defaults stored on each Inner (not the napi Config) → index.d.cts unchanged. Tests: 8 parser cases (scalar/array/negative/out-of-range eos, missing/ unparseable file, sampling fields) + 3 mock-backend fold cases (unspecified falls to default, explicit wins, None default is a no-op). Co-Authored-By: Claude Opus 4.8 <[email protected]>
… order Expand ModelGenerationDefaults' rustdoc into the authoritative precedence reference for the #38 feature, answering "when both generation_config.json and config.json exist, what wins?": - Sampling (temperature/top_k/top_p/min_p/repetition_penalty): request > generation_config.json > sampler builtin. config.json contributes nothing — the per-family Config struct has no sampling fields. - Stop tokens (eos_token_ids): a UNION at the single decode stop site (token_id == eos_id || extra_eos_ids.contains(..)), never an override. ChatML primary eos is the tokenizer <|im_end|> (config.json eos_token_id is deserialized but unused on the chat path); generation_config.json eos ids are OR'd on top. - Footnotes for the two diverging surfaces: raw model.generate() (primary eos from config.json; repetition_penalty qwen3-only) and Gemma4 (routes sampling defaults through its own Config, still a union for eos). Also fix a now-stale claim in decode.rs ("Empty for every ChatML family today"): after #38, ChatML families pass their generation_config.json eos ids here. Add cross-reference pointers from generation_defaults() and the DecodeLoopArgs.extra_eos_ids stop site. Comment-only — byte-identical runtime, no native rebuild. fmt clean; all fenced doc blocks are ```text (no doctest compilation). Co-Authored-By: Claude Opus 4.8 <[email protected]>
…_config.json (#38) (#70) ## Chat-engine refactor — model-neutral engine → paging inversion → compiled coexistence → pure-Rust eager/MTP → declarative convert > **Scope.** This branch carries the **entire** chat-engine refactor stacked on `main` — Phase 1 (engine extraction, S1–S12) plus follow-ups **P1–P8**, the **MTP and vision genericizations**, and the `#38` generation-config feature: **73 commits, 143 files, +39.5k / −54.0k (net ≈ −14.5k LOC)**. The phases were developed on one long-lived branch and build on each other, so they cannot be split into separate PRs against `main`. Opened for review. > > **Synced with `main`.** Merged `origin/main` (NVIDIA DGX/CUDA backend [#71] + qwen3.5 GDN chunked-ops prefill [#72]) into the branch — **PR is now conflict-free / mergeable**. The CUDA additions are Metal-gated, so the macOS path is byte-for-byte unchanged; the only merge work was repointing CUDA's `compiled_forward_backend_available()` Metal guards from the pre-refactor `qwen3_5::persistence_common` to the relocated `engine::persistence`, and keeping both our GDN tape-replay test and #72's new chunked-ops tests. ### Why Adding a new model family cost ~10–17k LOC because the production engine (decode loop, session mgmt, paged-KV, compiled-graph path, MTP) was built inside the first family (`qwen3_5/`) and copy-forked into each new one. This refactor extracts a model-neutral engine and pushes every production feature behind an engine-owned seam, so a new family becomes a thin backend impl — hence the large net deletion. ### Phases on this branch **Phase 1 — extract the model-neutral chat engine (S1–S12).** New `crates/mlx-core/src/engine/`: `ChatConfig/ChatResult/ChatStreamChunk` types, `ChatBackend`/`DecodeStep` traits, generic `run_decode_loop`, generic session cores + `ChatCmd` + napi glue, compiled locks, persistence helpers. All five families (qwen3, qwen3_5 dense, qwen3_5_moe, gemma4, lfm2) migrated onto it; legacy per-family chat machinery deleted (grep-gated). **P1–P3 — engine seams.** `ThinkingPolicy` + ChatML delta single-source-of-truth; paged-turn lifecycle dedup via a `PagedTurnPlan` adapter. **P4 — paging inversion (`engine::run_paged_turn<B: PagedBackend>`).** The default paged auto-regressive whole turn now flows through one generic engine path + `run_decode_loop` for all five families, behind a paged-forced byte-equivalence gate. **P5 — per-model-id compiled slot map.** Replaces the single process-global `g_active_model_id` gate over the C++ compiled-decode state with per-model-id slot maps, so **two compiled models coexist in one process** instead of the 2nd load silently demoting the 1st to eager. Includes the MTP draft/commit-graph residency owner-guard and a deadlock fix on the per-`Inner` Drop. **P6/P7 — delete the C++ compiled forwards, go pure-Rust.** Removed the qwen3_5 dense + MoE C++ compiled forward paths (~9.4k LOC + 104 FFI externs) in favor of a pure-Rust eager forward and a **pure-Rust eager MTP** (drafter + batched verify + accept/rewind + a Rust GDN tape for bit-exact acceptance). AR eager == former compiled (parity); eager MTP keeps committed-history acceptance. lfm2/gemma4 compiled paths preserved. A hard perf gate (eager-MTP must not regress vs compiled-MTP) was enforced. **P7 (collapse) — TS / NAPI / Cmd / training.** 6 streaming wrapper classes → one `makeStreamingModel` factory + `MODEL_REGISTRY`; 35 hand-written `#[napi]` chat methods → one `chat_napi_surface!` decl-macro; per-family training enums → `engine::cmd::TrainCmd` + `handle_train_cmd<B>` (+ 12 fallible AdamW-apply `unwrap` → `?`). **P8 — declarative convert (`ConversionRecipe` registry).** Collapsed the 7 scattered per-family `convert.rs` dispatch sites into one `recipe_for(model_type)` registry; **e2e `mlx convert` output is byte-identical (sha256)** for qwen3_5 / lfm2 / privacy-filter. **#38 — honor `generation_config.json` defaults engine-wide (vLLM out-of-box).** When a request leaves a sampling field unspecified it falls back to the checkpoint's `generation_config.json`, and that file's `eos_token_id` list merges into the per-turn stop set. Precedence `request > generation_config > sampler builtin`; eos is a **union** (never an override). Default-ON. `index.d.cts` unchanged (defaults live on each `Inner`). **MTP genericization — `engine::run_mtp_turn<B: MtpBackend>` + `run_mtp_cycle<S: MtpStepper>`.** Continuing P4's inversion for speculative decoding: the MTP whole turn and its propose / verify / accept-or-rewind cycle moved off the per-family `decode_loop_mtp!` macro onto one engine-owned generic path. qwen3_5 dense (flat sync, flat streaming, paged) and qwen3_5_moe (flat) all run it; the now-dead `decode_loop_mtp!` macro + `MtpOps` closure-bundle were deleted. Per-family T=0 byte-identity gates; the macro's unit tests were migrated to the live engine path — Codex caught a real dense `accept_with_residual` (T=1.0 dense-accept) coverage gap the migration had dropped, fixed with exact-one-hot deterministic tests. **Vision merge-contract genericization — `engine::vision::{VisionMerge, run_vlm_prefill_layers}`.** The qwen3.5 dense + MoE image-prefill already shared the vision encode + image-feature merge + M-RoPE step (one free fn); its last forked piece — the prefill layer loop — is now unified behind an engine-owned `VisionMerge` DTO + a `VlmPrefillLayer` trait (associated cache type, so each family keeps its distinct layer cache) + one generic `run_vlm_prefill_layers`. The sole divergence (dense relies on the attention layer's internal causal SDPA; MoE passes an explicit causal mask) is now a parameter, not a forked loop. gemma4 stays on its own core — it is structurally disjoint (masked_scatter + 4D mask, no M-RoPE) and even rejects a text delta on an image session. Env-gated T=0 image-chat goldens are byte-identical before / after for both dense (Qwen3.5-4B) and MoE (Qwen3.6-35b-a3b). ### Docs & examples - **Docs:** `ModelGenerationDefaults` rustdoc now documents the full `generation_config.json` vs `config.json` override order (sampling ladder + eos union + raw-`generate()`/Gemma4 divergences). - **Examples cleanup:** removed ~30 internal debug/probe/microbench/perf-A-B/smoke scripts (incl. the `grpo/validation/**` real-API subtree); `examples/` now keeps only user-facing examples — inference (`lm.ts`), VLM (`vlm-inference.ts`), OCR (`paddle-ocr-pipeline.ts`), tool-use (`tool-use-example.ts`), and the GRPO/SFT GitHub-tool training example. Reference-safe (`yarn typecheck` + `lsp.test.ts` 75/75 green; dead `package.json` bench scripts + doc references pruned). ### Verification - `cargo test -p mlx-core --lib` green (only the 2–3 pre-existing Metal-f32 failures, documented; on code paths byte-identical to `origin/main`) · `cargo test -p mlx-paged-attn` green. - Per-family real-checkpoint parity at each P4/P5 step (paged-vs-flat byte-identical); P6/P7 AR eager==compiled + eager-MTP acceptance parity; P8 byte-identical convert; #38 real-checkpoint smoke + 11 unit tests. - `clippy --all -D warnings` + `cargo fmt --check` clean · `yarn build:native` ok · `packages/core/index.d.cts` byte-stable · `yarn typecheck` + TS lint clean. - Post-sync re-gate on the merge commit: `build` + `clippy -D warnings` + `fmt --check` clean; `mlx-core` lib 1775 pass; the merged `gated_delta` module runs both the GDN tape-replay test and #72's chunked-ops tests (7/7). - MTP + vision genericization: per-family T=0 byte-identity goldens green before / after; `mlx-core` lib **1796 pass** / 3 pre-existing Metal-f32; Codex adversarial-review **approve** (no material findings) on both. - Adversarial (Codex) review on each landed phase (all approve / findings fixed). ### Post-review follow-ups & CI - **Open review threads resolved (3/3), each verified against real control flow first:** restored the native config constructor on the streaming wrappers (`ConstructorParameters<C>` — `new Gemma4Model(config)` / `new QianfanOCRModel(config)` type-check again); reinserted the `.biases` sidecar on the vision-dequant fallback so a failed dequant can't emit a corrupt affine quant group; the gemma4 paged-cap flag was confirmed **not** a regression (the clamp was intentionally converged onto the shared engine contract — the KV pool is sized to `max_position_embeddings` and `record_tokens` rolls back on exhaustion, so over-budget turns abort cleanly rather than overrun). - **Rust Lint fix:** moved the `VlmPrefillLayer` impl above the test module (`clippy::items-after-test-module`, a `--all-targets`-only lint that the local `--lib` check missed). - **Removed T=0 parity scaffolding** (`scripts/t0-smoke.sh` + its env-gated Rust capture harnesses, −1.6k LOC): dev-only, never ran in CI, and the refactor it verified has landed. Kept the real CI coexistence test. - **Gated heavy model E2E, folded into `ci.yml` to reuse the single Build:** real-checkpoint tests run as a label-gated `model-test` job inside `.github/workflows/ci.yml` that **reuses the `build` job's `mlx-node` + `mlx-metallib` artifacts — no second native build** (the original standalone `model-e2e.yml` duplicated the entire build job verbatim). A per-family matrix downloads the smallest checkpoint (qwen3 0.6B · qwen3.5 dense 0.8B · lfm2 1.2B · gemma4 E2B) and runs that family's self-referential `--ignored` parity/session tests (paged≡flat, reset/replay determinism, session warm-reuse, greedy MTP≡AR — no host-specific golden). Runs only on `main` pushes, `workflow_dispatch`, or a PR labeled `model-e2e` — keyed on the label that fired the event, so adding an unrelated label to an already-labeled PR is a no-op. On a `model-e2e` label event only `build` + `model-test` run (the regular `test`/`lint` already ran on the PR's push). qwen3.5 MoE is excluded (no checkpoint below 35B-A3B). [#71]: #71 [#72]: #72 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **High Risk** > The declaration file removes and reshapes large parts of the public `@mlx-node/core` API (chat, Qwen3 paged paths, training hooks), and publish now gates on optional E2E—both affect consumers and release flow. > > **Overview** > Adds a **`model-test` CI job** inside `ci.yml` that reuses the build artifacts, downloads small real checkpoints per family (qwen3, qwen3.5 dense, lfm2), and runs `#[ignore]` parity/session tests when pushing to `main`, on `workflow_dispatch`, or when a PR carries the **`model-e2e`** label—with guards so unrelated label events do not re-run the full test/lint suite. **Publish** now depends on `model-test` succeeding (or being skipped) so a failed E2E leg blocks release. > > Regenerates **`packages/core/index.d.cts`** to match the refactored native surface: unified **`ChatConfig` / `ChatResult` / `ChatStreamChunk`**, session + streaming entry points on model classes, **`ChatStreamHandle`**, block-paged cache helpers, expanded GRPO/SFT engine factories, and new exports (Gemma4, LFM2, Harrier, PrivacyFilter, QianfanOCR, ResponseStore, profiling/memory helpers). Several legacy Qwen3 paged-attention and in-process `chat()`/`forward` APIs are **removed** from the typings in favor of model-thread session APIs. > > Small follow-ups: Gemma4 loader test asserts **transitive subclass** via `makeStreamingModel`; README TUI example points at `train-github-tool.ts`. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 99cb197. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Claude Fable 5 <[email protected]> Co-authored-by: p6 <p6@local>

Note
High Risk
Large feature addition that introduces a new vision-language model pipeline (image preprocessing, prompt formatting, weight conversion, GPU inference, and KV-cache reuse), which can impact correctness and performance in core generation paths.
Overview
Adds end-to-end support for the
qianfan-ocrmodel, including a newQianfanOCRModelNAPI API (load,chat,chatStream,generate) that integrates InternViT vision encoding, a pixel-shuffle + MLP bridge, and a Qwen3-based language model with optional KV-cache reuse.Introduces Qianfan-OCR-specific building blocks: config + JS factory, InternVL chat template formatting (images, thinking, tools), dynamic image tiling/normalization, and HuggingFace→internal weight-key transformation (including Conv2D transposition). The conversion pipeline now recognizes
model_type: qianfan-ocrfor weight sanitization, and a small TS smoke test validates the new NAPI bindings.Updates docs to reflect the Vite+ CLI change from
vitetovp, including new command grouping and CI setup guidance.Written by Cursor Bugbot for commit cb82f14. This will update automatically on new commits. Configure here.