Skip to content

perf(vlm): 5.9x decode speedup via C++ fused forward pass with dtype fix and compiled SwiGLU - #14

Merged
Brooooooklyn merged 6 commits into
mainfrom
vlm-perf
Feb 4, 2026
Merged

Brooooooklyn merged 6 commits into
mainfrom
vlm-perf

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Feb 3, 2026 •

Copy link
Copy Markdown
Contributor

Move the PaddleOCR-VL decode forward pass entirely to C++ and fix two critical performance issues that were causing a 3x gap vs Python mlx-vlm:

  1. dtype promotion fix: mRoPE cos/sin were computed in float32 but never cast back to the model's dtype (float16). This caused Q*cos to promote Q, K, KV cache, and SDPA to float32 — doubling memory and halving throughput. Fix: cos.astype(input_embeds.dtype()), matching Python's cos.astype(x.dtype). (85 → 246 tok/s)

  2. Compiled SwiGLU: Python's nn.silu uses @mx.compile to fuse sigmoid(x)*x into a single Metal kernel. Our C++ did 3 separate kernel launches. Fix: use mlx::core::compile() with shapeless=true to fuse the SwiGLU activation. (246 → 288 tok/s)

Additional optimizations in this branch:

  • C++ fused forward pass (mlx_paddleocr_vl_forward_step) eliminates ~1400 NAPI FFI calls per decode step, reducing to ~6
  • Pre-sectioned mRoPE cos/sin computed once outside the layer loop
  • Pre-transposed weight matrices avoid redundant transposes per layer
  • GPU-CPU pipelined decode loop with zero-copy token passing
  • Vision encoder attention mask improvements

Performance progression:
NAPI path: ~49 tok/s (baseline)
C++ fused: ~82 tok/s (1.7x)
Pipelined: ~90 tok/s (1.8x)
dtype fix: ~246 tok/s (5.0x)
Compiled SwiGLU: ~288 tok/s (5.9x)
Python mlx-vlm: ~264 tok/s (reference)


Note

High Risk
High risk because it rewires PaddleOCR-VL generation to a new fused C++/FFI execution path (KV caching, mRoPE, attention) and changes lazy/eval behavior, which can impact correctness, memory usage, and runtime stability across devices.

Overview
PaddleOCR-VL generation is reworked for performance by introducing a fused C++ transformer forward (mlx_paddleocr_vl_forward_step) with Rust-side fused KV cache management, chunked prefill, GPU/CPU pipelined decode on a dedicated stream, and dtype-alignment fixes to avoid float32 promotion during multimodal embedding/vision-text merging.

Core MLX ops/FFI are extended and adjusted: new split_at_indices binding, SDPA mask handling and broader use of fused SDPA (including vision encoder attention masks), vectorized repetition penalty via put_along_axis, and C++ copy/SDPA paths no longer force eager eval().

New output/interop features: PaddleOCR-VL parser adds OutputFormat::Json plus XLSX export (documentToXlsx, saveToXlsx) backed by rust_xlsxwriter with Node bindings/tests; model conversion now accepts modelType (auto-detected) to apply PaddleOCR-VL weight sanitization and detects already-MLX-formatted weights.

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

Summary by CodeRabbit

  • New Features

    • Array splitting by explicit indices; JSON and XLSX export APIs and CLI --model-type option; generation benchmark script; JS bindings for XLSX exports.
  • Performance Improvements

    • Pipelined GPU–CPU generation with fused forward/KV-cache paths; fused attention and vectorized sampling; improved vision encoder masking and multimodal RoPE handling.
  • Documentation

    • CLI help for model-type and doc note on fused multimodal rotary embedding.
  • Chores

    • Updated .gitignore and added XLSX writer workspace dependency.
  • Tests

    • Added XLSX export unit tests.

…fix and compiled SwiGLU

Move the PaddleOCR-VL decode forward pass entirely to C++ and fix two
critical performance issues that were causing a 3x gap vs Python mlx-vlm:

1. **dtype promotion fix**: mRoPE cos/sin were computed in float32 but
   never cast back to the model's dtype (float16). This caused Q*cos to
   promote Q, K, KV cache, and SDPA to float32 — doubling memory and
   halving throughput. Fix: `cos.astype(input_embeds.dtype())`, matching
   Python's `cos.astype(x.dtype)`. (85 → 246 tok/s)

2. **Compiled SwiGLU**: Python's nn.silu uses @mx.compile to fuse
   sigmoid(x)*x into a single Metal kernel. Our C++ did 3 separate
   kernel launches. Fix: use mlx::core::compile() with shapeless=true
   to fuse the SwiGLU activation. (246 → 288 tok/s)

Additional optimizations in this branch:
- C++ fused forward pass (mlx_paddleocr_vl_forward_step) eliminates
  ~1400 NAPI FFI calls per decode step, reducing to ~6
- Pre-sectioned mRoPE cos/sin computed once outside the layer loop
- Pre-transposed weight matrices avoid redundant transposes per layer
- GPU-CPU pipelined decode loop with zero-copy token passing
- Vision encoder attention mask improvements

Performance progression:
  NAPI path:        ~49 tok/s (baseline)
  C++ fused:        ~82 tok/s (1.7x)
  Pipelined:        ~90 tok/s (1.8x)
  dtype fix:       ~246 tok/s (5.0x)
  Compiled SwiGLU: ~288 tok/s (5.9x)
  Python mlx-vlm:  ~264 tok/s (reference)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Feb 3, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Adds fused mRoPE and fused PaddleOCR‑VL forward/generation paths with GPU‑CPU pipelining and fused KV cache handling; vectorized repetition‑penalty sampling; new array-splitting API and FFI/C++ fused generation entrypoints; XLSX/JSON parser exports and model‑type aware conversion.

Changes

Cohort / File(s) Summary
Build / tooling
\.gitignore, Cargo.toml, crates/mlx-sys/mlx
Ignore *.metallib and .vite-agent; add workspace rust_xlsxwriter dependency; update mlx submodule pointer.
Core array & attention
crates/mlx-core/src/array/attention.rs, crates/mlx-core/src/array/mod.rs
Inlined scaled_dot_product_attention and replaced CString "" construction; added MxArray::split_at_indices() API and removed slice_assign_axis.
Vision encoder / attention
crates/mlx-core/src/vision/encoder.rs
Added build_attention_mask() and replaced manual QKV attention with fused scaled_dot_product_attention; forward now accepts cu_seqlens.
Language model (mRoPE & fused KV)
crates/mlx-core/src/models/paddleocr_vl/language.rs
Pre-shaped inv_freq for broadcasting; exposed get_inv_freq_ptr/mrope_section_arr; added fused KV cache fields and management APIs; added forward_fused() and layer weight pointer accessors.
Generation pipeline (VLModel)
crates/mlx-core/src/models/paddleocr_vl/model.rs
Reworked generate to GPU‑CPU pipelined prefill+decode using Streams and fused KV paths; chunked fused prefill, two‑phase pipelined decode, integrated sampling/repetition penalty, periodic cache clearing.
Sampling / penalties
crates/mlx-core/src/sampling.rs
Rewrote repetition penalty to vectorized gather/scatter (take_along_axis/put_along_axis) with explicit 1D/2D handling; early returns clone logits.
FFI surface & C++ backend
crates/mlx-sys/src/lib.rs, crates/mlx-sys/src/mlx.cpp
Added mlx_array_split_at_indices and fused forward/generation APIs (PaddleOCR‑VL, Qwen3 batched/step/generate); removed some eager eval() calls; implemented fused mRoPE, SwiGLU, KV-cache and generation helpers in C++.
Bindings / types / convert
packages/core/index.d.cts, crates/mlx-core/src/convert.rs, scripts/convert-model.ts
Added modelType/model_type options to conversion paths; convert supports model-specific sanitization (e.g., paddleocr-vl) and CLI --model-type with auto-detect via config.
PaddleOCR‑VL persistence
crates/mlx-core/src/models/paddleocr_vl/persistence.rs
Added MLX-format fast path: detect MLX keys and pass through/filter ignored keys instead of HF transformation.
Parser / exports (JSON/XLSX)
crates/mlx-core/src/models/paddleocr_vl/parser.rs, packages/core/index.cjs, packages/vlm/src/index.ts, __test__/models/paddleocr-vl-xlsx.test.ts
Added OutputFormat::Json, JSON formatter, XLSX export (document_to_xlsx, save_to_xlsx) with N-API bindings; exposed JS bindings, re-exports, and tests.
Examples / benchmarks / tests
examples/test-mlx-vlm-speed.py, __test__/models/paddleocr-vl-xlsx.test.ts
Added VLM speed benchmark script and XLSX-related tests.
Build script
crates/mlx-sys/build.rs, crates/mlx-core/Cargo.toml
Defined MLX_STATIC in build.rs; added rust_xlsxwriter dependency to crates/mlx-core Cargo.toml.

Sequence Diagram

sequenceDiagram
    participant Client
    participant CPU as CPU (Main Loop)
    participant GPU as GPU Stream
    participant Lang as LangModel
    participant Sampler as Sampler

    rect rgba(100,150,200,0.5)
    Note over Client,Lang: Prefill (fused, chunked)
    Client->>Lang: forward_fused(prefill_embeds)
    Lang->>GPU: enqueue fused forward (forward_fused)
    GPU-->>Lang: logits + fused KV (async)
    end

    rect rgba(150,100,200,0.5)
    Note over CPU,Sampler: Decode loop (pipelined)
    loop each token
        par Phase 1: GPU builds & computes next token
            Lang->>GPU: build and eval step N+1 (async)
            GPU-->>Lang: logits_N+1
        and Phase 2: CPU extracts & samples token N
            Lang->>CPU: expose logits_N
            CPU->>Sampler: apply repetition penalty (vectorized gather/scatter)
            Sampler->>CPU: sample token
            CPU->>Lang: update position_ids & fused cache idx
        end
    end
    end

    rect rgba(200,150,100,0.5)
    Note over CPU,Lang: Cleanup
    CPU->>Lang: reset_fused_kv_caches()
    Lang-->>CPU: caches reset
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰
I nibbled bytes and braided Rope,
Fused caches hummed — a clever hope,
GPU leaps while CPU sings,
Tokens hop out on stitched-up strings,
Rabbity cheers for faster springs!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main performance improvement: a 5.9x decode speedup achieved via C++ fused forward pass, dtype fix, and compiled SwiGLU. It is specific, concise, and directly reflects the primary objectives of the PR.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 vlm-perf

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

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

@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: 7

Caution

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

⚠️ Outside diff range comments (1)
crates/mlx-core/src/models/paddleocr_vl/language.rs (1)

385-442: ⚠️ Potential issue | 🟡 Minor

Attention mask is now ignored in this path.
_mask is unused; if callers ever rely on padding or custom masks, outputs will attend to masked tokens. Please confirm mask is always None here or reintroduce masking support.

🤖 Fix all issues with AI agents
In `@crates/mlx-core/src/array/mod.rs`:
- Around line 414-419: The doc comment describing "Fused multimodal rotary
position embedding (mRoPE)" is incorrectly attached to the transpose function;
update the documentation so it accurately describes transpose or move the mRoPE
doc to the actual fused mRoPE API. Locate the transpose function (named
transpose) and replace the mRoPE doc block with a brief, transpose-specific
description (what it transposes, dimensions/shape semantics, panics/returns),
and place the mRoPE documentation on the actual mRoPE function/type (or create a
new mrope_fused/mrope function) ensuring the doc accurately references the fused
C++ operation and its arguments.
- Around line 1157-1192: The split_at_indices method is missing the #[napi]
export and lacks axis/indices validation; add the #[napi] attribute to pub fn
split_at_indices and before calling the FFI normalize and validate axis (handle
negative axis like other array methods), validate indices are non-empty (if
required), ensure each index is within [0, dim) for the target axis, ensure the
indices are strictly increasing/sorted (or sort and deduplicate as per module
convention), and return an Error with appropriate Status when out-of-bounds or
invalid; then pass the validated/normalized indices and axis to
sys::mlx_array_split_at_indices exactly as done in sibling split() to avoid
sending invalid values to the FFI.

In `@crates/mlx-core/src/models/paddleocr_vl/language.rs`:
- Around line 879-963: forward_fused currently assumes init_fused_kv_caches()
ran and indexes self.fused_kv_keys / self.fused_kv_values directly which can
panic; add a guard at the top of forward_fused that verifies the fused KV caches
are initialized (e.g., check self.fused_kv_keys.len() == num_layers &&
self.fused_kv_values.len() == num_layers and optionally that entries are
Some(...) as required) and return an Err immediately with a clear message if not
initialized (instead of panicking). Update references in forward_fused (where it
builds kv_keys_ptrs / kv_values_ptrs and later when updating from out_kv_* ) to
use safe indexing/get() after the guard. Ensure the error follows the function's
Result<MxArray> error type.

In `@crates/mlx-core/src/models/paddleocr_vl/model.rs`:
- Around line 829-856: The repetition-penalty call in Phase 1
(apply_repetition_penalty) is using all_tokens which is only updated after Phase
2, so the most-recent token emitted by the pipeline is omitted; fix by
constructing a temporary token list that includes the current/latest token and
pass that to apply_repetition_penalty (e.g. build penalty_tokens = all_tokens +
[token.clone() or the last emitted token] or update all_tokens before calling
apply_repetition_penalty), keeping the same parameters (repetition_penalty,
Some(repetition_context_size)); update references around token, all_tokens, and
apply_repetition_penalty to use this temporary list so Phase 1 penalties match
the non-pipelined path.

In `@crates/mlx-core/src/vision/encoder.rs`:
- Around line 79-132: The build_attention_mask function must validate cu_seqlens
before using it: check that cu_seqlens.size() > 0, that the first boundary is 0,
that the last boundary equals seq_len, and that boundaries are non-decreasing
(each cu_seqlens.item_at_int32(i) <= cu_seqlens.item_at_int32(i+1)); if any
check fails return an Err with a clear message instead of proceeding to build
segment_ids. Add these guards near the start of build_attention_mask (before
computing num_boundaries or iterating boundaries) and reference cu_seqlens,
seq_len, num_boundaries and the loop over b when implementing the checks so the
function refuses to create a mask from invalid boundaries.

In `@crates/mlx-sys/src/mlx.cpp`:
- Around line 1963-1979: The function mlx_array_split_at_indices dereferences
indices unconditionally; add a guard at the start of mlx_array_split_at_indices
to return 0 early if indices is nullptr while indices_len > 0 (and optionally
validate out_handles is non-null when max_outputs > 0) to avoid UB across the
FFI boundary, then proceed to build mlx::core::Shape only when indices is valid
and continue the existing logic to populate out_handles and return the count.

In `@packages/core/index.d.cts`:
- Around line 267-275: The JSDoc describing "Fused multimodal rotary position
embedding (mRoPE)" is incorrectly attached to the transpose() declaration;
update the documentation so it no longer misleads TypeScript users by either
moving that doc block to the actual mRoPE API (if one exists) or
removing/rewriting it here to describe transpose() accurately. Locate the
transpose(axes?: Int32Array | undefined | null): MxArray signature and replace
the mRoPE text with a correct description of transpose behavior (or relocate the
full mRoPE doc to the mRoPE function/class symbol) ensuring the doc comments
reference the correct API symbol names.
🧹 Nitpick comments (2)
crates/mlx-core/src/models/paddleocr_vl/model.rs (2)

681-706: Verify the wired‑memory size assumption for non‑fp16/bf16 weights.
dtype_bytes is hardcoded to 2; if weights load as fp32 (or quantized), the wired limit can be under/over-estimated. Consider deriving this from an actual weight dtype or documenting the fp16/bf16‑only assumption.


819-823: ngram_size < 8 effectively disables repetition checks.
With min_pattern_len = 8, any user‑set ngram_size below 8 results in no checks. Consider clamping min_pattern_len to ngram_size or documenting this behavior.

Comment thread crates/mlx-core/src/array/mod.rs Resolved
Comment thread crates/mlx-core/src/array/mod.rs Resolved
Comment thread crates/mlx-core/src/vision/encoder.rs Resolved
Comment thread crates/mlx-sys/src/mlx.cpp Resolved
Comment thread packages/core/index.d.cts Resolved

@cursor cursor 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.

Cursor Bugbot has reviewed your changes and found 2 potential issues.

Bugbot Autofix is OFF. To automatically fix reported issues with Cloud Agents, enable Autofix in the Cursor dashboard.

Comment thread crates/mlx-sys/src/mlx.cpp Resolved
Brooooooklyn and others added 2 commits February 4, 2026 08:08
Root cause: Vision encoder outputs float32 (from float32 pixel inputs),
which when merged with bfloat16 text embeddings promoted the entire KV
cache and all decode operations to float32 (2x memory bandwidth).

Fix: Cast vision features to match language model embedding dtype before
merging. Also adds chunked prefill, stream contexts for GPU-CPU overlap,
eval_fused_kv_caches for graph materialization, and first-token sync eval
to eliminate step 0 penalty.

Before: Image decode 61 tok/s (5.5x slower than Python mlx-vlm 274 tok/s)
After:  Image decode 301 tok/s (1.10x FASTER than Python mlx-vlm 274 tok/s)
        Text decode 316 tok/s (1.07x faster than Python 296 tok/s)

Also includes:
- MLX format auto-detection in weight loader (passthrough for sanitized weights)
- Model-type-specific weight sanitization in converter
- Python benchmark script for mlx-vlm comparison

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

@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: 2

🤖 Fix all issues with AI agents
In `@crates/mlx-core/src/models/paddleocr_vl/persistence.rs`:
- Around line 92-103: The current MLX-format detection uses is_mlx_format =
weights.keys().any(|k| k.starts_with("language_model.")) which can mis-identify
mixed maps as MLX and skip HF transforms; change the guard so you only treat the
map as MLX when there are MLX keys present AND there are no HF-style prefixes
remaining (e.g., ensure no key starts with HF prefixes like
"visual.vision_model.", "text_model.", or other HF naming used elsewhere).
Modify the logic around is_mlx_format (and the early return that uses
weights.into_iter().filter(|(k,_)| !should_ignore_key(k)).collect()) to check
both presence of MLX keys and absence of any HF prefixes before short-circuiting
so mixed-format weight maps fall through to the HF transformation path.

In `@scripts/convert-model.ts`:
- Around line 25-28: The import currently pulls convertModel from the disallowed
package `@mlx-node/core`; change the import to use the allowed re-export from
`@mlx-node/trl` by replacing the convertModel import source so the statement
imports convertModel from '@mlx-node/trl' (update the import that references
convertModel to point to '@mlx-node/trl' instead of '@mlx-node/core').
🧹 Nitpick comments (1)
crates/mlx-core/src/convert.rs (1)

289-373: Recompute num_parameters after sanitization for accuracy.

Sanitization can drop/merge tensors (ignored keys, QKV merge), but num_parameters still reflects the pre‑sanitized count. Consider recomputing from converted_tensors so the reported stats match what’s written.

♻️ Possible adjustment
-    let converted_tensors = match model_type.as_deref() {
+    let converted_tensors = match model_type.as_deref() {
         Some("paddleocr-vl") => {
             info!(
                 "Applying PaddleOCR-VL weight sanitization (key renaming, Q/K/V merging, conv2d transposition)..."
             );
             load_paddleocr_vl_weights(converted_tensors)?
         }
         Some(other) => {
             return Err(Error::from_reason(format!(
                 "Unknown model type: '{}'. Supported: paddleocr-vl",
                 other
             )));
         }
         None => converted_tensors,
     };
+
+    // Optional: recompute parameter count after sanitization
+    let num_parameters: i64 = converted_tensors
+        .values()
+        .try_fold(0i64, |acc, t| Ok(acc + t.size()? as i64))?;

Comment thread scripts/convert-model.ts Resolved

@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: 1

🤖 Fix all issues with AI agents
In `@crates/mlx-sys/src/mlx.cpp`:
- Around line 4697-4720: The function mlx_paddleocr_vl_forward_step lacks FFI
safety checks and exception handling; add null-pointer guards at the top to
validate input_embeds_handle, layer_weights, final_norm_weight_handle,
lm_head_weight_handle, inv_freq_handle, position_ids_handle, mrope_section and
the output pointer slots out_logits, out_kv_keys, out_kv_values, out_cache_idx
before any reinterpret_casts, and return early (setting outputs to nullptr/0 if
provided) on invalid inputs; wrap the entire implementation body in a
try/catch(...) block to catch all exceptions, translate them to a safe failure
path (clean up if needed, set outputs to nullptr/0) and avoid letting exceptions
propagate across the FFI boundary; keep the rest of the logic unchanged and only
perform reinterpret_casts after the null checks.
🧹 Nitpick comments (1)
crates/mlx-sys/src/mlx.cpp (1)

4735-4758: Pre-transposing weights is a good optimization.

Pre-transposing all layer weights once before the layer loop (instead of per-layer) saves ~119 transpose operations for an 18-layer model. This is a clean optimization that improves decode throughput.

Consider adding a brief comment documenting the 9-weight-per-layer layout for maintainability:

// Layer weights layout (9 per layer):
// [0]=input_norm, [1]=post_attn_norm, [2]=w_q, [3]=w_k, [4]=w_v,
// [5]=w_o, [6]=w_gate, [7]=w_up, [8]=w_down

Comment thread crates/mlx-sys/src/mlx.cpp Resolved
@Brooooooklyn
Brooooooklyn merged commit 46c4e59 into main Feb 4, 2026
6 checks passed
@Brooooooklyn
Brooooooklyn deleted the vlm-perf branch February 4, 2026 09:55
Brooooooklyn added a commit that referenced this pull request Apr 11, 2026
…fix and compiled SwiGLU (#14)

Move the PaddleOCR-VL decode forward pass entirely to C++ and fix two
critical performance issues that were causing a 3x gap vs Python
mlx-vlm:

1. **dtype promotion fix**: mRoPE cos/sin were computed in float32 but
never cast back to the model's dtype (float16). This caused Q*cos to
promote Q, K, KV cache, and SDPA to float32 — doubling memory and
halving throughput. Fix: `cos.astype(input_embeds.dtype())`, matching
Python's `cos.astype(x.dtype)`. (85 → 246 tok/s)

2. **Compiled SwiGLU**: Python's nn.silu uses @mx.compile to fuse
sigmoid(x)*x into a single Metal kernel. Our C++ did 3 separate kernel
launches. Fix: use mlx::core::compile() with shapeless=true to fuse the
SwiGLU activation. (246 → 288 tok/s)

Additional optimizations in this branch:
- C++ fused forward pass (mlx_paddleocr_vl_forward_step) eliminates
~1400 NAPI FFI calls per decode step, reducing to ~6
- Pre-sectioned mRoPE cos/sin computed once outside the layer loop
- Pre-transposed weight matrices avoid redundant transposes per layer
- GPU-CPU pipelined decode loop with zero-copy token passing
- Vision encoder attention mask improvements

Performance progression:
  NAPI path:        ~49 tok/s (baseline)
  C++ fused:        ~82 tok/s (1.7x)
  Pipelined:        ~90 tok/s (1.8x)
  dtype fix:       ~246 tok/s (5.0x)
  Compiled SwiGLU: ~288 tok/s (5.9x)
  Python mlx-vlm:  ~264 tok/s (reference)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> High risk because it rewires PaddleOCR-VL generation to a new fused
C++/FFI execution path (KV caching, mRoPE, attention) and changes
lazy/eval behavior, which can impact correctness, memory usage, and
runtime stability across devices.
> 
> **Overview**
> **PaddleOCR-VL generation is reworked for performance** by introducing
a fused C++ transformer forward (`mlx_paddleocr_vl_forward_step`) with
Rust-side fused KV cache management, chunked prefill, GPU/CPU pipelined
decode on a dedicated stream, and dtype-alignment fixes to avoid float32
promotion during multimodal embedding/vision-text merging.
> 
> **Core MLX ops/FFI are extended and adjusted**: new `split_at_indices`
binding, SDPA mask handling and broader use of fused SDPA (including
vision encoder attention masks), vectorized repetition penalty via
`put_along_axis`, and C++ copy/SDPA paths no longer force eager
`eval()`.
> 
> **New output/interop features**: PaddleOCR-VL parser adds
`OutputFormat::Json` plus XLSX export (`documentToXlsx`, `saveToXlsx`)
backed by `rust_xlsxwriter` with Node bindings/tests; model conversion
now accepts `modelType` (auto-detected) to apply PaddleOCR-VL weight
sanitization and detects already-MLX-formatted weights.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
a04eaa8. 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

* **New Features**
* Array splitting by explicit indices; JSON and XLSX export APIs and CLI
--model-type option; generation benchmark script; JS bindings for XLSX
exports.

* **Performance Improvements**
* Pipelined GPU–CPU generation with fused forward/KV-cache paths; fused
attention and vectorized sampling; improved vision encoder masking and
multimodal RoPE handling.

* **Documentation**
* CLI help for model-type and doc note on fused multimodal rotary
embedding.

* **Chores**
  * Updated .gitignore and added XLSX writer workspace dependency.

* **Tests**
  * Added XLSX export unit tests.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.5 <[email protected]>
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
…ounded model walk, no-follow install preflight, genuine-child session metrics

Fix-delta review of the review-#14 fixes surfaced 5 edge-case tails (each a
refinement of an R14 fix, none a reverted/broken fix). All verified via
control-flow analysis before fixing.

Native (crates/mlx-paged-attn/src/cold_cache.rs):
- #5 honest drain durability: the writer discarded persist_block errors and
  acked the barrier unconditionally, so drain() reported success even when a
  covered block failed to persist. Barrier now carries SyncSender<bool>; the
  writer accumulates a per-window failure flag and acks !failed; drain returns
  true only on an Ok(true) ack.
- #4 whole-drain bounded by timeout: drain's blocking send admitted the barrier
  before recv_timeout, so a full queue behind a stuck fsync could exceed the
  timeout or hang exit. Admission is now deadline-aware try_send (recovering the
  barrier job on Full) plus a remaining-time recv_timeout — total wall time is
  bounded by the timeout.

Dashboard:
- #1 (models.ts walkDirStats): readdirSync eagerly materialized the whole
  Dirent[] before the entry budget applied. Switched to incremental
  opendirSync/readSync so the budget bounds memory and time on a pathological
  high-fan-out directory; closeSync in finally.
- #2 (download.ts processJob): existsSync(finalDir) follows symlinks, so a
  dangling finalDir symlink bypassed the ownership preflight and triggered a
  full wasted download. Added a no-follow occupied() (lstatSync) used at the
  preflight and both publish-time ownership checks.
- #3 (api.ts handleSessionMetrics): the session_id = ? OR root_session_id = ?
  union resurrected an abandoned root turn (dropped from turns after a branch)
  as a fake delegated turn, inflating count/token totals. Narrowed to genuine
  children (root_session_id = ? AND session_id != ?); verified the child-trace
  discriminator against the metrics-trace writer.

Also de-flaked download.test.ts's mid-job-error case: staging cleanup runs in
the job finally, after the error event the test unblocks on, so it now waits
for eventual staging reclaim instead of racing that teardown.

Gate: cold_cache 37/0; typecheck 0; dashboard 191/191 (×2, race gone);
lint 0; clippy clean. NAPI signature unchanged — no build:native needed.

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
…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
…ounded model walk, no-follow install preflight, genuine-child session metrics

Fix-delta review of the review-#14 fixes surfaced 5 edge-case tails (each a
refinement of an R14 fix, none a reverted/broken fix). All verified via
control-flow analysis before fixing.

Native (crates/mlx-paged-attn/src/cold_cache.rs):
- #5 honest drain durability: the writer discarded persist_block errors and
  acked the barrier unconditionally, so drain() reported success even when a
  covered block failed to persist. Barrier now carries SyncSender<bool>; the
  writer accumulates a per-window failure flag and acks !failed; drain returns
  true only on an Ok(true) ack.
- #4 whole-drain bounded by timeout: drain's blocking send admitted the barrier
  before recv_timeout, so a full queue behind a stuck fsync could exceed the
  timeout or hang exit. Admission is now deadline-aware try_send (recovering the
  barrier job on Full) plus a remaining-time recv_timeout — total wall time is
  bounded by the timeout.

Dashboard:
- #1 (models.ts walkDirStats): readdirSync eagerly materialized the whole
  Dirent[] before the entry budget applied. Switched to incremental
  opendirSync/readSync so the budget bounds memory and time on a pathological
  high-fan-out directory; closeSync in finally.
- #2 (download.ts processJob): existsSync(finalDir) follows symlinks, so a
  dangling finalDir symlink bypassed the ownership preflight and triggered a
  full wasted download. Added a no-follow occupied() (lstatSync) used at the
  preflight and both publish-time ownership checks.
- #3 (api.ts handleSessionMetrics): the session_id = ? OR root_session_id = ?
  union resurrected an abandoned root turn (dropped from turns after a branch)
  as a fake delegated turn, inflating count/token totals. Narrowed to genuine
  children (root_session_id = ? AND session_id != ?); verified the child-trace
  discriminator against the metrics-trace writer.

Also de-flaked download.test.ts's mid-job-error case: staging cleanup runs in
the job finally, after the error event the test unblocks on, so it now waits
for eventual staging reclaim instead of racing that teardown.

Gate: cold_cache 37/0; typecheck 0; dashboard 191/191 (×2, race gone);
lint 0; clippy clean. NAPI signature unchanged — no build:native needed.

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
…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
…ounded model walk, no-follow install preflight, genuine-child session metrics

Fix-delta review of the review-#14 fixes surfaced 5 edge-case tails (each a
refinement of an R14 fix, none a reverted/broken fix). All verified via
control-flow analysis before fixing.

Native (crates/mlx-paged-attn/src/cold_cache.rs):
- #5 honest drain durability: the writer discarded persist_block errors and
  acked the barrier unconditionally, so drain() reported success even when a
  covered block failed to persist. Barrier now carries SyncSender<bool>; the
  writer accumulates a per-window failure flag and acks !failed; drain returns
  true only on an Ok(true) ack.
- #4 whole-drain bounded by timeout: drain's blocking send admitted the barrier
  before recv_timeout, so a full queue behind a stuck fsync could exceed the
  timeout or hang exit. Admission is now deadline-aware try_send (recovering the
  barrier job on Full) plus a remaining-time recv_timeout — total wall time is
  bounded by the timeout.

Dashboard:
- #1 (models.ts walkDirStats): readdirSync eagerly materialized the whole
  Dirent[] before the entry budget applied. Switched to incremental
  opendirSync/readSync so the budget bounds memory and time on a pathological
  high-fan-out directory; closeSync in finally.
- #2 (download.ts processJob): existsSync(finalDir) follows symlinks, so a
  dangling finalDir symlink bypassed the ownership preflight and triggered a
  full wasted download. Added a no-follow occupied() (lstatSync) used at the
  preflight and both publish-time ownership checks.
- #3 (api.ts handleSessionMetrics): the session_id = ? OR root_session_id = ?
  union resurrected an abandoned root turn (dropped from turns after a branch)
  as a fake delegated turn, inflating count/token totals. Narrowed to genuine
  children (root_session_id = ? AND session_id != ?); verified the child-trace
  discriminator against the metrics-trace writer.

Also de-flaked download.test.ts's mid-job-error case: staging cleanup runs in
the job finally, after the error event the test unblocks on, so it now waits
for eventual staging reclaim instead of racing that teardown.

Gate: cold_cache 37/0; typecheck 0; dashboard 191/191 (×2, race gone);
lint 0; clippy clean. NAPI signature unchanged — no build:native needed.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
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