Skip to content

feat: add PP-StructureV3 document understanding pipeline with PP-OCRv5 text detection and recognition - #15

Merged
Brooooooklyn merged 2 commits into
mainfrom
feat/pp-doclayout-v3
Feb 12, 2026
Merged

Brooooooklyn merged 2 commits into
mainfrom
feat/pp-doclayout-v3

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Feb 12, 2026 •

Copy link
Copy Markdown
Contributor

Implements the full PP-StructureV3 pipeline: PP-DocLayoutV3 (layout detection) + PP-OCRv5 TextDet (text line detection with LKPAN neck + DB head) + PP-OCRv5 TextRec (text recognition with HGNetV2 backbone + SVTR neck + CTC head).

Achieves ~4-5x faster text extraction than VLM-based OCR with ~6x smaller model footprint (292MB vs 1.7GB). Includes PaddlePaddle .pdiparams conversion scripts, ConvTranspose2d FFI support, and the StructureV3Pipeline TypeScript API.


Note

High Risk
High risk due to large new model surface area plus new batched generation logic that merges/filters KV caches and calls unsafe FFI (mlx_paddleocr_vl_forward_step_batched), which can impact correctness and memory/perf.

Overview
Adds new model modules for PP-Structure components, including an initial PP-DocLayoutV3 implementation (HGNetV2 backbone/config plus transformer decoder with deformable attention) with accompanying unit tests.

Extends paddleocr_vl with N-API batch inputs (VLMBatchItem) and new VLModel.batch/VLModel.ocr_batch APIs that do per-item prefill, merge/left-pad KV caches, then run a batched decode loop via a new ERNIELanguageModel batched fused forward path. Includes regression tests to prevent cross-item token/KV misalignment when batch items finish early.

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

Summary by CodeRabbit

  • New Features

    • Added DocLayoutModel (PP-DocLayoutV3), TextDetModel and TextRecModel for layout, text detection, and recognition.
    • VLM: added batch OCR endpoints (ocrBatch, batch) and VlmBatchItem support.
    • New StructureV3 pipeline: end-to-end layout + OCR with Markdown output.
  • API / Types

    • JS exports and typings extended: LayoutElement, TextBox, RecResult, VlmBatchItem; VLModel gains ocrBatch/batch.
  • Chores

    • Updated example, packaging and image-processing dependencies and build typings to support new features.

@coderabbitai

coderabbitai Bot commented Feb 12, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Adds three new ML model families (PP-DocLayoutV3, PP-TextDet, PP-TextRec) with SafeTensors loaders and N-API bindings, implements batched PaddleOCR‑VL generation (per-item KV caches + batched forward), exports native conv2d/conv_transpose2d FFI, updates TypeScript bindings/packages, and adds a StructureV3 pipeline composing layout→detection→recognition.

Changes

Cohort / File(s) Summary
PP-DocLayoutV3 model
crates/mlx-core/src/models/pp_doclayout_v3/mod.rs, .../config.rs, .../backbone.rs, .../encoder.rs, .../decoder.rs, .../heads.rs, .../model.rs, .../persistence.rs, .../postprocessing.rs, .../processing.rs
New full PP-DocLayoutV3 implementation: config, HGNetV2 backbone, hybrid encoder, transformer decoder, heads, image processing, postprocessing (LayoutElement), SafeTensors persistence loader, N-API DocLayoutModel, tests.
PP-TextDet model
crates/mlx-core/src/models/pp_text_det/mod.rs, .../config.rs, .../lkpan.rs, .../db_head.rs, .../model.rs, .../persistence.rs, .../postprocessing.rs, .../processing.rs
New PP-OCRv5 DBNet text-detection: config, LKPAN neck, PFHeadLocal/DB head, image processor, postprocessing (TextBox), SafeTensors loader, N-API TextDetModel, tests.
PP-TextRec model
crates/mlx-core/src/models/pp_text_rec/mod.rs, .../config.rs, .../svtr_neck.rs, .../ctc_head.rs, .../dictionary.rs, .../model.rs, .../persistence.rs, .../processing.rs
New PP-OCRv5 text-recognition: config, SVTR neck, CTC head, CharDictionary, image processor, persistence loader, N-API TextRecModel and batch/single recognition APIs, tests.
PaddleOCR‑VL batching
crates/mlx-core/src/models/paddleocr_vl/chat.rs, .../mod.rs, .../language.rs, .../model.rs
Added VLMBatchItem type and batched public APIs (batch, ocr_batch), ERNIELanguageModel fused-batched methods (forward_fused_extract_kv, forward_fused_batched), and large batched decode/generation implementation with per-item KV cache handling and tests.
MLX FFI & C++ batched forward
crates/mlx-sys/src/lib.rs, crates/mlx-sys/src/mlx.cpp
New FFI exports: mlx_conv2d, mlx_conv_transpose2d, and mlx_paddleocr_vl_forward_step_batched plus C++ batched PaddleOCR‑VL transformer implementation (batched KV cache, batched RoPE, create_batched_causal_mask).
Rust conv path & tests
crates/mlx-core/src/vision/conv2d.rs
Replaced fallback conv with MLX FFI-backed general conv path; added tests exercising the general FFI convolution path and bias handling.
TypeScript bindings & packages
packages/core/index.cjs, packages/core/index.d.cts, packages/core/tsconfig.json, packages/vlm/*, examples/*, packages/vlm/src/pipeline/structure-v3.ts
Added JS/TS exports and typings for DocLayoutModel/PPDocLayoutV3Model, TextDetModel, TextRecModel, VlmBatchItem, RecResult, LayoutElement, TextBox; converted OutputFormat to enum; added StructureV3 pipeline (structure-v3) that composes layout→det→rec and a VLM batch-enabled example.
Build/tsconfig tweaks
packages/core/build.ts, tsconfig.json, packages/*/tsconfig.json
Minor build output post-processing and updated project references for new packages.
Examples & packaging
examples/vlm-inference.ts, examples/package.json
Reworked VLM example into combined layout→OCR pipeline, added CLI flags, uses batch OCR; bumped some JS deps and added @napi-rs/image.

Sequence Diagram(s)

sequenceDiagram
    participant App as Application
    participant VLM as PaddleOCR-VL
    participant Tokenizer as Tokenizer/Embedder
    participant KV as KV Cache Manager
    participant Decoder as Batched Decoder

    App->>VLM: batch(Vec<VLMBatchItem>, config)
    VLM->>Tokenizer: per-item tokenize + vision features
    Tokenizer->>KV: prefill per-item KV caches
    KV->>KV: left-pad & stack per-layer KV caches (batched state)
    loop decode positions
        VLM->>Decoder: forward_fused_batched(all_inputs, left_padding, kvs)
        Decoder->>KV: update per-layer batched KV caches
        Decoder->>VLM: logits + per-item next tokens
        VLM->>VLM: filter completed items (EOS) and shrink batch
    end
    VLM->>App: Vec<VLMChatResult>
Loading
sequenceDiagram
    participant App as Application
    participant Structure as StructureV3 Pipeline
    participant Layout as DocLayoutModel
    participant Det as TextDetModel
    participant Rec as TextRecModel
    participant Crop as Image Crop/Processor
    participant Formatter as Markdown Assembler

    App->>Structure: analyze(image_path, options)
    Structure->>Layout: detect(image_path, threshold)
    Layout->>Structure: Vec<LayoutElement>
    loop each layout element (reading order)
        Structure->>Crop: crop element region -> tmp image
        alt element is text-capable
            Structure->>Det: detect(crop)
            Det->>Structure: Vec<TextBox>
            loop each text line
                Structure->>Crop: crop line region
                Structure->>Rec: recognize or recognizeBatch(line crops)
                Rec->>Structure: RecResult(s)
            end
        else
            Structure->>Structure: placeholder/formatting
        end
    end
    Structure->>Formatter: assemble markdown from elements + OCR
    Formatter->>App: markdown, StructuredDocument
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

Poem

🐰 Hop, hop—new models in a row,

Layout maps the pages we know,
Det finds lines, Rec reads each line,
Batched VLM hums with caches fine,
TypeScript ties the garden bright—code hops into light!

🚥 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 and specifically describes the main feature: adding a PP-StructureV3 document understanding pipeline with PP-OCRv5 text detection and recognition.
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 feat/pp-doclayout-v3

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

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/vision/conv2d.rs (1)

184-252: ⚠️ Potential issue | 🟠 Major

Guard the patch‑embedding fast path against dilation/groups.
Line 186: the fast‑path condition ignores _dilation and _groups, so grouped or dilated convs that still match kernel/stride/padding will take the fast path and return incorrect results. Gate the fast path to (1,1) dilation and groups == 1 so those cases fall back to the FFI path.

🔧 Suggested fix
-    if k_h == stride.0 as i64 && k_w == stride.1 as i64 && padding.0 == 0 && padding.1 == 0 {
+    if k_h == stride.0 as i64
+        && k_w == stride.1 as i64
+        && padding.0 == 0
+        && padding.1 == 0
+        && _dilation == (1, 1)
+        && _groups == 1
+    {
🤖 Fix all issues with AI agents
In `@crates/mlx-core/src/models/paddleocr_vl/model.rs`:
- Around line 1248-1265: The generate_batch method can panic when called with an
empty input because item_cache_idxs.iter().max().unwrap() assumes non-empty
data; add a defensive guard at the start of generate_batch (use the existing
variables: all_input_ids, batch_size, or item_cache_idxs) to handle empty
inputs—either return Ok with an empty Vec<GenerationResult> or return an
Err—before any use of item_cache_idxs.iter().max().unwrap(); ensure any
downstream logic that assumes non-zero batch_size is skipped after this check.

In `@crates/mlx-core/src/models/pp_doclayout_v3/decoder.rs`:
- Around line 266-281: MultiscaleDeformableAttention::new currently doesn't
validate that d_model is divisible by num_heads, which leads to silent
truncation when computing hidden_dim = d_model / n_heads; add a check at the
start of the new function to return an Err if d_model % num_heads != 0
(mirroring SelfAttention::new validation), and only proceed to construct Linear
layers and compute hidden_dim after the check; reference the new constructor
(MultiscaleDeformableAttention::new), the parameters d_model and num_heads, and
the derived hidden_dim in your changes.

In `@crates/mlx-core/src/models/pp_doclayout_v3/encoder.rs`:
- Around line 380-419: The FFN residual is taken after applying final_layer_norm
in the pre-norm path; when self.normalize_before is true you should capture the
residual before calling final_layer_norm so the skip adds the original x +
FFN(norm(x)), not norm(x)+FFN(norm(x)). In the forward method, before the FFN
block use a temp like pre_ffn = x.clone() (the value coming into the FFN), then
if self.normalize_before call self.final_layer_norm.forward(&x)? and set
residual = pre_ffn.clone(); proceed with fc1/apply_activation/fc2 and add
residual; keep existing behavior for the post-norm (normalize_before == false)
path.

In `@crates/mlx-core/src/models/pp_doclayout_v3/heads.rs`:
- Around line 110-115: The GlobalPointer struct's head_size field is an i32
which can be negative and later gets cast to u32 for dimensions (causing huge
allocations); change head_size to an unsigned type (u32/usize) or add a
validation in the constructor/new function that ensures head_size > 0 and
returns a Result or panics on invalid input; update all uses of head_size (e.g.,
where you compute (head_size * 2) as u32) to use the new unsigned type or the
validated/cast value so Linear::new/dense creation cannot receive a wrapped
large size; reference symbols: GlobalPointer, head_size, dense, Linear, and the
constructor/new function that builds GlobalPointer.

In `@crates/mlx-core/src/models/pp_doclayout_v3/postprocessing.rs`:
- Around line 50-112: The code assumes batch size == 1 but indexes tensors as if
unbatched (symbols: scores.shape(), scores_shape, scores_vec, boxes_vec, total,
num_queries, num_labels, pred_boxes), which will silently break for batch > 1;
add an explicit guard after reading scores_shape (e.g., let batch =
scores_shape[0] as usize) and if batch != 1 return an error (or Err with a clear
message) indicating batched inputs are unsupported, and likewise validate
pred_boxes has matching batch dim before continuing so the subsequent uses of
scores_vec[..total] and indexing into boxes_vec (query_idx * 4) are safe.

In `@crates/mlx-core/src/models/pp_text_det/lkpan.rs`:
- Around line 207-256: The forward method (function forward) assumes exactly 4
pyramid levels and directly indexes ins[0..3], self.ins_convs, self.inp_convs,
self.pan_head_convs, and self.pan_lat_convs which will panic on unexpected
input; add an upfront validation in forward that checks features.len() == 4 and
that self.ins_convs.len() == features.len(), self.inp_convs.len() >= 4,
self.pan_head_convs.len() >= 3, self.pan_lat_convs.len() >= 4 (and if
intracl_blocks.is_some() then intracl_blocks.len() == 4), and if any check fails
return an Err with a clear message (rather than indexing and panicking); keep
the rest of the implementation (upsample_nearest_to_match,
MxArray::concatenate_many, etc.) unchanged so subsequent code can assume
validated lengths.

In `@crates/mlx-core/src/models/pp_text_det/processing.rs`:
- Around line 177-219: process_crop must validate that width and height are
non-zero and that rgb_data length matches width * height * 3 before allocating
or calling RgbImage::from_raw; update the function to check (1) if width == 0 or
height == 0 return a descriptive InvalidArg error naming the bad dimension(s),
(2) compute expected_len = (width as usize) * (height as usize) * 3 and if
rgb_data.len() != expected_len return an InvalidArg error describing the
mismatch, and only then call RgbImage::from_raw (or convert rgb_data to a Vec)
to avoid the unnecessary rgb_data.to_vec() allocation; reference symbols:
process_crop, RgbImage::from_raw, rgb_data, width, height.

In `@crates/mlx-core/src/models/pp_text_rec/ctc_head.rs`:
- Around line 60-65: ctc_greedy_decode currently assumes logits is 3D and
indexes shape[2], which will panic for other ranks; add a guard after let shape
= logits.shape()? to check shape.len() == 3 and if not return a structured
InvalidArg error (e.g., Err(Error::InvalidArg("ctc_greedy_decode expects logits
with rank 3".into()))), so callers receive a clear InvalidArg instead of a
panic; reference symbols: ctc_greedy_decode, logits, shape, InvalidArg.

In `@crates/mlx-core/src/models/pp_text_rec/dictionary.rs`:
- Around line 50-57: The loop that parses dictionary lines currently skips empty
lines (the check on ch.is_empty()), which silently shifts character indices;
update the parser that iterates over content.lines() to detect empty lines and
treat them as an error or at least emit a warning with context instead of
silently skipping them. Specifically, where the variables content, ch, and chars
are used, add logic to capture the line number (or index) and either return a
Result::Err (e.g., DictionaryParseError::EmptyLine(line_num)) or call the
crate's logging facility to warn about an unexpected blank line (optionally
allowing a single trailing blank line), so accidental blanks don't silently
change the mapping.

In `@crates/mlx-core/src/models/pp_text_rec/model.rs`:
- Around line 200-233: avg_pool2d_k3x2 assumes a 4D tensor but never checks
shape.len(), so add a guard at the start of avg_pool2d_k3x2 to validate
shape.len() == 4 and return a descriptive Error::from_reason if not (e.g.,
"avg_pool2d_k3x2: expected 4D input but got N-D"), before accessing shape[0..3];
this prevents panics and gives a clear error when inputs of the wrong rank are
passed.

In `@crates/mlx-core/src/models/pp_text_rec/processing.rs`:
- Around line 31-34: The doc comment for the struct fields mean and std says [R,
G, B] but the code uses channel_map = [2, 1, 0], so the current normalization
applies mean[0] to B, mean[1] to G, mean[2] to R; fix by either updating the doc
comments to state BGR order or (preferred) change the normalization use-site to
index mean/std via channel_map (i.e., use mean[channel_map[c]] and
std[channel_map[c]] when normalizing each channel) so mean/std remain documented
as RGB; look for the normalization logic in this file that references mean/std
and channel_map to implement the indirection.
- Around line 51-55: compute_resized_width can divide by zero when height == 0;
add an early check in compute_resized_width (same fn signature, using parameters
width, height, img_w_limit and self.target_height) that if height == 0 returns
the clamped minimum width (e.g. return 1.min(img_w_limit)) and otherwise keep
the existing ratio/new_w calculation and final clamp
new_w.max(1).min(img_w_limit).

In `@examples/vlm-inference.ts`:
- Around line 35-36: The threshold parsing currently uses parseFloat on
args[thresholdIdx + 1] which can yield NaN if the value is missing or
non-numeric; update the logic around thresholdIdx and threshold to first verify
args[thresholdIdx + 1] exists, then parse it and check Number.isFinite or isNaN,
and if invalid fall back to the default 0.5; modify the code that sets threshold
(referencing thresholdIdx, threshold, args, parseFloat) to perform this guard
and fallback so a missing or bad value doesn't silently propagate NaN.

In `@packages/vlm/src/pipeline/structure-v3.ts`:
- Around line 385-394: The footnote cases ('footnote' and 'table_footnote') are
emitting `[^]: ${trimmed}` which is invalid; change them to emit a labeled
footnote like `[^${label}]: ${trimmed}` where label is derived from the node
(e.g., node.label or node.id) or, if none exists, generate a stable numeric
label using the existing footnote counter in this module/function (add one if
missing) so the returned string becomes `[^<label>]: ${trimmed}\n`; update both
the 'footnote' and 'table_footnote' branches to use this labeled form and ensure
any code that references footnote labels uses the same label source/generation.
- Around line 285-290: The hardcoded 10px vertical threshold in the sort
callback can misorder boxes at different resolutions; replace it with a dynamic
threshold computed from box sizes or image dimensions (e.g., derive yThreshold
from the average bbox height of the two boxes or a small fraction of the image
height) and use that instead of 10; update the sort in the code that builds
`sorted` (the sort callback operating on `textBoxes` and their `bbox` values) to
compute e.g. `const yThreshold = Math.max( ( (a.bbox[3]-a.bbox[1]) +
(b.bbox[3]-b.bbox[1]) )/4, imageHeight * 0.01 )` and then use `if
(Math.abs(yDiff) > yThreshold) return yDiff;` so line grouping adapts to
resolution.
- Line 34: The import statement currently pulls DocLayoutModel, TextDetModel,
TextRecModel, and LayoutElement directly from `@mlx-node/core` which violates the
guideline; update the import in structure-v3.ts to import these symbols from the
appropriate package entry point (prefer `@mlx-node/vlm` for VLM/training utilities
or `@mlx-node/lm` for inference utilities) using the same symbol names
(DocLayoutModel, TextDetModel, TextRecModel, LayoutElement); if those types are
not yet re-exported from `@mlx-node/vlm` or `@mlx-node/lm`, add re-exports in the
package index (export { DocLayoutModel, TextDetModel, TextRecModel,
LayoutElement } from '@mlx-node/core') and then change the import to the
re-exporting package.
🧹 Nitpick comments (31)
examples/vlm-inference.ts (1)

147-170: 'figure' and 'chart' in ocrLabels are dead code.

These labels are intercepted at lines 228–231 and routed to nonOcrParts before the ocrLabels.has(label) check at line 234 is reached. Similarly, the getPrompt cases for 'chart'/'figure' (lines 139–140) are unreachable.

Either remove them from ocrLabels/getPrompt, or remove the early-exit at lines 228–231 if you actually want to OCR figures/charts.

crates/mlx-core/src/models/pp_text_det/postprocessing.rs (1)

76-97: O(N × H × W) per-component scan — consider a single-pass approach.

The loop scans all map_h * map_w pixels for each label ID. With many components this becomes expensive. A single pass collecting per-label bounding rects and scores into a HashMap<usize, (min_x, min_y, max_x, max_y, score_sum, count)> would reduce this to O(H × W) total.

For typical OCR workloads (few dozen components, ~640² map) this is fine, so flagging as a future optimization rather than a blocker.

Sketch of single-pass approach
+    // Single pass: collect per-label stats
+    struct LabelStats { min_x: usize, min_y: usize, max_x: usize, max_y: usize, score_sum: f64, count: usize }
+    let mut stats: std::collections::HashMap<usize, LabelStats> = std::collections::HashMap::new();
+    for y in 0..map_h {
+        for x in 0..map_w {
+            let idx = y * map_w + x;
+            let label_id = labels[idx];
+            if label_id == 0 { continue; }
+            let s = stats.entry(label_id).or_insert(LabelStats {
+                min_x: x, min_y: y, max_x: x, max_y: y, score_sum: 0.0, count: 0,
+            });
+            s.min_x = s.min_x.min(x);
+            s.min_y = s.min_y.min(y);
+            s.max_x = s.max_x.max(x);
+            s.max_y = s.max_y.max(y);
+            s.score_sum += prob_map[idx] as f64;
+            s.count += 1;
+        }
+    }
+    // Then iterate stats to build boxes...
crates/mlx-core/src/models/pp_text_rec/svtr_neck.rs (2)

63-67: Confusing prenorm=False documentation.

The comment says "Block(prenorm=False) which applies LayerNorm BEFORE the sublayer (attention/FFN)" — the naming in PaddleOCR's codebase is misleading (the parameter controls something different from what its name suggests), and reproducing it here without clarification will confuse readers. Consider rephrasing to make the actual behavior clear, e.g.:

PaddleOCR's Block class uses prenorm=False (confusingly named); in practice, norm1/norm2 are still applied before the sublayers (pre-norm pattern).


50-56: Unknown activation silently defaults to SiLU.

Line 54 catches any unrecognized activation string and falls back to silu without warning. This could mask configuration bugs. Consider logging a warning or returning an error for unexpected values.

crates/mlx-core/src/models/paddleocr_vl/model.rs (4)

1060-1069: Duplicated LaTeX-stripping logic — consider extracting a helper.

The same strip_prefix("\\(\\text{") / strip_suffix("}\\)") pattern appears in both ocr() (lines 270-274) and ocr_batch(). If the wrapper format changes (e.g., new LaTeX patterns), only one site may get updated.

♻️ Proposed refactor
/// Strip common LaTeX wrappers from OCR output
fn strip_latex_wrappers(text: String) -> String {
    text.strip_prefix("\\(\\text{")
        .and_then(|s| s.strip_suffix("}\\)"))
        .map(|s| s.to_string())
        .unwrap_or(text)
}

Then use strip_latex_wrappers(r.text) in both ocr() and ocr_batch().


1155-1213: ImageProcessor is re-created per item with identical config — hoist it out of the loop.

processor_config and processor don't vary across batch items (they depend solely on self.config). Constructing them inside the per-item loop is wasteful for large batches.

♻️ Proposed fix
+        let processor_config = ImageProcessorConfig {
+            patch_size: self.config.vision_config.patch_size,
+            merge_size: self.config.vision_config.spatial_merge_size,
+            ..ImageProcessorConfig::default()
+        };
+        let processor = ImageProcessor::new(Some(processor_config));
+
         for item in &batch {
             // Process images
             let (pixel_values, grid_thw) = if let Some(paths) = &item.image_paths {
                 if paths.is_empty() {
                     (None, None)
                 } else {
-                    let processor_config = ImageProcessorConfig {
-                        patch_size: self.config.vision_config.patch_size,
-                        merge_size: self.config.vision_config.spatial_merge_size,
-                        ..ImageProcessorConfig::default()
-                    };
-                    let processor = ImageProcessor::new(Some(processor_config));
                     let processed = processor.process_files(paths.clone())?;

1480-1534: Read lock on LM for the entire decode loop blocks all other LM users (including other generate/chat calls) from acquiring write access.

lm.read() at line 1476 is held until the loop finishes (potentially hundreds of steps). Any concurrent call to generate(), chat(), or another batch() that needs a write lock will block. This is inherent to the RwLock-based design and not a bug, but worth documenting at the API level that VLModel is not concurrency-safe for simultaneous generation calls.


1155-1213: Significant code duplication: image processing + token counting logic is copy-pasted from chat().

The entire block (image processing via ImageProcessor, pixel value reshaping, grid_thw extraction, image token counting with spatial_merge_size) duplicates lines 127-179 from chat(). Consider extracting a shared helper like fn process_item_images(&self, paths: &[String]) -> Result<(Option<MxArray>, Option<MxArray>, Option<usize>)>.

crates/mlx-core/src/models/pp_text_det/config.rs (1)

155-174: Tests cover backbone and detection params but miss a few config fields.

pf_head_k, pf_head_mode, unclip_ratio, max_candidates, min_size, and activation are not asserted. Consider adding assertions for completeness, especially for pf_head_mode ("large") since it controls the LocalModule mid_channels.

crates/mlx-core/src/models/pp_doclayout_v3/processing.rs (2)

86-100: Consider pre-indexing into the raw pixel buffer instead of per-pixel get_pixel calls.

After to_rgb8(), the underlying buffer is contiguous. Using rgb_img.as_raw() and indexing directly would avoid per-pixel bounds-checking overhead, which adds up at 800×800. This matches the pattern used in pp_text_det/processing.rs.

♻️ Suggested optimization
-        let mut pixel_data: Vec<f32> = Vec::with_capacity(h * w * channels);
-
-        for y in 0..h {
-            for x in 0..w {
-                let pixel = rgb_img.get_pixel(x as u32, y as u32);
-                for c in 0..channels {
-                    let val = pixel[c] as f32 / 255.0;
-                    pixel_data.push(val);
-                }
-            }
-        }
+        let raw = rgb_img.as_raw();
+        let mut pixel_data: Vec<f32> = Vec::with_capacity(h * w * channels);
+        for &byte in raw.iter() {
+            pixel_data.push(byte as f32 / 255.0);
+        }

110-119: Test only validates construction; no integration test for process_file.

A test that processes a small synthetic image (e.g., via image::RgbImage::new(100, 50)) and validates the output tensor shape [1, 800, 800, 3] and value range [0, 1] would catch regressions in the resize/rescale pipeline.

crates/mlx-core/src/models/pp_text_rec/persistence.rs (2)

32-244: Significant code duplication: load_backbone is nearly identical to pp_text_det/persistence.rs.

Both pp_text_rec and pp_text_det implement ~210 lines of identical backbone-loading logic (stem loading, stage iteration, block/layer construction, aggregation). The only variation is the config type wrapping the same HGNetV2Config. Consider extracting a shared load_hgnetv2_backbone(params, backbone_config: &HGNetV2Config, eps: f64) -> Result<HGNetV2Backbone> into the pp_doclayout_v3::persistence module (which already hosts the shared helpers) to eliminate duplication.


308-319: Hardcoded LayerNorm epsilon values — intentional but worth a config field.

norm1/norm2 use 1e-5 and the final norm uses 1e-6. These are likely PaddleOCR defaults, but they're invisible to anyone tuning the model. Consider adding svtr_layer_norm_eps and svtr_final_norm_eps to TextRecConfig with these as defaults, matching the pattern used for batch_norm_eps.

crates/mlx-core/src/models/pp_text_det/persistence.rs (1)

448-469: Hardcoded IntraCL block count (4) is coupled to backbone level count.

The loop 1..=4 assumes exactly 4 backbone feature levels. If n_levels (derived from config.backbone.stage_out_channels.len()) were ever different, this would silently load the wrong number of blocks or fail on missing keys.

♻️ Suggested fix to derive count from config
-        let mut intracl_blocks = Vec::with_capacity(4);
-        for i in 1..=4 {
+        let mut intracl_blocks = Vec::with_capacity(n_levels);
+        for i in 1..=n_levels {
             intracl_blocks.push(load_intracl_block(params, &format!("neck.incl{}", i), eps)?);
         }
crates/mlx-core/src/models/pp_text_rec/processing.rs (1)

222-224: rgb_data.clone() on each batch item allocates a full copy of the pixel buffer.

RgbImage::from_raw requires ownership. Since process_batch takes &[(Vec<u8>, u32, u32)], each image's data is cloned. For large batches of large crops this could be a noticeable allocation spike. Consider changing the signature to take owned data (Vec<(Vec<u8>, u32, u32)>) or using image::imageops::resize directly on a view.

crates/mlx-core/src/models/pp_text_det/model.rs (1)

50-83: detect performs synchronous file I/O + inference on the JS thread.

Both process_file (disk read + decode + resize) and forward (full model inference) run synchronously. For large images or in server contexts, this blocks the Node.js event loop. This is likely acceptable for the initial implementation, but consider offering an async variant (e.g., #[napi(ts_return_type = "Promise<TextBox[]>")]) in the future.

crates/mlx-core/src/models/pp_doclayout_v3/config.rs (2)

596-630: Duplicate label names in default_id2label appear intentional but may confuse consumers.

Indices 8 & 9 both map to "footer", 12 & 13 to "header", 5 & 15 to "formula", and 22 & 23 to "text". If this matches the upstream PaddlePaddle config, it's fine — but a brief comment noting these intentional duplicates would help future maintainers.


145-158: output_channels silently drops unrecognized feature names.

If out_features contains a name that doesn't match "stage<N>", it's silently filtered out by filter_map. This is fine for normal operation but could mask a misconfiguration. Consider logging a warning or at least adding a doc comment noting this behavior.

crates/mlx-core/src/models/pp_doclayout_v3/persistence.rs (1)

205-446: Significant code duplication with pp_text_det/persistence.rs::load_backbone.

This load_backbone function shares ~90% of its structure with the one in pp_text_det/persistence.rs (Lines 30–243 in the snippet). The main differences are the weight key prefix ("backbone.model.embedder" vs "backbone") and minor channel handling. Consider extracting a shared backbone loader parameterized by prefix to reduce duplication.

#!/bin/bash
# Verify the degree of duplication between the two load_backbone functions
echo "=== pp_doclayout_v3 load_backbone ==="
rg -c "load_conv_bn_act" crates/mlx-core/src/models/pp_doclayout_v3/persistence.rs

echo ""
echo "=== pp_text_det load_backbone ==="
rg -c "load_conv_bn_act" crates/mlx-core/src/models/pp_text_det/persistence.rs

echo ""
echo "=== Shared helper usage ==="
rg -n "pub\(crate\) fn" crates/mlx-core/src/models/pp_doclayout_v3/persistence.rs | head -20
crates/mlx-core/src/models/pp_text_det/processing.rs (1)

146-162: Duplicated normalization loop between process_file and process_crop.

The pixel normalization logic (BGR channel reorder + per-channel normalize) is identical in both methods. Extract a shared helper like normalize_rgb_to_bgr(&self, img: &RgbImage, h: usize, w: usize) -> Vec<f32> to reduce duplication. The same pattern exists in pp_text_rec/processing.rs with its own normalization, so a trait or shared utility could serve all processors.

Also applies to: 199-214

crates/mlx-core/src/models/pp_text_det/lkpan.rs (1)

260-288: upsample_nearest_to_match uses iterative 2× doubling — correct but potentially inefficient for large scale factors.

For a 16× upsample (e.g., stride-32 → stride-2), this performs 4 reshape+broadcast+reshape iterations. Each iteration materializes a full intermediate tensor. A single reshape+broadcast to the target size would be more efficient, but the current approach is simpler and correct.

packages/vlm/src/pipeline/structure-v3.ts (2)

165-177: Mixing sync I/O (readFileSync, mkdtempSync) with async method.

readFileSync at Line 176 blocks the event loop while reading potentially large image files. Consider using readFile from node:fs/promises since the method is already async. Similarly, mkdtempSync could use mkdtemp from node:fs/promises.


304-320: @napi-rs/image is dynamically imported on every call to ocrRegion and cropElement.

The await import('@napi-rs/image') is evaluated each time these methods are called. While Node.js caches module imports, the await still adds overhead in a hot path (called per layout element). Consider importing once and storing the reference, or importing at the top of the file.

Suggested approach
+// At class level or module level:
+let _imageModule: typeof import('@napi-rs/image') | undefined;
+async function getImageModule() {
+  if (!_imageModule) {
+    _imageModule = await import('@napi-rs/image');
+  }
+  return _imageModule;
+}
crates/mlx-core/src/models/pp_text_det/db_head.rs (1)

57-97: Head::forward duplicates the logic of forward_with_features — consider delegating.

forward (Lines 57–75) repeats the same conv→BN→ReLU→deconv→BN→ReLU→deconv→sigmoid chain as forward_with_features (Lines 81–97). Since MLX uses lazy evaluation, the unused intermediate f has negligible cost.

Suggested simplification
     pub fn forward(&self, input: &MxArray) -> Result<MxArray> {
-        // Conv + BN + ReLU
-        let x = self.conv1.forward(input)?;
-        let x = self.bn1.forward(&x)?;
-        let x = Activations::relu(&x)?;
-
-        // Deconv (2x upsample) + BN + ReLU
-        let x = self.deconv1.forward(&x)?;
-        let x = self.bn2.forward(&x)?;
-        let x = Activations::relu(&x)?;
-
-        // Deconv (2x upsample) + Sigmoid
-        let x = self.deconv2.forward(&x)?;
-        Activations::sigmoid(&x)
+        let (result, _) = self.forward_with_features(input)?;
+        Ok(result)
     }
crates/mlx-core/src/models/pp_doclayout_v3/decoder.rs (2)

1086-1093: Misleading variable name mask_dim — it actually holds num_queries.

mq_shape is the shape of mask_query_embed which is [B, num_queries, num_prototypes], so mq_shape[1] is num_queries. The name mask_dim suggests it's a mask-related dimension. Consider renaming to num_queries_out or just reusing num_queries from the earlier computation.


503-669: Bilinear interpolation with per-corner validity masking is correct but extremely verbose.

The 4-corner gather+mask+weight pattern repeats nearly identical code 4 times for (tl, tr, bl, br). This is correct and matches PyTorch's grid_sample with padding_mode="zeros", but the ~170 lines of near-duplicate code are hard to audit and maintain.

Consider extracting a helper like:

fn gather_and_weight(
    value_bh: &MxArray, idx: &MxArray, weight: &MxArray, mask: &MxArray,
    batch_size: i64, nh: i64, num_queries: i64, np: i64, hidden_dim: i64,
) -> Result<MxArray> { ... }
crates/mlx-core/src/models/pp_text_rec/model.rs (1)

60-117: Extract shared decode logic to reduce duplication across recognize, recognize_batch, and recognize_crop.

All three methods (recognize, recognize_batch, recognize_crop) duplicate the same post-forward decode-and-build-RecResult logic (CTC greedy decode → empty check → dictionary decode → construct RecResult). Consider extracting a private helper like decode_logits(&self, logits: &MxArray) -> Result<RecResult>.

♻️ Proposed helper extraction

Add a private method to TextRecModel:

fn decode_result(&self, logits: &MxArray) -> Result<RecResult> {
    let decoded = ctc_greedy_decode(logits)?;
    if decoded.is_empty() {
        return Ok(RecResult {
            text: String::new(),
            score: 0.0,
        });
    }
    let (indices, scores) = &decoded[0];
    let (text, score) = self.dictionary.decode_with_score(indices, scores);
    Ok(RecResult {
        text,
        score: score as f64,
    })
}

Then each public method becomes:

 pub fn recognize(&self, image_path: String) -> Result<RecResult> {
     let pixel_values = self.image_processor.process_file(&image_path)?;
     let logits = self.forward(&pixel_values)?;
-    let decoded = ctc_greedy_decode(&logits)?;
-
-    if decoded.is_empty() {
-        return Ok(RecResult {
-            text: String::new(),
-            score: 0.0,
-        });
-    }
-
-    let (indices, scores) = &decoded[0];
-    let (text, score) = self.dictionary.decode_with_score(indices, scores);
-
-    Ok(RecResult {
-        text,
-        score: score as f64,
-    })
+    self.decode_result(&logits)
 }
crates/mlx-core/src/models/pp_doclayout_v3/model.rs (2)

278-310: Redundant NCHW transpose of mask_feat when mask_enhanced is true.

When mask_enhanced is true, mask_feat is transposed to NCHW on line 284 within the if-block, but then the same mask_feat (original NHWC) is transposed again on line 310 for the decoder. Consider hoisting the transpose to line 310 and reusing it in both places.

♻️ Suggested refactor
+        // 12. Convert mask_feat to NCHW for decoder and mask-enhanced block
+        let mask_feat_nchw = mask_feat.transpose(Some(&[0, 3, 1, 2]))?;
+
         // 11. Mask-enhanced reference points (if enabled)
         let reference_points_unact = if self.config.mask_enhanced {
             let out_query = self.decoder_norm.forward(&target)?;
             let mask_query_embed = self.mask_query_head.forward(&out_query)?;
 
-            let mask_feat_nchw = mask_feat.transpose(Some(&[0, 3, 1, 2]))?;
             let mf_shape = mask_feat_nchw.shape()?;
             // ... rest unchanged
         } else {
             reference_points_unact
         };
 
-        // 12. Convert mask_feat to NCHW for decoder
-        let mask_feat_nchw = mask_feat.transpose(Some(&[0, 3, 1, 2]))?;
-
         // 13. Run decoder

162-363: The detect method is ~200 lines implementing a full inference pipeline.

This is a dense end-to-end pipeline with 15 sequential steps. While each step is well-commented, the overall length hurts readability. Consider extracting logical sub-pipelines (e.g., encoder output + top-K selection, mask-enhanced refinement) into private helper methods in a follow-up.

crates/mlx-core/src/models/pp_doclayout_v3/backbone.rs (1)

578-606: General MaxPool2d path returns an error for stride > 1 — consider a debug_assert! or documented invariant instead.

The general case (kernel > 2) hard-errors when stride > 1 (line 592), which is fine given the only usage is MaxPool2d::new(2, 1, true) in HGNetV2Embeddings. However, the error is discovered at runtime during forward pass rather than at construction time. If this is an intentional restriction, validating in MaxPool2d::new would surface misuse earlier.

♻️ Optional: validate unsupported configs at construction time
 pub fn new(kernel_size: i32, stride: i32, ceil_mode: bool) -> Self {
+    // NOTE: Only kernel_size=2, stride=1 is optimized. Other combinations
+    // may produce errors at forward time.
+    debug_assert!(
+        kernel_size == 2 && stride == 1,
+        "MaxPool2d currently only supports kernel_size=2, stride=1"
+    );
     Self {
         kernel_size,
         stride,
         ceil_mode,
     }
 }
crates/mlx-core/src/models/pp_doclayout_v3/encoder.rs (1)

811-831: The fallback upsampling loop assumes power-of-2 scale relationships between feature levels.

The loop { ... upsample_bilinear_2x ... } on lines 815–821 repeatedly doubles dimensions until they meet or exceed the target, then slices. This works correctly for power-of-2 relationships (which is standard for FPN strides), but the post-loop slice on lines 824–828 may introduce subtle alignment artifacts if the overshoot is significant. This is fine for the current architecture but worth noting if future feature levels break the power-of-2 assumption.

A brief comment documenting this assumption would help future maintainers:

             let processed = if proc_h != out_h || proc_w != out_w {
-                // Use bilinear upsampling to match output size
-                // Since we're dealing with power-of-2 relationships, repeated 2x upsampling works
+                // Repeated 2x bilinear upsampling to match output resolution.
+                // Assumes power-of-2 stride ratios between feature levels (standard for FPN).
+                // Non-power-of-2 ratios will overshoot and be sliced, which may cause
+                // minor alignment artifacts.
                 let mut p = processed;

Comment thread examples/vlm-inference.ts 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 1 potential issue.

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

…5 text detection and recognition

Implements the full PP-StructureV3 pipeline: PP-DocLayoutV3 (layout detection) +
PP-OCRv5 TextDet (text line detection with LKPAN neck + DB head) +
PP-OCRv5 TextRec (text recognition with HGNetV2 backbone + SVTR neck + CTC head).

Achieves ~4-5x faster text extraction than VLM-based OCR with ~6x smaller model
footprint (292MB vs 1.7GB). Includes PaddlePaddle .pdiparams conversion scripts,
ConvTranspose2d FFI support, and the StructureV3Pipeline TypeScript API.

Co-Authored-By: Claude Opus 4.6 <[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: 6

Caution

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

⚠️ Outside diff range comments (2)
crates/mlx-core/src/vision/conv2d.rs (2)

186-218: ⚠️ Potential issue | 🟠 Major

Fast path silently ignores dilation and groups — correctness risk.

The fast path condition on line 186 only checks k_h == stride && k_w == stride && padding == 0, but does not verify that dilation == (1, 1) and groups == 1. If a caller passes non-unit dilation or grouped convolution with parameters that happen to match the fast-path condition (stride == kernel_size, no padding), the fast path will silently produce incorrect results by ignoring those parameters.

Now that the general FFI path handles all parameters correctly, the fast-path guard should also assert that dilation and groups are default values.

Proposed fix
-    if k_h == stride.0 as i64 && k_w == stride.1 as i64 && padding.0 == 0 && padding.1 == 0 {
+    if k_h == stride.0 as i64
+        && k_w == stride.1 as i64
+        && padding.0 == 0
+        && padding.1 == 0
+        && _dilation.0 == 1
+        && _dilation.1 == 1
+        && _groups == 1
+    {

134-144: 🛠️ Refactor suggestion | 🟠 Major

Stale underscore prefixes and outdated comments.

  1. Parameters _dilation (line 140) and _groups (line 141) are now used in the general FFI path (lines 232–234). The underscore prefix conventionally signals "intentionally unused" and is misleading here — rename to dilation and groups.

  2. The TODO on line 144 ("Add proper conv2d FFI when available") is now resolved by the new general path — remove it.

  3. The doc comment on lines 19–20 ("Currently only supports the patch embedding case…") is outdated now that the general path exists.

Proposed fix for parameter names
 pub fn conv2d_forward(
     input: &MxArray,
     weight: &MxArray,
     bias: Option<&MxArray>,
     stride: (u32, u32),
     padding: (u32, u32),
-    _dilation: (u32, u32),
-    _groups: u32,
+    dilation: (u32, u32),
+    groups: u32,
 ) -> Result<MxArray> {
-    // For now, implement a basic version using matrix operations
-    // TODO: Add proper conv2d FFI when available
🤖 Fix all issues with AI agents
In `@crates/mlx-core/src/models/pp_doclayout_v3/decoder.rs`:
- Around line 59-866: Add manual backward implementations for SelfAttention,
MultiscaleDeformableAttention, and DecoderLayer by adding corresponding gradient
functions (e.g., self_attention_backward,
multiscale_deformable_attention_backward, decoder_layer_backward) in the
gradients/ module and registering them with the operator/compute-block registry;
each backward must mirror the forward tensor shapes/reshapes/transposes and
return gradients for inputs and learnable weights. For SelfAttention compute
grads for query/key/value projections and out_proj plus hidden_states and
position_embeddings (handle scaling, the Q multiply-by-scaling, attention_mask
addition and softmax backward, and the reshape/transpose sequence). For
MultiscaleDeformableAttention implement gradients for value_proj,
sampling_offsets, attention_weights, and output_proj including: (a) backprop
through attention_weights softmax and weighted sum, (b) backprop through
bilinear sampling (compute grads w.r.t. sampling locations → offsets →
sampling_offsets params), (c) proper handling of per-corner masks and clamping
used for zero padding, and (d) gathering/reshape transposes matching the
forward. For DecoderLayer implement a backward that chains self-attn backward,
deformable cross-attn backward and FFN backward, producing grads for
hidden_states, position_embeddings, encoder_hidden_states, reference_points and
all Linear/LayerNorm params; ensure residual adds and LayerNorm backward are
applied in correct order. Ensure gradient functions preserve dtype/shape
contracts and add unit tests comparing numeric gradients to these analytical
grads.

In `@crates/mlx-sys/src/mlx.cpp`:
- Around line 4888-4987: Wrap the entire body of the extern "C" entry function
mlx_paddleocr_vl_forward_step_batched in a try/catch block so no C++ exceptions
escape the FFI; catch (const std::exception& e) and call the existing
error-reporting helper (e.g., set_last_error or the same mechanism used in
mlx_array_eval) with e.what() and return early, and also catch (...) to set a
generic "unknown C++ exception" error and return; apply the same pattern to the
other FFI entry points mentioned (mlx_paddleocr_vl_forward_step, mlx_conv2d,
mlx_conv_transpose2d) so all C++ exceptions are converted to FFI-safe error
reporting instead of propagating into Rust.

In `@examples/vlm-inference.ts`:
- Around line 203-205: The footnote branch returning `[^]: ${trimmed}\n` uses an
invalid footnote definition (missing identifier); update the handler for the
'footnote' and 'table_footnote' cases to emit a valid identifier (e.g., use the
element's label if available, or generate/consume a sequential counter) so
output becomes `[^<id>]: <trimmed>` and ensure the corresponding footnote
reference in the main text uses the same `[^<id>]` identifier; locate this logic
in the switch/case that handles 'footnote' and 'table_footnote' and wire it to
the chosen ID source (label or counter) consistently.
- Around line 26-27: The import of LayoutElement should come from the package
entry point that re-exports it: move LayoutElement out of the first import and
into the second import from '@mlx-node/vlm' (update the import that currently
brings in DocLayoutModel, VLModel, parsePaddleResponse, OutputFormat to also
import LayoutElement); keep ChatRole imported from '@mlx-node/core' unchanged
because it is not re-exported from the allowed entry points yet (do not attempt
to re-export or modify exports here). Ensure you update only the import
declarations and leave all references to LayoutElement, ChatRole,
DocLayoutModel, VLModel, parsePaddleResponse, and OutputFormat intact.

In `@packages/core/index.d.cts`:
- Around line 2315-2327: Update the bbox type for layout coordinate arrays to
use a TypedArray: change the LayoutElement interface's bbox from Array<number>
to Float32Array and do the same for the TextBox interface (replace bbox:
Array<number> with bbox: Float32Array) so public API uses TypedArray for numeric
detection output; locate and update the two interface declarations
(LayoutElement and TextBox) in the declaration file accordingly.

In `@packages/vlm/src/pipeline/structure-v3.ts`:
- Around line 100-126: The constants TEXT_LABELS and SKIP_LABELS violate the
camelCase style; rename them to textLabels and skipLabels (update the const
declarations for TEXT_LABELS and SKIP_LABELS to textLabels and skipLabels
respectively) and then update every usage/reference in this module to the new
identifiers (e.g., where TEXT_LABELS and SKIP_LABELS are referenced later in
this file). Ensure imports/exports and any tests or other files that reference
these names are updated to the new camelCase identifiers to avoid breaking
references.
🧹 Nitpick comments (21)
crates/mlx-core/src/vision/conv2d.rs (2)

428-478: Test labeled "General FFI path" actually exercises the fast path.

The comment on lines 431–438 correctly notes that 1×1 / stride 1 / pad 0 matches the fast-path condition, yet this test is under the "General FFI path tests" section. This is misleading to future readers. Consider either moving it out of this section or tweaking parameters (e.g., padding: (1, 1)) to genuinely exercise the general path.

Also, there are no tests exercising dilation != (1, 1) or groups != 1 via the general FFI path — these would be valuable given that the fast path currently doesn't guard against those parameters (per the issue above).


134-142: No backward pass for the general conv2d path.

The coding guidelines state that new layers should have corresponding backward passes in the gradients/ module. The general conv2d FFI path is new; if gradient computation through this layer is needed for training/fine-tuning, a backward pass should be added. If this is strictly inference-only, consider documenting that explicitly.

Based on learnings: "Implement manual backward passes for new activation functions and layers by adding corresponding functions to the gradients/ module."

crates/mlx-sys/src/mlx.cpp (2)

4802-4884: Significant code duplication with paddleocr_vl_block_forward_cached (lines 4609–4694).

paddleocr_vl_block_forward_batched is ~80 lines that are nearly identical to paddleocr_vl_block_forward_cached. The only material difference is the attention mask creation (lines 4867–4868 vs 4675–4677): the batched version uses create_batched_causal_mask while the non-batched version uses the "causal" / "" string mode.

Consider parameterizing the mask-creation strategy (e.g., pass an optional left_padding and choose the mask path internally) to collapse both into a single function. The same applies to mlx_paddleocr_vl_forward_step_batched vs mlx_paddleocr_vl_forward_step (~100 duplicated lines).

This isn't blocking, but maintaining two near-identical copies of performance-critical attention + KV-cache logic is a future correctness risk — any bug fix applied to one copy can easily be missed in the other.


4925-4948: Local LayerWeightsT struct redeclared — identical to non-batched version at line 4735.

This struct is defined identically in both mlx_paddleocr_vl_forward_step and mlx_paddleocr_vl_forward_step_batched. Consider hoisting it to the anonymous namespace scope so both functions can share it.

crates/mlx-core/src/models/pp_text_rec/processing.rs (1)

192-210: Unused default_ratio computation is dead code.

default_ratio is computed on line 197 but immediately suppressed with let _ = default_ratio; on line 210. The comment explains the rationale, but the computation itself is wasteful. Consider removing it entirely and keeping only the explanatory comment.

♻️ Suggested cleanup
-        // Step 1: Compute the maximum w/h ratio across all images in the batch.
-        // Following PaddleOCR: max_wh_ratio starts at imgW/imgH (default_width / target_height),
-        // then is updated with each image's actual ratio.
-        let default_ratio = self.max_width as f64 / self.target_height as f64;
         let mut max_wh_ratio: f64 = 0.0;
         for (_rgb_data, width, height) in images.iter() {
             let ratio = *width as f64 / *height as f64;
             if ratio > max_wh_ratio {
                 max_wh_ratio = ratio;
             }
         }
-        // PaddleOCR clamps the minimum to the default ratio (imgW/imgH).
-        // But here we just need the max across images; the default ratio acts as a floor
-        // only if no image is wider. We don't enforce the floor because we want narrow
-        // images to produce narrow tensors when the batch is entirely narrow.
-        // However, we do need to cap at max_width.
-        let _ = default_ratio; // Not used as a floor; max_width cap is sufficient.
+        // Note: PaddleOCR uses a default ratio floor (imgW/imgH), but we rely on
+        // the max_width cap instead, allowing narrow batches to produce narrow tensors.
crates/mlx-core/src/models/pp_text_det/postprocessing.rs (2)

76-97: Per-component bounding rect scan is O(num_labels × map_h × map_w).

Each label re-scans the entire map. For a probability map with many small components this becomes quadratic. A single-pass approach collecting (min_x, min_y, max_x, max_y, score_sum, count) per label in one traversal would reduce this to O(map_h × map_w + num_labels).

This is unlikely to be a bottleneck for typical document images (few hundred components) but could matter for noisy inputs.

♻️ Single-pass bounding rect collection
-    for label_id in 1..=num_labels {
-        // Find bounding rect
-        let mut min_x = map_w;
-        let mut min_y = map_h;
-        let mut max_x = 0usize;
-        let mut max_y = 0usize;
-        let mut score_sum = 0.0f64;
-        let mut count = 0usize;
-
-        for y in 0..map_h {
-            for x in 0..map_w {
-                let idx = y * map_w + x;
-                if labels[idx] == label_id {
-                    min_x = min_x.min(x);
-                    min_y = min_y.min(y);
-                    max_x = max_x.max(x);
-                    max_y = max_y.max(y);
-                    score_sum += prob_map[idx] as f64;
-                    count += 1;
-                }
-            }
-        }
+    // Single-pass: collect per-label stats
+    struct LabelStats { min_x: usize, min_y: usize, max_x: usize, max_y: usize, score_sum: f64, count: usize }
+    let mut stats: Vec<Option<LabelStats>> = vec![None; num_labels + 1];
+
+    for y in 0..map_h {
+        for x in 0..map_w {
+            let idx = y * map_w + x;
+            let label_id = labels[idx];
+            if label_id == 0 { continue; }
+            let s = stats[label_id].get_or_insert(LabelStats {
+                min_x: x, min_y: y, max_x: x, max_y: y, score_sum: 0.0, count: 0,
+            });
+            s.min_x = s.min_x.min(x);
+            s.min_y = s.min_y.min(y);
+            s.max_x = s.max_x.max(x);
+            s.max_y = s.max_y.max(y);
+            s.score_sum += prob_map[idx] as f64;
+            s.count += 1;
+        }
+    }
+
+    for label_id in 1..=num_labels {
+        let Some(ref st) = stats[label_id] else { continue; };
+        let (min_x, min_y, max_x, max_y, score_sum, count) =
+            (st.min_x, st.min_y, st.max_x, st.max_y, st.score_sum, st.count);

192-207: Union-find find uses recursion — safe here due to union-by-rank.

The recursive path compression in find is bounded to O(log n) depth thanks to union-by-rank, so stack overflow is not a practical concern. That said, an iterative two-pass find is trivially simple and avoids any doubt about stack safety on very large images.

♻️ Iterative find (optional)
     fn find(parent: &mut [usize], x: usize) -> usize {
-        if parent[x] != x {
-            parent[x] = find(parent, parent[x]);
-        }
-        parent[x]
+        let mut root = x;
+        while parent[root] != root { root = parent[root]; }
+        let mut cur = x;
+        while cur != root { let next = parent[cur]; parent[cur] = root; cur = next; }
+        root
     }
crates/mlx-core/src/models/pp_text_det/processing.rs (1)

148-162: Normalization loop is duplicated between process_file and process_crop.

Both methods contain the same BGR channel-mapping + normalize loop. Consider extracting a shared helper like normalize_to_tensor(&RgbImage, round_w, round_h) -> Result<MxArray> to reduce duplication.

Also applies to: 200-214

crates/mlx-core/src/models/pp_text_det/db_head.rs (1)

191-202: upsample_nearest_2x is duplicated from pp_doclayout_v3/encoder.rs.

This is an exact copy of the function at crates/mlx-core/src/models/pp_doclayout_v3/encoder.rs:575-591. Consider extracting it into a shared utility (e.g., crate::nn::upsample or a shared ops module) to avoid maintaining two copies.

Additionally, the function assumes 4D input but doesn't validate shape.len() == 4 — a rank mismatch will panic on shape[3].

crates/mlx-core/src/models/pp_text_rec/model.rs (2)

89-117: recognize_batch is sequential, not batched — the comment honestly explains why.

Since different text line crops produce different-sized tensors after preprocessing, true batching would require padding. The sequential approach is correct for now. If this becomes a throughput bottleneck, consider grouping by similar aspect ratio and padding within groups.


150-187: Forward pass implements the PaddleOCR pipeline correctly with a reasonable H > 1 fallback.

The backbone → pool → neck → Im2Seq → head flow is clean. The fallback at line 182 (spatial.mean) handles unexpected H > 1 gracefully, though it silently diverges from PaddleOCR's assert H == 1. Consider logging a warning in that branch.

♻️ Add warning for unexpected H > 1
         let sequence = if h == 1 {
             spatial.reshape(&[batch, w, dims])?
         } else {
             // Fallback: pool height dimension if somehow H > 1
+            tracing::warn!("Im2Seq: expected H=1 after neck, got H={}. Falling back to mean pooling.", h);
             spatial.mean(Some(&[1]), Some(false))?
         };
crates/mlx-core/src/models/pp_text_rec/persistence.rs (2)

32-244: load_backbone is duplicated across three persistence modules.

This function is nearly identical to load_backbone in pp_text_det/persistence.rs (lines 31-244) and pp_doclayout_v3/persistence.rs (lines 205-446). The only material differences are:

  1. The stem_prefix ("backbone" vs "backbone.model.embedder").
  2. DocLayoutV3 tracks block_in/out_channels for residual logic while text_rec/text_det use the simpler block_idx != 0 check.

Consider extracting a shared load_hgnetv2_backbone helper parameterized by the prefix and residual strategy.


308-319: Hardcoded LayerNorm epsilon values — prefer config-driven values.

Lines 308 and 311 use 1e-5 and line 319 uses 1e-6 as hardcoded epsilon values for different LayerNorm instances. While these match the PaddleOCR reference, they're fragile if the upstream model ever changes. Consider adding these as fields on TextRecConfig (similar to batch_norm_eps) or defining named constants.

crates/mlx-core/src/models/pp_doclayout_v3/persistence.rs (2)

337-341: Dead variable layer_in — computed but immediately discarded.

layer_in is calculated on lines 337-341 but then discarded with let _ = layer_in; on line 379 in the standard (non-light) block path. If the channel is truly inherent in the loaded weights, consider removing this computation in the non-light branch to avoid confusion.

Also applies to: 379-379


714-717: Implicit assumption: fpn_stride >= base_stride.

(fpn_stride as f64 / base_stride as f64).log2() as usize will produce 0 when fpn_stride == base_stride (correct), but if a misconfigured feat_strides ever puts a smaller stride after sorting, log2() returns a negative value that wraps to a very large usize on cast. The current code is safe because sorted_strides is ascending, but a debug assertion would make the invariant explicit.

examples/vlm-inference.ts (1)

249-253: No error handling for batch OCR failures.

If vlm.batch(batchItems) throws or returns fewer results than expected, the assembly loop (lines 261-273) will silently produce incorrect output or crash. Consider wrapping in try/catch or validating batchResults.length === ocrItems.length.

crates/mlx-core/src/models/pp_text_rec/svtr_neck.rs (2)

50-55: Catch-all activation defaults to silu silently.

If an unrecognized activation string is passed (e.g., a typo like "swis"), the match falls through to silu without any warning or error. Consider logging a warning or returning an error for unknown activations to catch configuration mistakes early.

Proposed fix
         match self.activation.as_str() {
             "swish" | "silu" => Activations::silu(&x),
             "relu" => Activations::relu(&x),
             "none" => Ok(x),
-            _ => Activations::silu(&x),
+            other => Err(Error::from_reason(format!(
+                "SVTRConvBN: unsupported activation: {other}"
+            ))),
         }

63-67: Docstring is confusingly worded regarding prenorm=False.

The comment states "PaddleOCR's EncoderWithSVTR uses Block(prenorm=False) which applies LayerNorm BEFORE the sublayer". In many frameworks, prenorm=False would mean post-norm, making this comment misleading. Consider clarifying that PaddleOCR's naming convention is inverted relative to the standard meaning, or just describe the actual behavior without referencing the parameter name.

crates/mlx-core/src/models/pp_doclayout_v3/encoder.rs (3)

811-831: Unbounded upsampling loop assumes power-of-2 size ratios.

This loop repeatedly doubles spatial dims until they meet or exceed the target. If the ratio between proc_h/proc_w and out_h/out_w isn't a power of 2, the loop overshoots and relies on slicing (lines 823-828), which works but wastes compute. More importantly, if proc_h or proc_w is 0, this loops forever.

Consider adding a safety bound (e.g., max 8 iterations) to prevent potential infinite loops in edge cases:

Suggested guard
                 let mut p = processed;
-                loop {
+                for _ in 0..8 {
                     let ps = p.shape()?;
                     if ps[1] >= out_h && ps[2] >= out_w {
                         break;
                     }
                     p = upsample_bilinear_2x(&p)?;
                 }

1042-1068: FPN top-down path: in-place update of fpn_feature_maps[idx] is intentional but subtle.

Line 1054 replaces fpn_feature_maps[idx] with the lateral-conv output, then uses top_fpn (cloned before the update) for upsampling. This works correctly because top_fpn was bound before the in-place update. However, the original feature at fpn_feature_maps[idx] is silently overwritten — if any downstream code expected the un-lateral-conv'd feature, it would get the wrong value.

A brief inline comment clarifying this intent would help future readers.


959-990: HybridEncoder::new stores config fields but encoder_layers is only used as a guard — consider simplifying.

encoder_layers (line 933) is only checked as > 0 on line 1009 to skip the AIFI block. If encoders is empty, the loop on line 1010 would simply not execute regardless. You could remove the encoder_layers field and just check !self.encoders.is_empty() instead, reducing config coupling.

Comment thread crates/mlx-sys/src/mlx.cpp Resolved
Comment thread examples/vlm-inference.ts Resolved
Comment thread examples/vlm-inference.ts Resolved
Comment thread packages/core/index.d.cts 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: 8

🤖 Fix all issues with AI agents
In `@crates/mlx-core/src/models/pp_doclayout_v3/encoder.rs`:
- Around line 30-1104: The new encoder components lack manual backward
implementations causing training to fail; add corresponding backward functions
in the gradients/ module (crates/mlx-core/src/gradients/nn_gradients.rs)
implementing proper gradient flow for the composed layers. Implement
conv_norm_layer_backward that chains gradients through ConvNormLayer (conv ->
norm -> optional activation) and ConvLayer similarly if needed; implement
multihead_attention_backward that handles position_embeddings addition,
query/key/value projections, head reshape/transpose logic, softmax backprop and
out_proj; implement encoder_layer_backward that accounts for residuals,
self_attn (using multihead_attention_backward), LayerNorms, FFN
(fc1->activation->fc2) and normalize_before flag; implement
csp_rep_layer_backward to backprop through conv1/conv2 branches, sequential
RepVggBlock blocks (use rep_vgg block backward), merge/add and optional conv3;
and implement hybrid_encoder_backward that sequences AIFI
(build_2d_sincos_position_embedding usage), FPN top-down (lateral_convs,
upsample_nearest_2x, fpn_blocks), PAN bottom-up (downsample_convs, pan_blocks),
mask_feature_head (ScaleHead layers including upsample_bilinear_2x) and
encoder_mask_lateral/output, ensuring gradients respect reshapes, concatenations
(MxArray::concatenate), broadcasts and slicing. Use the existing forward
function names and types (ConvNormLayer::forward, ConvLayer::forward,
MultiheadAttention::forward, EncoderLayer::forward, CSPRepLayer::forward,
HybridEncoder::forward, ScaleHead::forward, RepVggBlock::forward) as anchors to
locate logic and mirror their operation order when computing reverse-mode
gradients.

In `@crates/mlx-core/src/models/pp_doclayout_v3/heads.rs`:
- Around line 147-152: The code in forward currently indexes shape[0] and
shape[1] without validating the input rank, which can panic for 1D/2D inputs;
add a guard right after obtaining shape (the Vec<i64>) that checks shape.len()
>= 2 (or >=3 if the function semantics require 3D) and return an Err with a
clear message when the check fails; update uses of batch_size and seq_len
(derived from shape[0] and shape[1]) to occur only after this validation so
forward, inputs, shape, batch_size and seq_len are safe to access.
- Around line 134-137: from_weights currently accepts any i32 for head_size and
can allow non-positive values that lead to NaN in forward(); update from_weights
(the function named from_weights) to enforce the same head_size > 0 validation
as new() — e.g. add an assert or conditional that returns/panics with a clear
message if head_size <= 0 — so callers cannot create a struct with an invalid
head_size that later breaks the sqrt/reshape in forward().

In `@crates/mlx-core/src/models/pp_text_det/lkpan.rs`:
- Around line 271-285: The upsampling loop that clones src into x and repeatedly
doubles spatial dims (variables x, src, shape(), h, w, target_h, target_w) can
infinite-loop when h==0 or w==0; add a defensive guard before the loop that
checks if shape()[1]==0 || shape()[2]==0 and return an Err (or early-return)
with a clear message about zero spatial dimensions so malformed inputs do not
hang the process; keep the rest of the doubling logic
(reshape/broadcast_to/reshape) unchanged.

In `@crates/mlx-core/src/models/pp_text_rec/processing.rs`:
- Around line 202-206: The loop that computes max_wh_ratio iterates over
images.iter() and divides *width by *height without guarding against height ==
0, which can produce f64::INFINITY and blow out batch_width; update the loop
(the block that computes ratio and updates max_wh_ratio) to detect zero height
(e.g., if *height == 0) and skip that image or treat the ratio as 0 (or another
bounded fallback) before computing ratio and updating max_wh_ratio so you never
assign Infinity to max_wh_ratio; mirror the guard behavior used in
compute_resized_width to keep behavior consistent.

In `@examples/vlm-inference.ts`:
- Around line 203-205: The footnote handlers in the switch for 'footnote' and
'table_footnote' return a constant id `[^note]`, which will collide for multiple
footnotes; update the logic in the switch cases (the 'footnote'/'table_footnote'
branch) to generate a unique id for each footnote (e.g., append el.order or an
incrementing counter/UUID) and return `[^note-<unique>]` (and ensure references
elsewhere use the same generated id).
- Around line 218-274: Sort the detected elements by reading order before
assigning indices and cropping so the assembled markdown respects el.order;
specifically, before the loop that uses idx/for (const el of elements) create a
sorted array (sorted by el.order) and iterate that instead, updating
nonOcrParts, ocrItems, and idx from the sorted collection so cropElement,
getPrompt and the subsequent vlm.batch call produce results in reading order,
and ensure the final assembly loop (using ocrResultIdx, batchResults,
parsePaddleResponse, and formatElement) consumes items in the same sorted
sequence.

In `@packages/vlm/src/pipeline/structure-v3.ts`:
- Around line 385-387: The footnote cases in structure-v3.ts currently return a
constant id (`[^note]`) which will collide for multiple footnotes; update the
return in the 'footnote' and 'table_footnote' branches to emit a stable unique
id (for example `[^note-${order}]` or `[^note-${footnoteCounter++}]`) using the
existing `order` value or an incrementing counter variable, and ensure the same
id is used where the footnote is referenced so IDs remain consistent.
🧹 Nitpick comments (8)
crates/mlx-core/src/models/pp_text_det/lkpan.rs (1)

266-294: Nearest-neighbor upsample via iterative 2× doubling may over-allocate for non-power-of-2 scale factors.

For example, upsampling from height 5 to height 9 will first produce height 10 (then slice back to 9), but from 5→33 it goes 5→10→20→40 before slicing to 33 — allocating ~21% more than needed. This is likely acceptable for the fixed 4-level FPN ratios (typically powers of 2), but worth a brief doc comment noting the assumption.

crates/mlx-core/src/models/pp_text_det/processing.rs (2)

108-115: The exists() check is a TOCTOU race; open() already handles missing files.

The explicit exists() guard provides a nicer error message, but it introduces a TOCTOU window. Since ImageReader::open returns an error if the file doesn't exist anyway, you could remove the pre-check and match on the open error kind to provide the same user-friendly message. Very minor — not blocking.


146-162: Duplicated normalization loop between process_file and process_crop.

The BGR channel-swap + normalize loop (lines 148–162) is copy-pasted in process_crop (lines 210–224). Consider extracting a shared helper, e.g.:

fn normalize_rgb_to_bgr(&self, rgb_img: &image::RgbImage) -> Vec<f32> { ... }

This would keep both paths in sync if the normalization logic ever changes.

Also applies to: 207-224

crates/mlx-core/src/models/pp_text_rec/processing.rs (1)

200-213: Dead binding default_ratio can be removed.

default_ratio is computed on line 200 and immediately discarded with let _ = default_ratio;. The comment explains the rationale, but the computation itself is unnecessary — consider removing both lines to reduce noise.

♻️ Proposed cleanup
-        let default_ratio = self.max_width as f64 / self.target_height as f64;
         let mut max_wh_ratio: f64 = 0.0;
         for (_rgb_data, width, height) in images.iter() {
             let ratio = *width as f64 / *height as f64;
             if ratio > max_wh_ratio {
                 max_wh_ratio = ratio;
             }
         }
-        // PaddleOCR clamps the minimum to the default ratio (imgW/imgH).
-        // But here we just need the max across images; the default ratio acts as a floor
-        // only if no image is wider. We don't enforce the floor because we want narrow
-        // images to produce narrow tensors when the batch is entirely narrow.
-        // However, we do need to cap at max_width.
-        let _ = default_ratio; // Not used as a floor; max_width cap is sufficient.
crates/mlx-core/src/models/pp_text_rec/model.rs (2)

89-117: recognize_batch processes images sequentially — missed batching opportunity.

The method name and doc suggest batch inference, but it loops over images individually. TextRecImageProcessor::process_batch already handles dynamic-width padding, so true batched inference through backbone→neck→head is possible and would better utilize hardware parallelism. At minimum, consider documenting this as a known limitation or renaming to avoid implying batched GPU execution.

♻️ Sketch using actual batch processing
     #[napi]
     pub fn recognize_batch(&self, image_paths: Vec<String>) -> Result<Vec<RecResult>> {
-        let mut results = Vec::with_capacity(image_paths.len());
-
-        // Process images one at a time through the model
-        // (batching requires all images to have same dimensions after processing)
-        for path in &image_paths {
-            let pixel_values = self.image_processor.process_file(path)?;
-            let logits = self.forward(&pixel_values)?;
-            let decoded = ctc_greedy_decode(&logits)?;
-
-            if decoded.is_empty() {
-                results.push(RecResult {
-                    text: String::new(),
-                    score: 0.0,
-                });
-                continue;
-            }
-
-            let (indices, scores) = &decoded[0];
-            let (text, score) = self.dictionary.decode_with_score(indices, scores);
-
-            results.push(RecResult {
-                text,
-                score: score as f64,
-            });
-        }
-
-        Ok(results)
+        // Load and collect RGB data for batch processing
+        let mut rgb_images = Vec::with_capacity(image_paths.len());
+        for path in &image_paths {
+            // ... load each image into (rgb_data, width, height) ...
+            todo!("collect rgb data from each path");
+        }
+
+        let pixel_values = self.image_processor.process_batch(&rgb_images)?;
+        let logits = self.forward(&pixel_values)?;
+        let decoded = ctc_greedy_decode(&logits)?;
+
+        // ... map decoded results back to RecResult vec ...
+        todo!("map decoded to results")
     }

60-79: Duplicated decode-result mapping across recognize, recognize_crop, and recognize_batch.

The pattern of calling ctc_greedy_decode → checking empty → dictionary.decode_with_score → constructing RecResult is repeated three times. Consider extracting a small helper to reduce duplication.

♻️ Example helper
fn decode_single(&self, logits: &MxArray) -> Result<RecResult> {
    let decoded = ctc_greedy_decode(&logits)?;
    if decoded.is_empty() {
        return Ok(RecResult { text: String::new(), score: 0.0 });
    }
    let (indices, scores) = &decoded[0];
    let (text, score) = self.dictionary.decode_with_score(indices, scores);
    Ok(RecResult { text, score: score as f64 })
}

Also applies to: 128-148

examples/vlm-inference.ts (1)

112-277: Ensure temp dir cleanup on errors.
If any crop/OCR step throws, rmSync at the end won’t run, leaving temp files. Wrap the pipeline after tmpDir creation in try/finally.

🔧 Suggested try/finally cleanup
-const tmpDir = mkdtempSync(join(tmpdir(), 'vlm-crop-'));
+const tmpDir = mkdtempSync(join(tmpdir(), 'vlm-crop-'));
+try {
   // Step 2-5 ...
-// Cleanup temp files
-rmSync(tmpDir, { recursive: true, force: true });
+} finally {
+  rmSync(tmpDir, { recursive: true, force: true });
+}
packages/vlm/src/pipeline/structure-v3.ts (1)

165-246: Consider whether explicit sorting is necessary based on DocLayoutModel.detect() behavior.

The code relies on detect() to return layout elements in reading order (as documented: "Vec of LayoutElements sorted by reading order"). However, assembleMarkdown() simply iterates through the elements array without using the order field to verify or enforce ordering. If the documentation is accurate, explicit sorting is unnecessary; if detect() can return unsorted elements despite its documented contract, adding defensive sorting would ensure deterministic output regardless.

Suggested defensive sorting
-    const layoutElements = this.layout.detect(imagePath, layoutThreshold);
+    const layoutElements = this.layout
+      .detect(imagePath, layoutThreshold)
+      .sort((a, b) => a.order - b.order);

Comment thread examples/vlm-inference.ts Resolved
Comment thread examples/vlm-inference.ts Resolved
@Brooooooklyn
Brooooooklyn merged commit 3538fcd into main Feb 12, 2026
6 checks passed
@Brooooooklyn
Brooooooklyn deleted the feat/pp-doclayout-v3 branch February 12, 2026 13:50
Brooooooklyn added a commit that referenced this pull request Apr 11, 2026
…5 text detection and recognition (#15)

Implements the full PP-StructureV3 pipeline: PP-DocLayoutV3 (layout
detection) + PP-OCRv5 TextDet (text line detection with LKPAN neck + DB
head) + PP-OCRv5 TextRec (text recognition with HGNetV2 backbone + SVTR
neck + CTC head).

Achieves ~4-5x faster text extraction than VLM-based OCR with ~6x
smaller model footprint (292MB vs 1.7GB). Includes PaddlePaddle
.pdiparams conversion scripts, ConvTranspose2d FFI support, and the
StructureV3Pipeline TypeScript API.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> High risk due to large new model surface area plus new batched
generation logic that merges/filters KV caches and calls unsafe FFI
(`mlx_paddleocr_vl_forward_step_batched`), which can impact correctness
and memory/perf.
> 
> **Overview**
> Adds new model modules for PP-Structure components, including an
initial PP-DocLayoutV3 implementation (HGNetV2 backbone/config plus
transformer decoder with deformable attention) with accompanying unit
tests.
> 
> Extends `paddleocr_vl` with N-API batch inputs (`VLMBatchItem`) and
new `VLModel.batch`/`VLModel.ocr_batch` APIs that do per-item prefill,
merge/left-pad KV caches, then run a batched decode loop via a new
`ERNIELanguageModel` batched fused forward path. Includes regression
tests to prevent cross-item token/KV misalignment when batch items
finish early.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
2ed2fed. 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**
* Added DocLayoutModel (PP-DocLayoutV3), TextDetModel and TextRecModel
for layout, text detection, and recognition.
* VLM: added batch OCR endpoints (ocrBatch, batch) and VlmBatchItem
support.
* New StructureV3 pipeline: end-to-end layout + OCR with Markdown
output.

* **API / Types**
* JS exports and typings extended: LayoutElement, TextBox, RecResult,
VlmBatchItem; VLModel gains ocrBatch/batch.

* **Chores**
* Updated example, packaging and image-processing dependencies and build
typings to support new features.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>
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
… iterative FD-bounded model walk

Fix-delta review of the review-#15 fixes confirmed #3/#4/#5 sound and surfaced
two Important edge-case defects in the two dashboard #15 fixes. Both verified
via control-flow analysis before fixing.

- A (models.ts isDownloaderOwned): the ownership marker was read with
  readFileSync, which FOLLOWS symlinks, so a live finalDir symlink into an
  external directory carrying a valid .mlx-download-complete.json was reported
  downloader-owned — slipping a foreign install past the no-follow occupancy
  preflight (a wasted overwrite, or a false "done" through the link). R15 #2
  hardened only the occupancy check. Now isDownloaderOwned lstat-gates on a REAL
  directory before reading the marker, so ANY symlink/non-directory (dangling OR
  live-into-a-marked-dir) is foreign at all three ownership call sites.

- B (models.ts walkDirStats): R15 #1's incremental opendirSync recursed into a
  child while the parent Dir handle was still open, holding one fd per level; a
  deep real-directory tree under a low RLIMIT_NOFILE hit EMFILE on a child
  opendirSync, which was swallowed with truncated=false — a silent
  false-complete undercount. Rewrote the walk as an explicit worklist of
  directory paths: each handle is closeSync'd before any child is opened (at
  most one fd ever live), and opendirSync/readSync failures now set
  truncated=true (a lower bound) instead of a silent return. Budget, no-follow
  symlink semantics, dev:ino cycle guard, and the exactly-maxEntries boundary
  are preserved.

Gate: typecheck 0; dashboard 198/198 (×2); lint 0. Dashboard-only — native
(#4/#5) and api.ts (#3) unchanged.

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
…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
… iterative FD-bounded model walk

Fix-delta review of the review-#15 fixes confirmed #3/#4/#5 sound and surfaced
two Important edge-case defects in the two dashboard #15 fixes. Both verified
via control-flow analysis before fixing.

- A (models.ts isDownloaderOwned): the ownership marker was read with
  readFileSync, which FOLLOWS symlinks, so a live finalDir symlink into an
  external directory carrying a valid .mlx-download-complete.json was reported
  downloader-owned — slipping a foreign install past the no-follow occupancy
  preflight (a wasted overwrite, or a false "done" through the link). R15 #2
  hardened only the occupancy check. Now isDownloaderOwned lstat-gates on a REAL
  directory before reading the marker, so ANY symlink/non-directory (dangling OR
  live-into-a-marked-dir) is foreign at all three ownership call sites.

- B (models.ts walkDirStats): R15 #1's incremental opendirSync recursed into a
  child while the parent Dir handle was still open, holding one fd per level; a
  deep real-directory tree under a low RLIMIT_NOFILE hit EMFILE on a child
  opendirSync, which was swallowed with truncated=false — a silent
  false-complete undercount. Rewrote the walk as an explicit worklist of
  directory paths: each handle is closeSync'd before any child is opened (at
  most one fd ever live), and opendirSync/readSync failures now set
  truncated=true (a lower bound) instead of a silent return. Budget, no-follow
  symlink semantics, dev:ino cycle guard, and the exactly-maxEntries boundary
  are preserved.

Gate: typecheck 0; dashboard 198/198 (×2); lint 0. Dashboard-only — native
(#4/#5) and api.ts (#3) unchanged.

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
…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
… iterative FD-bounded model walk

Fix-delta review of the review-#15 fixes confirmed #3/#4/#5 sound and surfaced
two Important edge-case defects in the two dashboard #15 fixes. Both verified
via control-flow analysis before fixing.

- A (models.ts isDownloaderOwned): the ownership marker was read with
  readFileSync, which FOLLOWS symlinks, so a live finalDir symlink into an
  external directory carrying a valid .mlx-download-complete.json was reported
  downloader-owned — slipping a foreign install past the no-follow occupancy
  preflight (a wasted overwrite, or a false "done" through the link). R15 #2
  hardened only the occupancy check. Now isDownloaderOwned lstat-gates on a REAL
  directory before reading the marker, so ANY symlink/non-directory (dangling OR
  live-into-a-marked-dir) is foreign at all three ownership call sites.

- B (models.ts walkDirStats): R15 #1's incremental opendirSync recursed into a
  child while the parent Dir handle was still open, holding one fd per level; a
  deep real-directory tree under a low RLIMIT_NOFILE hit EMFILE on a child
  opendirSync, which was swallowed with truncated=false — a silent
  false-complete undercount. Rewrote the walk as an explicit worklist of
  directory paths: each handle is closeSync'd before any child is opened (at
  most one fd ever live), and opendirSync/readSync failures now set
  truncated=true (a lower bound) instead of a silent return. Budget, no-follow
  symlink semantics, dev:ino cycle guard, and the exactly-maxEntries boundary
  are preserved.

Gate: typecheck 0; dashboard 198/198 (×2); lint 0. Dashboard-only — native
(#4/#5) and api.ts (#3) unchanged.

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