Skip to content

feat: add document preprocessing pipeline (orientation, unwarp) and refactor image APIs to in-memory buffers - #20

Merged
Brooooooklyn merged 1 commit into
mainfrom
feat/doc-preprocessing-pipeline
Feb 22, 2026
Merged

Brooooooklyn merged 1 commit into
mainfrom
feat/doc-preprocessing-pipeline

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Feb 21, 2026 •

Copy link
Copy Markdown
Contributor
  • Add PP-LCNet doc orientation model (0/90/180/270° classification + rotation)
  • Add UVDoc document unwarping model with reflect padding fix for correct displacement field output (matches original PyTorch reference within 0.001)
  • Add PyTorch .pkl checkpoint loader (pickle parser + weight conversion)
  • Refactor all image model APIs from file paths to in-memory Buffer/&[u8], eliminating temp file I/O throughout the OCR pipeline
  • Fix reading order: promote doc_title elements at top of page to front when the pairwise order model misranks them in multi-column layouts
  • Update StructureV3Pipeline and vlm-inference.ts to pass buffers through the full chain: orient → unwarp → layout → crop → OCR

Note

Medium Risk
Touches core NAPI surface area and changes image I/O semantics from paths to in-memory buffers, which can break downstream callers and alter runtime behavior across the OCR pipeline.

Overview
Adds two new NAPI-exposed preprocessing models, DocOrientationModel (classify + optional rotate) and DocUnwarpModel (unwarp), and exports new result types (OrientationResult, ClassifyRotateResult, UnwarpResult) plus a convertForeignWeights API for importing non-SafeTensors checkpoints.

Refactors the OCR/VLM and related document model APIs to take encoded image Buffers instead of file paths (including VlmChatConfig, ocr, ocrBatch, and batch items), wiring image processing through process_many and updating the generated JS/TS bindings and exports accordingly. Adds zip as a workspace dependency and introduces a small TS test suite to validate preprocessing model loading errors and type-level integration for preprocessing config/options.

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

Summary by CodeRabbit

  • New Features

    • Doc orientation (classify & auto-rotate) and document unwarp models exposed to JS; weight-conversion tool to import pretrained models.
    • Image APIs now accept encoded image buffers (replacing file-path inputs); pipeline supports optional orient/unwarp preprocessing and new CLI flags.
    • Updated examples demonstrating unwarp, buffer-based workflows, and preprocessing options.
  • Bug Fixes

    • Improved reading-order handling for document title elements.
  • Tests

    • Added tests for document preprocessing models and pipeline integration.

@coderabbitai

coderabbitai Bot commented Feb 21, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Adds two document-preprocessing models (orientation and unwarp), migrates many image APIs from file-paths to in-memory Buffers, introduces foreign-weight conversion (including pickle support), updates pipeline/examples to use in-memory preprocessing, and expands native/TS exports to expose the new models and conversion utility.

Changes

Cohort / File(s) Summary
Document Preprocessing Models
crates/mlx-core/src/models/pp_doc_ori/*, crates/mlx-core/src/models/pp_doc_unwarp/*
New PP-LCNet orientation and UVDoc unwarp implementations: configs, models, processing, persistence (SafeTensors loaders), N-API wrappers, and result types. Review persistence weight-loading and image-processing correctness.
Image API Migration (VL / OCR / Layout / Pipeline)
crates/mlx-core/src/models/paddleocr_vl/*, crates/mlx-core/src/models/pp_doclayout_v3/*, crates/mlx-core/src/models/pp_text_det/*, crates/mlx-core/src/models/pp_text_rec/*, packages/vlm/src/pipeline/structure-v3.ts
Replaced file-path APIs with in-memory Buffer APIs across processors and model entrypoints; updated batch APIs to accept Buffers; pipeline adapted to buffer-based cropping and preprocessing. Pay attention to signature changes, buffer lifetimes, and corners where temp-file logic was removed.
Foreign Weight Conversion & Pickle
crates/mlx-core/src/utils/foreign_weights.rs, crates/mlx-core/src/utils/pickle.rs, crates/mlx-core/src/utils/mod.rs
New convert_foreign_weights flow with Paddle/PyTorch loaders and SafeTensors writer; full Rust pickle deserializer added. High surface area — review parsing correctness, remapping logic, and produced SafeTensors/config.json.
Core Exports & Typings
crates/mlx-core/index.cjs, packages/core/index.cjs, packages/core/index.d.cts, packages/vlm/src/index.ts
Exposes DocOrientationModel, DocUnwarpModel, and convertForeignWeights on native binding surface and updates TypeScript declarations to Buffer-based signatures and new result types. Verify native bindings and TS typings stay in sync.
Processing Utilities & Activations
crates/mlx-core/src/models/pp_doclayout_v3/mod.rs, crates/mlx-core/src/nn/activations.rs
Added hard_swish / hard_sigmoid implementations and mapping; check numeric correctness and unit tests.
pp_doclayout Postprocessing
crates/mlx-core/src/models/pp_doclayout_v3/postprocessing.rs
Added heuristic to promote top doc_title elements in reading order; confirm ordering invariants and tests.
VL Model Changes (chat/ocr batch)
crates/mlx-core/src/models/paddleocr_vl/chat.rs, crates/mlx-core/src/models/paddleocr_vl/model.rs, crates/mlx-core/src/models/paddleocr_vl/processing.rs
Replaced image path fields with Buffer types and adjusted processing (process_bytes/process_many). Review napi Buffer usage and memory copies.
Utils & Workspace
crates/mlx-core/Cargo.toml, crates/mlx-core/*
Added zip dependency workspace-wide and crate-level module additions. Confirm Cargo workspace consistency and feature flags.
Examples, CLI & Scripts
examples/*, scripts/*, examples/vlm-inference.ts, examples/debug_unwarp.ts
Examples and scripts updated to use Buffer-based flows and new CLI options for preprocessing and model conversion. Validate end-to-end examples.
Tests
__test__/models/doc-preprocess.test.ts
New tests for model load/error cases and StructureV3Pipeline preprocessing config. Ensure tests cover both success and failure model-load paths.

Sequence Diagram(s)

sequenceDiagram
    actor User
    participant JS as JavaScript Client
    participant Pipeline as StructureV3Pipeline
    participant Orient as DocOrientationModel
    participant Unwarp as DocUnwarpModel
    participant Layout as DocLayoutModel
    participant OCR as OCR Models

    User->>JS: analyze(imageData, options)
    JS->>Pipeline: analyze(imageData, {useDocOrientationClassify, useDocUnwarping})

    opt useDocOrientationClassify
        Pipeline->>Orient: classify(imageData)
        Orient-->>Pipeline: OrientationResult
        Pipeline->>Orient: classifyAndRotate(imageData)
        Orient-->>Pipeline: rotated image bytes
        Note over Pipeline: replace imageData with rotated bytes
    end

    opt useDocUnwarping
        Pipeline->>Unwarp: unwarp(imageData)
        Unwarp-->>Pipeline: UnwarpResult (bytes, success)
        Note over Pipeline: replace imageData with unwarped bytes
    end

    Pipeline->>Layout: detect(imageData)
    Layout-->>Pipeline: layout elements
    Pipeline->>OCR: ocr regions (Buffers)
    OCR-->>Pipeline: text results
    Pipeline-->>JS: structured document
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰
I hop on bytes and buffers bright,
I twist and unwarp each doc just right.
From orient to unwarp, I mend the page,
A floppy-eared coder on the processing stage — hooray! 🎩📄

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The PR title accurately summarizes the main changes: addition of document preprocessing models (orientation and unwarp) and refactoring of image APIs from file paths to in-memory buffers.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/doc-preprocessing-pipeline

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

Caution

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

⚠️ Outside diff range comments (5)
crates/mlx-core/src/models/pp_text_det/processing.rs (1)

198-198: ⚠️ Potential issue | 🟡 Minor

Stale method name in comment.

The comment references the old process_file which no longer exists.

📝 Proposed fix
-        // Channel mapping: RGB->BGR (same as process_file)
+        // Channel mapping: RGB->BGR (same as process)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/pp_text_det/processing.rs` at line 198, Comment in
processing.rs incorrectly references the removed process_file method; update the
comment to reference the current function that performs the same RGB->BGR
mapping (e.g., the function handling image channel conversion in this module
such as process_image or convert_channels) so the comment stays accurate and
meaningful. Locate the "// Channel mapping: RGB->BGR (same as process_file)"
comment and replace "process_file" with the correct current function name used
for channel mapping in this module, keeping the rest of the comment intact.
crates/mlx-core/src/models/paddleocr_vl/model.rs (2)

126-155: ⚠️ Potential issue | 🟡 Minor

Update comment to match process_many.

Line 153 still references process_files, but the code now uses process_many.

✏️ Suggested comment fix
-                // grid_thw already [num_images, 3] from process_files
+                // grid_thw already [num_images, 3] from process_many
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/paddleocr_vl/model.rs` around lines 126 - 155, The
inline comment incorrectly references process_files; update it to reflect the
current use of process_many: change the comment near the processed.grid_thw()
call (variable processed and method processed.grid_thw()) to something like "//
grid_thw already [num_images, 3] from process_many" so the comment matches the
actual code path and clarifies the source of grid_thw.

1025-1071: ⚠️ Potential issue | 🟡 Minor

Update ocrBatch example to use buffers.

The example still shows file paths; the API now expects encoded image buffers.

✏️ Suggested doc update
-    /// const texts = model.ocrBatch(['page1.jpg', 'page2.jpg', 'page3.jpg']);
+    /// const texts = model.ocrBatch([
+    ///   readFileSync('page1.jpg'),
+    ///   readFileSync('page2.jpg'),
+    ///   readFileSync('page3.jpg')
+    /// ]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/paddleocr_vl/model.rs` around lines 1025 - 1071,
The doc comment for ocr_batch currently shows file path strings but the API
expects encoded image buffers; update the example and description to demonstrate
passing a Vec<Buffer> (encoded image buffers) into ocr_batch and clarify that
each item becomes a VLMBatchItem with images: Some(vec![Buffer]) and messages
built with VLMChatMessage; replace the example that uses file paths with one
that constructs/mentions buffers (e.g., encoded bytes or Buffer.from(...)) and
ensure the top-level doc text explicitly states "images - Encoded image buffers"
and that the function accepts Vec<Buffer> inputs.
packages/core/index.d.cts (2)

1736-1741: ⚠️ Potential issue | 🟡 Minor

Stale example in ocrBatch doc comment — passes strings instead of Buffers.

The example still shows model.ocrBatch(['page1.jpg', 'page2.jpg', 'page3.jpg']) but the signature now accepts Array<Buffer>. This doc comment originates from the Rust source and would confuse TypeScript consumers.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/index.d.cts` around lines 1736 - 1741, The doc comment for the
ocrBatch declaration is stale: the example shows passing string file names but
the signature ocrBatch(images: Array<Buffer>, ...) expects Buffers; update the
example in the ocrBatch JSDoc to demonstrate creating and passing Buffer
instances (e.g., Buffer.from or fs.readFileSync) so TypeScript consumers see
correct usage with the ocrBatch function.

1773-1778: ⚠️ Potential issue | 🟡 Minor

Stale example in VLModel.load doc comment — uses old imagePaths property.

The example shows { imagePaths: ['./image.jpg'] } but VlmChatConfig now uses images: Array<Buffer>. The fix should be applied in the Rust doc comment for VLModel::load.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/index.d.cts` around lines 1773 - 1778, Update the Rust doc
comment for VLModel::load to replace the stale TypeScript example that uses the
old imagePaths property with the new VlmChatConfig shape: use images (an
Array<Buffer>) instead of imagePaths; update the example call (e.g.,
model.chat(...)) to pass images: Array<Buffer> so the docs reflect the current
VlmChatConfig type and signature.
🧹 Nitpick comments (11)
scripts/download-model.ts (1)

143-149: Verify whether .pdmodel (graph file) also needs to be downloaded.

Standard PaddlePaddle inference format requires both a .pdmodel file (model structure) and a .pdiparams file (model weights). The current filter only downloads .pdiparams. If the custom pickle loader built into the Rust crate reconstructs the graph from its own hardcoded topology, this is intentional — but if any paddle model variant served from HuggingFace also ships its .pdmodel and the runtime ever needs it, it will silently be absent after download.

Please confirm whether .pdmodel is explicitly not needed (because topology is embedded in Rust) and, if so, add a brief comment explaining that rationale so future maintainers don't add it by mistake.

Separately, the .yml filter is broad enough to match GitHub Actions workflows or other unrelated YAML files that some HuggingFace repos store at the root. Consider scoping it more tightly — e.g., matching only inference.yml or checking for PaddlePaddle-specific YAML names:

♻️ Proposed tighter YAML filter
-      file.path.endsWith('.yml')
+      file.path === 'inference.yml' ||
+      file.path.endsWith('.yml') && !file.path.includes('/')
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@scripts/download-model.ts` around lines 143 - 149, The current download
filter in scripts/download-model.ts checks CORE_FILES and extensions like
.pdiparams and .yml but omits .pdmodel and uses a broad .yml match; update the
filter around the file.path check to either include .pdmodel alongside
.pdiparams (if Paddle .pdmodel is required) or add a clear inline comment next
to the conditional/CORE_FILES explaining that .pdmodel is intentionally excluded
because the Rust loader reconstructs topology internally; also tighten the YAML
match to specific names (e.g., file.path.endsWith('inference.yml') or matching
/^.*(paddle|inference)\.ya?ml$/) instead of a blanket .yml to avoid downloading
unrelated workflows.
crates/mlx-core/src/nn/activations.rs (2)

212-252: Add autograd-breaking disclaimer (follow silu doc pattern).

Both hard_swish and hard_sigmoid clean up intermediate FFI handles, which breaks the MLX lazy-evaluation computation graph — identical to how silu works. Unlike silu, neither function documents this. The silu doc explicitly states:

"This version cleans up intermediate handles after use … doesn't preserve the computation graph for autograd. Use silu_for_autograd in training contexts."

Without the same disclaimer, a caller who uses these in a training forward-pass will silently get no gradients. Following the established codebase pattern, consider also providing hard_swish_for_autograd / hard_sigmoid_for_autograd variants built on the high-level MxArray operations (like silu_for_autograd).

📝 Proposed doc additions
-    /// Hard Swish: x * clamp(x + 3, 0, 6) / 6
-    /// Used in PP-LCNet (MobileNet-style architectures).
+    /// Hard Swish: x * clamp(x + 3, 0, 6) / 6
+    /// Used in PP-LCNet (MobileNet-style architectures).
+    ///
+    /// This version cleans up intermediate handles after use.
+    /// It works well for inference but doesn't preserve the computation graph for autograd.
+    /// If gradient computation is needed, implement a `hard_swish_for_autograd` variant
+    /// using high-level `MxArray` operations (see `silu_for_autograd`).
     pub fn hard_swish(input: &MxArray) -> Result<MxArray> {
-    /// Hard Sigmoid: clamp(x / 6 + 0.5, 0, 1)
-    /// Used in SE modules of PP-LCNet.
+    /// Hard Sigmoid: clamp(x / 6 + 0.5, 0, 1)
+    /// Used in SE modules of PP-LCNet.
+    ///
+    /// This version cleans up intermediate handles after use.
+    /// It works well for inference but doesn't preserve the computation graph for autograd.
+    /// If gradient computation is needed, implement a `hard_sigmoid_for_autograd` variant
+    /// using high-level `MxArray` operations (see `silu_for_autograd`).
     pub fn hard_sigmoid(input: &MxArray) -> Result<MxArray> {

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

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/nn/activations.rs` around lines 212 - 252, The hard_swish
and hard_sigmoid implementations (functions hard_swish and hard_sigmoid) free
intermediate FFI handles and therefore break autograd like silu does; add the
same doc disclaimer used in silu noting these versions clean up intermediate
handles and do not preserve the computation graph, and advise using
hard_swish_for_autograd / hard_sigmoid_for_autograd in training; implement
corresponding *_for_autograd variants using high‑level MxArray operations
(avoiding manual sys::mlx_array_delete) mirroring silu_for_autograd, and
register/implement any required backward logic in the gradients/ module so
autograd can compute gradients for these activations.

292-309: test_hard_swish never exercises the fractional (interior) activation path.

All five chosen inputs produce either 0.0 (clamped-zero region) or the identity value (linear region where clamp(x+3,0,6)/6 = 1). No test case validates that the formula yields a fractional result for an input strictly in (-3, 3), e.g. x = 1.0 → 1 * clamp(4,0,6) / 6 = 4/6 ≈ 0.6667.

🧪 Proposed additional assertion
     // x=0: 0 * clamp(3, 0, 6) / 6 = 0
     assert!((data[2] - 0.0).abs() < 1e-6);
+    // x=1: 1 * clamp(4, 0, 6) / 6 = 4/6 ≈ 0.6667  (interior / fractional region)
+    // x=3: 3 * clamp(6, 0, 6) / 6 = 3 * 6 / 6 = 3

Adjust the test input slice accordingly:

-    let input = MxArray::from_float32(&[-4.0, -3.0, 0.0, 3.0, 4.0], &[5]).unwrap();
+    let input = MxArray::from_float32(&[-4.0, -3.0, 0.0, 1.0, 3.0, 4.0], &[6]).unwrap();

and add the assertion after data[2]:

+    // x=1: 1 * clamp(4, 0, 6) / 6 = 4/6
+    assert!((data[3] - (4.0_f32 / 6.0)).abs() < 1e-6);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/nn/activations.rs` around lines 292 - 309,
test_hard_swish in Activations::hard_swish never covers the interior fractional
region; update the test input vector used in test_hard_swish to include a value
inside (-3,3) (e.g., 1.0) and add an assertion that checks the fractional output
(for x=1.0 expect ~0.6666667 with appropriate tolerance) so the branch computing
x * clamp(x+3,0,6) / 6 is exercised.
Cargo.toml (1)

33-33: Consider bumping zip to a newer major version.

The deflate feature name is valid and correctly covers both reading and writing deflate-compressed entries. By default, aes-crypto, bzip2, deflate, deflate64, lzma, ppmd, time, xz, and zstd are enabled. Pinning to "2" is functionally sound, but the zip crate is now at 7.x. The workspace rust-version = "1.89.0" satisfies even the latest MSRV, so an upgrade is safe. At minimum, verify that any new features or security fixes in later major versions are not needed before releasing.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Cargo.toml` at line 33, Update the zip dependency from the pinned major "2"
to a more recent major (e.g., "7") in Cargo.toml and verify the feature set
remains correct: ensure the "deflate" feature is still enabled (and any other
needed features like aes-crypto, bzip2, xz, zstd etc. are explicitly set or
intentionally disabled), run cargo update / cargo build to catch API or MSRV
incompatibilities, and confirm the workspace rust-version = "1.89.0" satisfies
the new zip crate's MSRV before finalizing the bump.
crates/mlx-core/src/models/pp_doclayout_v3/processing.rs (1)

73-81: Optional: iterate over the raw pixel buffer instead of get_pixel.

get_pixel issues a bounds-checked indirect call per pixel. For an 800×800 image (640 K iterations) iterating over the contiguous as_raw() slice or .pixels() iterator avoids the per-pixel overhead.

♻️ Proposed refactor using raw buffer
-        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);
-                }
-            }
-        }
+        for chunk in rgb_img.as_raw().chunks_exact(3) {
+            pixel_data.push(chunk[0] as f32 / 255.0); // R
+            pixel_data.push(chunk[1] as f32 / 255.0); // G
+            pixel_data.push(chunk[2] as f32 / 255.0); // B
+        }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/pp_doclayout_v3/processing.rs` around lines 73 -
81, The loop uses rgb_img.get_pixel(x, y) which does a bounds-checked call per
pixel; instead iterate the contiguous buffer (rgb_img.as_raw() or
rgb_img.pixels()) and normalize bytes directly into pixel_data to avoid
per-pixel indirect/bounds overhead. Replace the nested x/y/get_pixel loop with a
single iteration over rgb_img.as_raw().chunks_exact(channels) or over
rgb_img.pixels() and for each byte push (byte as f32 / 255.0) into pixel_data,
preserving the same channel order and using the existing variables rgb_img,
pixel_data, and channels.
examples/debug_unwarp.ts (1)

11-15: Consider guarding the file write on result.success.

The script logs result.success but unconditionally writes result.image to disk. If unwarp fails, this could write an empty or invalid buffer.

Suggested fix
 const result = model.unwarp(imageBuffer);
 console.log(`Unwarp success: ${result.success}`);
 console.log(`Output image: ${result.image.length} bytes`);
 
-writeFileSync('/tmp/unwarped_debug.png', result.image);
-console.log('Saved to /tmp/unwarped_debug.png');
+if (result.success) {
+  writeFileSync('/tmp/unwarped_debug.png', result.image);
+  console.log('Saved to /tmp/unwarped_debug.png');
+} else {
+  console.error('Unwarp failed, skipping file write');
+  process.exit(1);
+}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@examples/debug_unwarp.ts` around lines 11 - 15, Guard the writeFileSync call
so you only write result.image when model.unwarp succeeded: check result.success
before calling writeFileSync('/tmp/unwarped_debug.png', result.image) and skip
or log an error when false; use the existing result object (result.success and
result.image) and the writeFileSync call to implement the conditional write and
avoid writing empty/invalid buffers.
__test__/models/doc-preprocess.test.ts (1)

50-55: Consider also asserting the re-exported types at runtime.

Line 53-54 check that DocOrientationModel and DocUnwarpModel are toBeDefined() via dynamic import of @mlx-node/vlm, which is good. You might also verify they are the same references as the ones from @mlx-node/core to ensure the re-export is correctly wired (not accidentally shadowed).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@__test__/models/doc-preprocess.test.ts` around lines 50 - 55, The test
currently only checks that DocOrientationModel and DocUnwarpModel are defined
from the dynamic import of '@mlx-node/vlm'; update the test to also import the
originals from '@mlx-node/core' and assert that vlm.DocOrientationModel and
vlm.DocUnwarpModel are the exact same references as core.DocOrientationModel and
core.DocUnwarpModel (use strict equality assertions like toBe) to ensure the
re-exports are not shadowed or replaced.
crates/mlx-core/src/models/pp_doc_unwarp/model.rs (1)

342-349: success field in UnwarpResult is always true.

Errors are returned as Err(...), so this field can never be false in practice. It's dead information from the caller's perspective. If it's intended for forward-compatibility (e.g., partial-success scenarios), a comment would clarify; otherwise it adds noise to the API.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/pp_doc_unwarp/model.rs` around lines 342 - 349,
The UnwarpResult struct's success field is dead (always true because failures
are returned via Err); remove the success: bool field from the UnwarpResult
#[napi(object)] definition (the struct itself) and update all callers/consumers
to rely on Result vs Err instead of reading UnwarpResult.success; also update
any code that constructs UnwarpResult (e.g., functions returning UnwarpResult
like unwarp_document or builders creating UnwarpResult) to stop setting success,
and adjust any JS bindings/tests to check for a thrown/Err result rather than a
success flag. If you instead prefer to keep it for forward-compatibility,
replace it with a documented enum/option (e.g., status: Option<String>) and add
a comment explaining intended future semantics so consumers know why it exists.
crates/mlx-core/src/models/pp_doc_unwarp/persistence.rs (1)

225-241: Encoder loads only 3 of the 4 configured block groups.

UVDocConfig::default() defines block_nums: [3, 4, 6, 3] and stride: [1, 2, 2, 2] (4 entries each), but the encoder loop at Line 227 iterates 0..3, using only the first 3. The 4th entry is silently ignored. This appears intentional for UVDoc's ResnetStraight architecture (validated by the ≤0.001 match with PyTorch), but the config carries dead entries that could mislead future maintainers.

Consider either documenting why only 3 layers are used or trimming the config arrays to 3 entries.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/pp_doc_unwarp/persistence.rs` around lines 225 -
241, The encoder build loop currently iterates only 3 layers (the for loop in
persistence.rs that constructs encoder_layers and calls
load_residual_block/ResLayer::new), but UVDocConfig::default() supplies 4-entry
arrays (block_nums and stride), leaving the 4th entry unused; either remove the
unused 4th entries from UVDocConfig::default() (trim block_nums and stride to 3
entries) or explicitly document this design by adding a clear comment above the
encoder loop stating that ResnetStraight intentionally uses only the first 3
groups and add a runtime assertion (e.g., require block_nums.len() >= 3 and
stride.len() >= 3) to avoid silent misconfiguration — update references to
block_nums and stride and ensure load_residual_block and ResLayer::new usage
remains consistent.
crates/mlx-core/src/models/pp_doc_unwarp/processing.rs (1)

66-71: No validation that grid_data.len() >= grid_h * grid_w * 2.

Line 104 indexes into grid_data using gy * grid_w * 2 + gx * 2 + ch without bounds checking. If a caller provides mismatched grid_h/grid_w vs grid_data length, this will panic. Currently safe because the sole call site (model.rs) derives all three from the same tensor, but a debug assertion would harden this public function.

🛡️ Suggested defensive check
 pub fn apply_displacement_field(
     data: &[u8],
     grid_data: &[f32],
     grid_h: usize,
     grid_w: usize,
 ) -> Result<Vec<u8>> {
+    let expected_len = grid_h * grid_w * 2;
+    if grid_data.len() < expected_len {
+        return Err(Error::new(
+            Status::InvalidArg,
+            format!(
+                "grid_data length {} < expected {} (grid {}×{}×2)",
+                grid_data.len(), expected_len, grid_h, grid_w
+            ),
+        ));
+    }
     let img = image::load_from_memory(data).map_err(|e| {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/pp_doc_unwarp/processing.rs` around lines 66 - 71,
The function apply_displacement_field currently indexes grid_data using gy *
grid_w * 2 + gx * 2 + ch without validating grid_data length; add a defensive
check at the start of apply_displacement_field that verifies grid_data.len() >=
grid_h.checked_mul(grid_w).and_then(|v| v.checked_mul(2)).unwrap_or(usize::MAX)
(or compute safe multiplication with checked_* to avoid overflow) and return an
Err (or use debug_assert! in addition) when the condition fails so callers
cannot panic; update error path to produce a clear Result::Err describing the
mismatch so consumers of apply_displacement_field (and callers like model.rs)
get a safe, explicit failure instead of a panic.
crates/mlx-core/src/models/pp_doc_ori/model.rs (1)

238-274: Synchronous NAPI methods block the Node.js event loop.

Both classify and classify_and_rotate are synchronous #[napi] methods. For the 224×224 classification this is likely fast enough, but classify_and_rotate also decodes, rotates, and re-encodes the original-resolution image (via processing::rotate), which could be noticeably slow for large scanned documents.

Consider whether an async variant (or at least a doc comment warning) is warranted for the rotation path. This matches the chill review intent — flagging for awareness, not blocking.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/pp_doc_ori/model.rs` around lines 238 - 274, The
synchronous #[napi] methods classify and classify_and_rotate block the Node
event loop during heavy work (notably processing::rotate called from
classify_and_rotate); change classify_and_rotate to an async N-API method that
performs CPU-bound work off the JS thread (e.g., use a spawn_blocking or an
AsyncTask to call self.classify_bytes, processing::correction_angle and
processing::rotate) and return a Promise for ClassifyRotateResult, or at minimum
add a clear doc comment on classify_and_rotate warning callers that rotation
operates on original-resolution images and can be slow; reference
DocOrientationModel, classify, classify_and_rotate, processing::rotate and
processing::correction_angle when making the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@crates/mlx-core/src/models/pp_doc_ori/model.rs`:
- Around line 286-298: The code using prob_vec.iter().enumerate().max_by(|(_,
a), (_, b)| a.partial_cmp(b).unwrap()) can panic on NaN and later when indexing
ORIENTATION_LABELS[max_idx] if lengths mismatch; change the selection to handle
NaN safely (use partial_cmp(...).unwrap_or(std::cmp::Ordering::Less) or
filter_map to skip NaNs) and avoid unguarded unwraps by returning a Result error
if no valid max exists; after obtaining max_idx, validate that max_idx <
ORIENTATION_LABELS.len() (or check that prob_vec.len() ==
ORIENTATION_LABELS.len()) and return an Err if not, then construct
OrientationResult with the safe score and label only when checks pass (refer to
prob_vec, max_by/partial_cmp, max_idx, max_score, ORIENTATION_LABELS, and
OrientationResult).
- Around line 157-191: The struct doc for ClassificationHead currently misstates
the weight shape; update the comment for the field weight to reflect the actual
shape used by forward: change the doc on weight to "/// FC weight [in_channels,
num_classes]" so it matches the forward implementation where flat (shape [B,
channels]) is matmul'ed with self.weight to produce [B, num_classes]; ensure the
comment aligns with the earlier remark "Weight is stored as [in_features,
out_features] (Paddle convention)" in the forward method.

In `@crates/mlx-core/src/models/pp_doc_unwarp/config.rs`:
- Around line 9-10: The inline doc for the struct field img_size is inconsistent
with the default value and module-level doc: change the field doc from "[width,
height]" to "[height, width]" so it matches the default tuple (488, 712) and the
module-level "NHWC" note; update any nearby comments that describe img_size to
use the same (height, width) ordering to avoid confusion (look for img_size in
config.rs and mod.rs).

In `@crates/mlx-core/src/models/pp_doclayout_v3/postprocessing.rs`:
- Around line 209-217: The current promotion logic shifts non-title elements by
num_promoted causing gaps in the order sequence (variables: elements, title_set,
num_promoted); after the existing elements.sort_by_key(|e| e.order) add a
renormalization pass that iterates the sorted elements with enumerate and
assigns each element's order to its new contiguous index (e.g., order = index as
_), ensuring 0-based dense indices matching array position and preserving the
documented invariant.

In `@crates/mlx-core/src/utils/foreign_weights.rs`:
- Around line 168-197: The convert_uvdoc function currently errors if a
directory lacks inference.pdiparams and inference.json; change it to also scan
the directory for PyTorch checkpoints and fall back to loading them: add a
helper like find_pytorch_checkpoint_in_dir(dir: &Path) ->
Result<Option<PathBuf>> (similar to find_pdparams_in_dir) that looks for
extensions pkl/pt/pth, call it in the branch where pdiparams/json are missing,
and if it returns Some(path) use load_pytorch_checkpoint(path, verbose) and
convert_uvdoc_pytorch_keys(...) instead of returning an error; keep the existing
error path if no checkpoint is found.

In `@crates/mlx-core/src/utils/pickle.rs`:
- Around line 112-113: The function unpickle (pub fn unpickle(data: &[u8]) ->
Result<PickleValue>) is public but not annotated with #[napi]; either reduce its
visibility to crate-level (pub(crate) fn unpickle ...) if it should remain
internal, or add a napi-exported wrapper annotated with #[napi] that calls the
internal unpickle and converts/returns types safe for N-API; update references
to use the new visibility or wrapper accordingly so the public API follows the
project's N-API export guideline.

In `@examples/vlm-inference.ts`:
- Around line 117-126: The orientation pipeline calls orientModel.classify(...)
and then, if angle !== 0, calls orientModel.classifyAndRotate(...) which re-runs
inference; to fix, replace that two-step sequence by either (A) always calling
orientModel.classifyAndRotate(imageData) and using its returned {angle, score,
image} (skip replacing image when angle === 0), or (B) add a
rotateOnly(imageData, angle) method on orientModel and change the code to call
orientModel.classify(imageData) to get the angle/score and then call
orientModel.rotateOnly(imageData, oriResult.angle) when angle !== 0; apply the
same change to the duplicate block at the later pipeline (lines 164-176) so
orientation inference only runs once.

In `@packages/vlm/src/pipeline/structure-v3.ts`:
- Around line 198-204: The code currently calls
this.docOrientation.classify(...) and then, if oriResult.angle !== 0, calls
this.docOrientation.classifyAndRotate(...), causing double inference; replace
that flow by calling this.docOrientation.classifyAndRotate(imageBuffer) once
(respecting the existing guard on options.useDocOrientationClassify) and use the
returned object's angle to decide whether to replace imageBuffer with
Buffer.from(result.image); update references from oriResult to the single
rotateResult (or similar) so the orientation model runs only once.

In `@scripts/download-model.ts`:
- Around line 233-234: The current conditional masks hasPaddleModel behind
hasConfig, causing paddle-only models to always skip the "already downloaded"
branch; change the guard that currently reads hasConfig && (hasSingleModel ||
hasShardedModel || hasPaddleModel) to short-circuit hasPaddleModel independently
so paddle-only models are treated as already present—for example, use (hasConfig
&& (hasSingleModel || hasShardedModel)) || hasPaddleModel (reference variables:
hasPaddleModel, hasConfig, hasSingleModel, hasShardedModel).

---

Outside diff comments:
In `@crates/mlx-core/src/models/paddleocr_vl/model.rs`:
- Around line 126-155: The inline comment incorrectly references process_files;
update it to reflect the current use of process_many: change the comment near
the processed.grid_thw() call (variable processed and method
processed.grid_thw()) to something like "// grid_thw already [num_images, 3]
from process_many" so the comment matches the actual code path and clarifies the
source of grid_thw.
- Around line 1025-1071: The doc comment for ocr_batch currently shows file path
strings but the API expects encoded image buffers; update the example and
description to demonstrate passing a Vec<Buffer> (encoded image buffers) into
ocr_batch and clarify that each item becomes a VLMBatchItem with images:
Some(vec![Buffer]) and messages built with VLMChatMessage; replace the example
that uses file paths with one that constructs/mentions buffers (e.g., encoded
bytes or Buffer.from(...)) and ensure the top-level doc text explicitly states
"images - Encoded image buffers" and that the function accepts Vec<Buffer>
inputs.

In `@crates/mlx-core/src/models/pp_text_det/processing.rs`:
- Line 198: Comment in processing.rs incorrectly references the removed
process_file method; update the comment to reference the current function that
performs the same RGB->BGR mapping (e.g., the function handling image channel
conversion in this module such as process_image or convert_channels) so the
comment stays accurate and meaningful. Locate the "// Channel mapping: RGB->BGR
(same as process_file)" comment and replace "process_file" with the correct
current function name used for channel mapping in this module, keeping the rest
of the comment intact.

In `@packages/core/index.d.cts`:
- Around line 1736-1741: The doc comment for the ocrBatch declaration is stale:
the example shows passing string file names but the signature ocrBatch(images:
Array<Buffer>, ...) expects Buffers; update the example in the ocrBatch JSDoc to
demonstrate creating and passing Buffer instances (e.g., Buffer.from or
fs.readFileSync) so TypeScript consumers see correct usage with the ocrBatch
function.
- Around line 1773-1778: Update the Rust doc comment for VLModel::load to
replace the stale TypeScript example that uses the old imagePaths property with
the new VlmChatConfig shape: use images (an Array<Buffer>) instead of
imagePaths; update the example call (e.g., model.chat(...)) to pass images:
Array<Buffer> so the docs reflect the current VlmChatConfig type and signature.

---

Nitpick comments:
In `@__test__/models/doc-preprocess.test.ts`:
- Around line 50-55: The test currently only checks that DocOrientationModel and
DocUnwarpModel are defined from the dynamic import of '@mlx-node/vlm'; update
the test to also import the originals from '@mlx-node/core' and assert that
vlm.DocOrientationModel and vlm.DocUnwarpModel are the exact same references as
core.DocOrientationModel and core.DocUnwarpModel (use strict equality assertions
like toBe) to ensure the re-exports are not shadowed or replaced.

In `@Cargo.toml`:
- Line 33: Update the zip dependency from the pinned major "2" to a more recent
major (e.g., "7") in Cargo.toml and verify the feature set remains correct:
ensure the "deflate" feature is still enabled (and any other needed features
like aes-crypto, bzip2, xz, zstd etc. are explicitly set or intentionally
disabled), run cargo update / cargo build to catch API or MSRV
incompatibilities, and confirm the workspace rust-version = "1.89.0" satisfies
the new zip crate's MSRV before finalizing the bump.

In `@crates/mlx-core/src/models/pp_doc_ori/model.rs`:
- Around line 238-274: The synchronous #[napi] methods classify and
classify_and_rotate block the Node event loop during heavy work (notably
processing::rotate called from classify_and_rotate); change classify_and_rotate
to an async N-API method that performs CPU-bound work off the JS thread (e.g.,
use a spawn_blocking or an AsyncTask to call self.classify_bytes,
processing::correction_angle and processing::rotate) and return a Promise for
ClassifyRotateResult, or at minimum add a clear doc comment on
classify_and_rotate warning callers that rotation operates on
original-resolution images and can be slow; reference DocOrientationModel,
classify, classify_and_rotate, processing::rotate and
processing::correction_angle when making the change.

In `@crates/mlx-core/src/models/pp_doc_unwarp/model.rs`:
- Around line 342-349: The UnwarpResult struct's success field is dead (always
true because failures are returned via Err); remove the success: bool field from
the UnwarpResult #[napi(object)] definition (the struct itself) and update all
callers/consumers to rely on Result vs Err instead of reading
UnwarpResult.success; also update any code that constructs UnwarpResult (e.g.,
functions returning UnwarpResult like unwarp_document or builders creating
UnwarpResult) to stop setting success, and adjust any JS bindings/tests to check
for a thrown/Err result rather than a success flag. If you instead prefer to
keep it for forward-compatibility, replace it with a documented enum/option
(e.g., status: Option<String>) and add a comment explaining intended future
semantics so consumers know why it exists.

In `@crates/mlx-core/src/models/pp_doc_unwarp/persistence.rs`:
- Around line 225-241: The encoder build loop currently iterates only 3 layers
(the for loop in persistence.rs that constructs encoder_layers and calls
load_residual_block/ResLayer::new), but UVDocConfig::default() supplies 4-entry
arrays (block_nums and stride), leaving the 4th entry unused; either remove the
unused 4th entries from UVDocConfig::default() (trim block_nums and stride to 3
entries) or explicitly document this design by adding a clear comment above the
encoder loop stating that ResnetStraight intentionally uses only the first 3
groups and add a runtime assertion (e.g., require block_nums.len() >= 3 and
stride.len() >= 3) to avoid silent misconfiguration — update references to
block_nums and stride and ensure load_residual_block and ResLayer::new usage
remains consistent.

In `@crates/mlx-core/src/models/pp_doc_unwarp/processing.rs`:
- Around line 66-71: The function apply_displacement_field currently indexes
grid_data using gy * grid_w * 2 + gx * 2 + ch without validating grid_data
length; add a defensive check at the start of apply_displacement_field that
verifies grid_data.len() >= grid_h.checked_mul(grid_w).and_then(|v|
v.checked_mul(2)).unwrap_or(usize::MAX) (or compute safe multiplication with
checked_* to avoid overflow) and return an Err (or use debug_assert! in
addition) when the condition fails so callers cannot panic; update error path to
produce a clear Result::Err describing the mismatch so consumers of
apply_displacement_field (and callers like model.rs) get a safe, explicit
failure instead of a panic.

In `@crates/mlx-core/src/models/pp_doclayout_v3/processing.rs`:
- Around line 73-81: The loop uses rgb_img.get_pixel(x, y) which does a
bounds-checked call per pixel; instead iterate the contiguous buffer
(rgb_img.as_raw() or rgb_img.pixels()) and normalize bytes directly into
pixel_data to avoid per-pixel indirect/bounds overhead. Replace the nested
x/y/get_pixel loop with a single iteration over
rgb_img.as_raw().chunks_exact(channels) or over rgb_img.pixels() and for each
byte push (byte as f32 / 255.0) into pixel_data, preserving the same channel
order and using the existing variables rgb_img, pixel_data, and channels.

In `@crates/mlx-core/src/nn/activations.rs`:
- Around line 212-252: The hard_swish and hard_sigmoid implementations
(functions hard_swish and hard_sigmoid) free intermediate FFI handles and
therefore break autograd like silu does; add the same doc disclaimer used in
silu noting these versions clean up intermediate handles and do not preserve the
computation graph, and advise using hard_swish_for_autograd /
hard_sigmoid_for_autograd in training; implement corresponding *_for_autograd
variants using high‑level MxArray operations (avoiding manual
sys::mlx_array_delete) mirroring silu_for_autograd, and register/implement any
required backward logic in the gradients/ module so autograd can compute
gradients for these activations.
- Around line 292-309: test_hard_swish in Activations::hard_swish never covers
the interior fractional region; update the test input vector used in
test_hard_swish to include a value inside (-3,3) (e.g., 1.0) and add an
assertion that checks the fractional output (for x=1.0 expect ~0.6666667 with
appropriate tolerance) so the branch computing x * clamp(x+3,0,6) / 6 is
exercised.

In `@examples/debug_unwarp.ts`:
- Around line 11-15: Guard the writeFileSync call so you only write result.image
when model.unwarp succeeded: check result.success before calling
writeFileSync('/tmp/unwarped_debug.png', result.image) and skip or log an error
when false; use the existing result object (result.success and result.image) and
the writeFileSync call to implement the conditional write and avoid writing
empty/invalid buffers.

In `@scripts/download-model.ts`:
- Around line 143-149: The current download filter in scripts/download-model.ts
checks CORE_FILES and extensions like .pdiparams and .yml but omits .pdmodel and
uses a broad .yml match; update the filter around the file.path check to either
include .pdmodel alongside .pdiparams (if Paddle .pdmodel is required) or add a
clear inline comment next to the conditional/CORE_FILES explaining that .pdmodel
is intentionally excluded because the Rust loader reconstructs topology
internally; also tighten the YAML match to specific names (e.g.,
file.path.endsWith('inference.yml') or matching /^.*(paddle|inference)\.ya?ml$/)
instead of a blanket .yml to avoid downloading unrelated workflows.

Comment thread crates/mlx-core/src/utils/pickle.rs Resolved
Comment thread examples/vlm-inference.ts Resolved
Comment thread scripts/download-model.ts Resolved
@Brooooooklyn
Brooooooklyn force-pushed the feat/doc-preprocessing-pipeline branch from d509831 to e8aa6d3 Compare February 22, 2026 02:32

@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

Caution

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

⚠️ Outside diff range comments (3)
crates/mlx-core/src/models/pp_text_det/processing.rs (1)

198-199: ⚠️ Potential issue | 🟡 Minor

Stale comment references removed process_file method.

Line 198 says (same as process_file) but that method no longer exists — it was renamed to process.

Suggested fix
-        // Channel mapping: RGB->BGR (same as process_file)
+        // Channel mapping: RGB->BGR (same as process)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/pp_text_det/processing.rs` around lines 198 - 199,
The inline comment next to channel_map ([2usize, 1, 0]) incorrectly references
the removed process_file method; update the comment to refer to the current
function name or remove the stale note. Locate the channel_map declaration in
processing.rs (variable name channel_map) and change the comment from "(same as
process_file)" to "(same as process)" or simply "Channel mapping: RGB->BGR" so
it correctly reflects the existing process function.
crates/mlx-core/src/models/paddleocr_vl/model.rs (1)

1729-1734: ⚠️ Potential issue | 🟡 Minor

Stale doc example still references imagePaths.

The load() doc comment at line 1733 still shows { imagePaths: ['./image.jpg'] }, but the API now uses images with Buffer values.

📝 Proposed fix
-    /// const result = model.chat(messages, { imagePaths: ['./image.jpg'] });
+    /// const result = model.chat(messages, { images: [readFileSync('./image.jpg')] });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/paddleocr_vl/model.rs` around lines 1729 - 1734,
Update the stale doc example for VLModel.load / model.chat to use the new images
API instead of imagePaths: replace the object { imagePaths: ['./image.jpg'] }
with the current form using images (e.g., images: [Buffer.from(...)] or images:
[{ data: Buffer, filename?: string }]) so the example matches the API signatures
for VLModel::load and VLModel::chat.
packages/core/index.d.cts (1)

1730-1741: ⚠️ Potential issue | 🟡 Minor

Stale JSDoc examples after API rename.

Two doc examples weren't updated when APIs changed:

  1. Line 1738 (in ocrBatch JSDoc): model.ocrBatch(['page1.jpg', 'page2.jpg', 'page3.jpg']) still shows the old string-path signature; the new signature is ocrBatch(images: Array<Buffer>, ...).
  2. Line 1776 (in VLModel.load JSDoc): model.chat(messages, { imagePaths: ['./image.jpg'] }) still references the old VlmChatConfig.imagePaths field, which was renamed to images: Array<Buffer> (line 3143).

Since this file is auto-generated, the corresponding Rust doc comments need to be updated.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/index.d.cts` around lines 1730 - 1741, Update the stale JSDoc
examples to reflect the renamed API: change the ocrBatch example to call
ocrBatch with an Array<Buffer> (e.g., model.ocrBatch([Buffer.from(...),
Buffer.from(...)])) and update the VLModel.load/chat example to use the new
VlmChatConfig field images: Array<Buffer> instead of imagePaths (e.g.,
model.chat(messages, { images: [Buffer.from(...)] })). Since this file is
generated, make the corresponding fixes in the source Rust doc comments that
generate index.d.cts so the examples show Buffer usage and the images field
consistently (target symbols: ocrBatch, VLModel.load, VlmChatConfig.images).
🧹 Nitpick comments (14)
crates/mlx-core/src/models/pp_text_rec/processing.rs (1)

72-73: Consider into_rgb8() to eagerly drop the DynamicImage.

to_rgb8() borrows img, so the DynamicImage (which may hold a separate decoded buffer) stays alive alongside rgb_img through the call to process_rgb_single. into_rgb8() consumes img immediately and, when the underlying image is already in RGB8 format, avoids an extra copy.

♻️ Proposed change
-        let rgb_img = img.to_rgb8();
-        self.process_rgb_single(&rgb_img, rgb_img.width(), rgb_img.height())
+        let rgb_img = img.into_rgb8();
+        self.process_rgb_single(&rgb_img, rgb_img.width(), rgb_img.height())
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/pp_text_rec/processing.rs` around lines 72 - 73,
Replace the borrow-based conversion img.to_rgb8() with the consuming conversion
img.into_rgb8() so the DynamicImage is dropped immediately and we avoid a
potential extra copy when it's already RGB8; update the call around
process_rgb_single (keep using self.process_rgb_single(&rgb_img,
rgb_img.width(), rgb_img.height())) but ensure img is owned (DynamicImage) at
this call site so into_rgb8() can be called (if img is currently a reference,
adjust the caller to pass ownership or clone only when necessary).
crates/mlx-core/src/utils/pickle.rs (5)

20-43: PickleValue and its accessor methods should also be pub(crate).

Same rationale — these are internal types for the weight conversion pipeline, not N-API exports. Making them pub(crate) keeps the public API surface clean.

Suggested fix
-pub enum PickleValue {
+pub(crate) enum PickleValue {

And for each accessor method:

-    pub fn as_string(&self) -> Option<&str> {
+    pub(crate) fn as_string(&self) -> Option<&str> {

(Apply similarly to as_int, as_bytes, as_tuple, as_list, as_dict, as_object.)

As per coding guidelines, "Use #[napi] procedural macro to export public functions as Native API exports accessible from TypeScript."

Also applies to: 45-99

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/utils/pickle.rs` around lines 20 - 43, Make the
PickleValue enum and its accessor methods internal to the crate by changing
their visibility to pub(crate): update the PickleValue declaration and all
related accessor functions (as_int, as_bytes, as_tuple, as_list, as_dict,
as_object, etc.) to use pub(crate) instead of pub so these types and accessors
remain internal to the weight conversion pipeline and are not exported as N-API
surface.

661-677: long_from_bytes silently truncates integers larger than 8 bytes to i64.

Python's LONG1 can encode arbitrarily large integers (up to 255 bytes). Values requiring >8 bytes will lose high bits. This is fine for typical model metadata (shapes, sizes), but consider logging a warning or returning an error for bytes.len() > 8 to surface unexpected data.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/utils/pickle.rs` around lines 661 - 677, long_from_bytes
currently silently truncates inputs longer than 8 bytes; update long_from_bytes
to detect bytes.len() > 8 and surface that condition (e.g., return a Result or
at minimum log a warning) instead of silently truncating, so callers can handle
unexpected large integers; modify the function signature (or add a companion
function) to return Result<i64, Error> or log via the crate logger when
bytes.len() > 8, include the offending length and optionally the byte slice in
the message, and keep the existing sign-extension logic for lengths <= 8 to
preserve current behavior.

500-508: MEMOIZE key derivation via memo.len() can collide with explicit BINPUT/LONG_BINPUT keys.

If a pickle stream mixes explicit memo keys (via BINPUT/LONG_BINPUT) with auto-incrementing MEMOIZE, the memo.len() key could collide with an existing entry, silently overwriting it. In practice, PyTorch and Paddle use a single memo style per stream, so this is low risk — but worth a note.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/utils/pickle.rs` around lines 500 - 508, The MEMOIZE
(0x94) handler uses memo.len() to pick a key which can collide with explicit
BINPUT/LONG_BINPUT keys; update the MEMOIZE branch (the code handling 0x94 in
crates/mlx-core/src/utils/pickle.rs where memo.insert(key, val.clone()) is
called) to choose a non-colliding key instead of memo.len(): compute the next
unused u32 key (e.g. find max key in memo and use max+1 or loop from 0 upward
until a key is missing) and insert using that key so MEMOIZE never overwrites an
existing explicit memo entry.

200-205: BINBYTES8: u64 as usize length cast could allocate enormous buffers from malformed input.

A malicious or corrupted pickle stream could specify a multi-GB length. While this is used for trusted model files, consider adding a reasonable upper-bound check before allocating.

Suggested defensive check
 0x8e => {
     // BINBYTES8 (8-byte length)
     let len = read_u64(&mut cur)? as usize;
+    let remaining = data.len().saturating_sub(cur.position() as usize);
+    if len > remaining {
+        return Err(Error::from_reason(format!(
+            "pickle BINBYTES8: length {len} exceeds remaining data ({remaining} bytes)"
+        )));
+    }
     let data = read_bytes(&mut cur, len)?;
     stack.push(StackItem::Value(PickleValue::Bytes(data)));
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/utils/pickle.rs` around lines 200 - 205, The BINBYTES8
arm reads a u64 length and casts to usize then allocates via read_bytes, which
can lead to huge allocations from malformed input; after reading len =
read_u64(&mut cur) check it against a reasonable upper bound (e.g. a new
constant MAX_BINBYTES8 or reuse an existing max buffer constant) and return a
parse/error (propagate an Err) if len as usize exceeds that bound before calling
read_bytes and pushing StackItem::Value(PickleValue::Bytes(...))). Ensure the
bound is applied to the value returned by read_u64 and referenced in the
BINBYTES8 match arm that currently calls read_bytes and pushes the StackItem.

317-336: SETITEMS on OrderedDict discards the object and any prior state.

When SETITEMS encounters an OrderedDict Object on top of the stack (lines 323–329), it replaces the entire Object with a plain Dict containing only the new pairs, losing any previously accumulated entries or object metadata. This is intentional simplification for weight dicts, but could silently drop data for more complex OrderedDict usage.

scripts/convert-model.ts (2)

168-194: Consider wrapping convertForeignWeights in a try-catch for consistent error output.

The SafeTensors path (lines 208–235) catches errors and prints a user-friendly message with optional stack trace. The foreign-weight path lets exceptions propagate to the top-level catch (line 238), which only prints the raw error without the verbose stack trace toggle.

Suggested improvement
+    try {
     const result = convertForeignWeights({
       inputPath,
       outputDir,
       modelType,
       verbose,
     });

     const duration = ((Date.now() - startTime) / 1000).toFixed(2);
     console.log(`\n✓ Converted ${result.numTensors} tensors`);
     console.log(`✓ Output directory: ${result.outputPath}`);
     console.log(`✓ Duration: ${duration}s`);
+    } catch (error: any) {
+      console.error('\nConversion failed:', error.message);
+      if (error.stack && verbose) {
+        console.error('\nStack trace:', error.stack);
+      }
+      process.exit(1);
+    }
     return;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@scripts/convert-model.ts` around lines 168 - 194, The foreign-weights
conversion path calls convertForeignWeights(...) without a try-catch, allowing
exceptions to bypass the friendly error handling used elsewhere; wrap the call
to convertForeignWeights (the invocation that assigns to result) in a try-catch,
mirror the SafeTensors error handler by printing a clear "Error converting
foreign weights" message, include error.stack when verbose is true and
error.message otherwise, and call process.exit(1) on failure so
result.numTensors/result.outputPath logging only happens on success.

83-84: Minor: banner box width mismatch.

The header text on line 84 doesn't fill the box to the right border — there are extra trailing spaces but still one character short compared to the bottom border on line 85. This is cosmetic only.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@scripts/convert-model.ts` around lines 83 - 84, The ASCII banner in
scripts/convert-model.ts ("Convert Model Weights to MLX Format") has
one-character inconsistency between the top/bottom border and the text line; fix
by adjusting the banner string so the text line and/or padding matches the box
width (either extend the bottom/top border or add one more trailing space or
change padding around "Convert Model Weights to MLX Format") so the right border
aligns; locate and edit the banner block near the header string in the file to
make the box width consistent.
crates/mlx-core/src/utils/foreign_weights.rs (2)

748-758: Big-endian numpy dtypes silently fall through as unrecognized.

normalize_numpy_dtype only handles little-endian (<f4) and native (f4, float32) numpy dtype strings. Big-endian variants (>f4) or explicit native-endian (=f4) will fall through to the _ => s.to_string() arm, producing an unrecognized dtype string that later causes bytes_to_mxarray to error.

While Apple Silicon (MLX target) is always little-endian, checkpoints created on big-endian or explicitly-annotated systems could contain these prefixes.

♻️ Handle endian-prefix variants
 fn normalize_numpy_dtype(s: &str) -> String {
+    // Strip endianness prefix (< little, > big, = native, | not applicable)
+    let s = s.strip_prefix(['<', '>', '=', '|']).unwrap_or(s);
     match s {
-        "<f4" | "float32" | "f4" => "f32".to_string(),
-        "<f2" | "float16" | "f2" => "f16".to_string(),
-        "<f8" | "float64" | "f8" => "f64".to_string(),
-        "<i4" | "int32" | "i4" => "i32".to_string(),
-        "<i8" | "int64" | "i8" => "i64".to_string(),
-        "<u1" | "uint8" | "u1" => "u8".to_string(),
-        "|b1" | "bool" => "bool".to_string(),
+        "f4" | "float32" => "f32".to_string(),
+        "f2" | "float16" => "f16".to_string(),
+        "f8" | "float64" => "f64".to_string(),
+        "i4" | "int32" => "i32".to_string(),
+        "i8" | "int64" => "i64".to_string(),
+        "u1" | "uint8" => "u8".to_string(),
+        "b1" | "bool" => "bool".to_string(),
         _ => s.to_string(),
     }
 }

Note: if a big-endian dtype is encountered, bytes_to_mxarray will still interpret bytes as little-endian, producing wrong values. Consider erroring explicitly on > prefixes instead.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/utils/foreign_weights.rs` around lines 748 - 758,
normalize_numpy_dtype currently only matches little-endian/native-less prefixes
and lets big-endian (e.g. ">f4") or explicit-native ("=f4") fall through, which
leads to unrecognized dtype strings and later errors in bytes_to_mxarray; update
normalize_numpy_dtype to first strip an optional endianness prefix ('<', '>',
'=') or match variants with those prefixes and map the underlying type to the
correct Rust target type (e.g., map any of "<f4", "=f4", "f4", "float32" to
"f32"); additionally, detect and explicitly error for big-endian ('>') prefixes
instead of silently accepting them so bytes_to_mxarray won’t misinterpret byte
order—use the function normalize_numpy_dtype and the caller bytes_to_mxarray as
the points to change.

219-223: Redundant _metadata check.

Line 221: key == "_metadata" is already covered by key.starts_with("_"). The first condition is dead code.

♻️ Simplify
-        if key == "_metadata" || key.starts_with("_") {
+        if key.starts_with('_') {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/utils/foreign_weights.rs` around lines 219 - 223, The
check for key == "_metadata" is redundant because key.starts_with("_") already
covers that case; update the loop over raw_tensors in foreign_weights.rs to
remove the dead equality check and only use if key.starts_with("_") { continue;
} so internal PyTorch metadata and other underscore-prefixed keys are skipped by
the single condition (locate the for (key, array) in raw_tensors { ... } block
and the if key == "_metadata" || key.starts_with("_") check to modify).
crates/mlx-core/src/models/pp_doc_unwarp/model.rs (1)

342-349: success field is always true in UnwarpResult.

Since errors are propagated via ? before reaching the Ok(UnwarpResult { ... }), the success field will only ever be true. If the intent is to always throw on failure (which is the current behavior), consider whether this field is needed in the NAPI surface, or if it's kept for future soft-failure semantics.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/pp_doc_unwarp/model.rs` around lines 342 - 349,
The UnwarpResult NAPI struct currently has a success: bool that will always be
true because errors are propagated with ? before returning Ok(UnwarpResult { ...
}); update the implementation to either (A) remove the success field from
UnwarpResult (and any code constructing it) if you intend to continue throwing
on failure, or (B) change the unwarp code paths (the function that returns
UnwarpResult) to catch recoverable errors and return Ok(UnwarpResult { image:
..., success: false }) for soft-failure semantics; locate the UnwarpResult
struct and the function(s) that construct/return it and apply one of these two
approaches so the NAPI surface reflects actual behavior.
crates/mlx-core/src/models/pp_doc_unwarp/processing.rs (1)

88-149: Performance note: CPU-bound bilinear sampling over every pixel.

For large document images (e.g., 2000×3000 = 6M pixels), this nested loop with two bilinear interpolations per pixel could be noticeable. This is fine for correctness, but consider parallelizing with rayon or moving to GPU if performance becomes a bottleneck in production.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/pp_doc_unwarp/processing.rs` around lines 88 -
149, The nested oy/ox loops in the bilinear sampling block (inside the loop that
uses sample_coords, interpolates sample[], computes src_x/src_y, and reads from
rgb_img to write to output) are CPU-bound; replace the serial iteration with
parallel iteration (e.g., rayon) over rows or tiles to speed up processing: use
(0..out_h).into_par_iter() (or par_chunks over row indices) and compute each
row's pixels in parallel, writing into a thread-safe buffer (pre-allocated
Vec<u8> or per-row Vec that is later copied into image::RgbImage) to avoid
concurrent writes to output (or use per-row mutable slices/chunks_mut if
available), and keep reads from rgb_img immutable; this keeps the bilinear math
(sample_coords, src_x/src_y, pixel assembly) unchanged while making the outer
loop parallel for better throughput.
crates/mlx-core/src/models/pp_doc_ori/model.rs (1)

165-171: Arc<MxArray> wrapping is redundant.

MxArray already manages shared ownership internally via Arc<MxHandle>. Wrapping it in an outer Arc<MxArray> adds a second layer of reference counting with no benefit — ClassificationHead is exclusively owned by DocOrientationModel with no need for shared ownership at this level.

♻️ Proposed simplification
 pub struct ClassificationHead {
-    /// FC weight [num_classes, in_channels]
-    weight: Arc<MxArray>,
-    /// FC bias [num_classes]
-    bias: Arc<MxArray>,
+    /// FC weight [in_channels, num_classes]
+    weight: MxArray,
+    /// FC bias [num_classes]
+    bias: MxArray,
 }
 
 impl ClassificationHead {
     pub fn new(weight: &MxArray, bias: &MxArray) -> Self {
         Self {
-            weight: Arc::new(weight.clone()),
-            bias: Arc::new(bias.clone()),
+            weight: weight.clone(),
+            bias: bias.clone(),
         }
     }

Then update usages in forward from &self.weight / &self.bias to &self.weight / &self.bias (no change needed there).

Based on learnings: "Handle Arc with thread-safe lifetime management; use Arc for shared ownership across threads" — Arc at the MxArray level is unnecessary since MxArray already encapsulates Arc<MxHandle>.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/pp_doc_ori/model.rs` around lines 165 - 171, The
ClassificationHead currently stores weight and bias as Arc<MxArray>, which is
redundant because MxArray already wraps an Arc<MxHandle>; remove the outer Arc
by changing the ClassificationHead struct fields to MxArray (or &MxArray if
appropriate), update ClassificationHead::new to store cloned MxArray directly
(not Arc::new), and adjust any call sites (e.g., forward method references to
self.weight / self.bias) to use the updated types; ensure ownership/borrowing
semantics compile (clone where needed) and remove unnecessary Arc imports/usages
related to ClassificationHead.
packages/core/index.d.cts (1)

2145-2154: modelType should be a string literal union for type safety.

The valid values are "pp-lcnet-ori" and "uvdoc" (per the comment), but the type is string. Callers get no IDE autocomplete and no compile-time error for invalid values.

If the Rust side uses a #[napi]-annotated enum for model_type, NAPI-RS will generate the appropriate string literal union automatically:

-  /** Model type: "pp-lcnet-ori" or "uvdoc" */
-  modelType: string;
+  /** Model type */
+  modelType: 'pp-lcnet-ori' | 'uvdoc';
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/index.d.cts` around lines 2145 - 2154, The modelType property
on ForeignConversionOptions is declared as a plain string but should be a string
literal union to restrict values to the two valid options; update
ForeignConversionOptions.modelType to the union type "pp-lcnet-ori" | "uvdoc"
(and then update any call sites that pass modelType to use those exact literals
or the generated enum bindings), ensuring ForeignConversionOptions and any
places that construct or read modelType use the new union type for compile-time
safety and IDE autocomplete.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@crates/mlx-core/src/models/pp_doc_ori/model.rs`:
- Around line 258-266: The classify_and_rotate function returns PNG bytes for
rotated images (via processing::rotate) but returns the original input bytes
when angle == 0, causing inconsistent output formats; update classify_and_rotate
so both branches produce PNG: when angle != 0 keep using processing::rotate, and
when angle == 0 decode the input image bytes and re-encode them to PNG (or use
an existing utility like processing::encode_png) so the variable image is always
PNG-encoded before being returned; refer to classify_and_rotate, classify_bytes,
and processing::rotate to locate and change the logic.

In `@crates/mlx-core/src/models/pp_doc_unwarp/persistence.rs`:
- Around line 225-242: The encoder construction loop currently iterates
0..3usize and therefore skips the 4th group in config.block_nums and
config.stride; update the loop to iterate over the actual number of configured
layers (e.g., use config.block_nums.len() or 0..4) and adjust encoder_layers
capacity accordingly so all entries from config.block_nums and config.stride are
consumed when building encoder_layers before calling ResnetEncoder::new;
alternatively, if the 4th entry is intentionally unused, add a clear comment
next to config.block_nums/config.stride and the loop explaining why the last
element is ignored.

In `@crates/mlx-core/src/models/pp_doc_unwarp/processing.rs`:
- Around line 66-71: The function apply_displacement_field lacks validation for
grid_data length which can cause an index OOB in the sample_coords closure; add
an upfront check in apply_displacement_field that verifies grid_data.len() ==
grid_h * grid_w * 2 and return a clear Err (with a descriptive message) if it
does not match, so callers get a surfaced error instead of a panic from
sample_coords.

In `@crates/mlx-core/src/utils/foreign_weights.rs`:
- Around line 896-916: The LoD skip loop can overflow when computing and adding
level_len as usize * 8; replace the unchecked arithmetic in the loop that uses
level_len, offset and data with checked operations: use
level_len.checked_mul(8).and_then(|bytes| bytes.checked_add(offset as u64)) (or
convert safely to usize and use checked_mul/checked_add) and return an Err if
any checked_* returns None or if the computed byte count would go past
data.len(); update the block that reads level_len and the subsequent offset
increment (variables: level_len, offset, data, lod_count) to validate
multiplication and addition before changing offset to prevent overflow or
out-of-bounds reads.
- Around line 580-644: The match arms in extract_storage_info currently silently
return defaults ("f32","0") when heuristics fail; update the PickleValue::Object
and PickleValue::Tuple branches to detect when dtype_str=="f32" and
storage_key=="0" (i.e., fallbacks) and emit a debug-only warning using
#[cfg(debug_assertions)] eprintln! with context (include the tensor name and
which branch: PickleValue::Object or Tuple); keep existing behavior but add this
warning so developers see when the heuristic fallback is used; reference
storage_class_to_dtype, the PickleValue::Object branch, and the
PickleValue::Tuple branch to locate where to insert the debug eprintln! before
the Ok((dtype_str, storage_key)) returns.
- Around line 1050-1066: The read_varint function can overflow when parsing >10
continuation bytes; change read_varint to guard against shift overflow by
enforcing the protobuf max of 10 bytes (or stopping when shift >= 64) and return
a failure instead of allowing a wrap. Concretely: update read_varint's signature
to return Result<u64, DecodeError> (or a suitable error type), track the
byte/count/shift and if you see more than 10 continuation bytes or shift >= 64
return Err(DecodeError::VarintOverflow) rather than performing the left shift;
update callers of read_varint to handle the Result accordingly.

In `@packages/core/index.d.cts`:
- Around line 3109-3115: The UnwarpResult interface's image semantics when
success is false are unclear; update the doc comment for UnwarpResult.image (and
mention UnwarpResult.success) to state the exact fallback contract (e.g., "When
success is false, image will be an empty Buffer" or "will contain the original
input bytes" or "may be a partially processed result") so callers know whether
they can safely use image when success is false; pick the intended behavior
consistent with the implementation, document it explicitly in the comment, and
ensure callers can rely on that documented invariant.
- Around line 2022-2023: convertForeignWeights is currently declared as a
synchronous function and may block the Node.js event loop during heavy file
I/O/deserialization; change its signature to return a Promise by making it async
(export declare function convertForeignWeights(options:
ForeignConversionOptions): Promise<ForeignConversionResult>), update all call
sites to await it (matching convertModel's pattern), and update the Rust
implementation to an async fn that uses spawn_blocking for the blocking work so
the conversion runs off the event loop; adjust any surrounding types/exports to
accept ForeignConversionOptions/ForeignConversionResult as the async return
shape.

---

Outside diff comments:
In `@crates/mlx-core/src/models/paddleocr_vl/model.rs`:
- Around line 1729-1734: Update the stale doc example for VLModel.load /
model.chat to use the new images API instead of imagePaths: replace the object {
imagePaths: ['./image.jpg'] } with the current form using images (e.g., images:
[Buffer.from(...)] or images: [{ data: Buffer, filename?: string }]) so the
example matches the API signatures for VLModel::load and VLModel::chat.

In `@crates/mlx-core/src/models/pp_text_det/processing.rs`:
- Around line 198-199: The inline comment next to channel_map ([2usize, 1, 0])
incorrectly references the removed process_file method; update the comment to
refer to the current function name or remove the stale note. Locate the
channel_map declaration in processing.rs (variable name channel_map) and change
the comment from "(same as process_file)" to "(same as process)" or simply
"Channel mapping: RGB->BGR" so it correctly reflects the existing process
function.

In `@packages/core/index.d.cts`:
- Around line 1730-1741: Update the stale JSDoc examples to reflect the renamed
API: change the ocrBatch example to call ocrBatch with an Array<Buffer> (e.g.,
model.ocrBatch([Buffer.from(...), Buffer.from(...)])) and update the
VLModel.load/chat example to use the new VlmChatConfig field images:
Array<Buffer> instead of imagePaths (e.g., model.chat(messages, { images:
[Buffer.from(...)] })). Since this file is generated, make the corresponding
fixes in the source Rust doc comments that generate index.d.cts so the examples
show Buffer usage and the images field consistently (target symbols: ocrBatch,
VLModel.load, VlmChatConfig.images).

---

Duplicate comments:
In `@crates/mlx-core/src/models/pp_doc_ori/model.rs`:
- Around line 157-159: The doc comment for ClassificationHead::weight is wrong:
the forward pass uses flat.matmul(&self.weight) where flat is [B, C], so weight
must be shaped [in_channels, num_classes], not [num_classes, in_channels];
update the comment on the weight field (and any related struct-level doc) to say
[in_channels, num_classes], and verify the forward method
(ClassificationHead::forward or similar) and any code that constructs or loads
this tensor treat weight as [in_channels, num_classes].
- Around line 286-298: The current code unsafely uses partial_cmp(...).unwrap()
(panics on NaN) and indexes ORIENTATION_LABELS[max_idx] without bounds checks;
change the selection of the max score to handle NaN and empty vectors without
unwraps (e.g., use enumerate().max_by with
partial_cmp(...).unwrap_or(Ordering::Less) or explicitly filter out NaNs and
handle None), and then validate that max_idx < ORIENTATION_LABELS.len() before
indexing; if the vector is empty, all values are NaN, or the index is out of
range, return an Err from the function instead of panicking. Ensure references
to prob_vec, ORIENTATION_LABELS, and OrientationResult are used so the fix is
applied in the correct place.

In `@crates/mlx-core/src/models/pp_doc_unwarp/config.rs`:
- Around line 9-10: The docstring for the config field img_size is misleading:
it says “[width, height]” but the tuple and defaults use (height, width). Update
the doc comment for pub img_size: (u32, u32) in config.rs to accurately describe
the ordering (height, width) or swap the tuple to (width, height) to match the
comment; reference the img_size field to locate the change and make sure any
other code expecting the same ordering (e.g., places constructing or
destructuring img_size) is updated accordingly.

In `@crates/mlx-core/src/models/pp_doclayout_v3/postprocessing.rs`:
- Around line 209-218: The current promotion logic increments el.order by
num_promoted for non-title indices (using elements, title_set, num_promoted)
which can leave non-contiguous gaps; after the existing elements.sort_by_key(|e|
e.order) call, add a renormalization pass that iterates the sorted elements
slice and reassigns element.order = idx (0-based sequential) so orders become
contiguous and preserve relative sort order; locate the block containing
elements.iter_mut().enumerate(), elements.sort_by_key, and perform the
renumbering immediately after the sort.

In `@crates/mlx-core/src/utils/foreign_weights.rs`:
- Around line 168-197: convert_uvdoc currently fails for directory inputs that
contain PyTorch checkpoints because it only checks for inference.pdiparams +
inference.json; update convert_uvdoc to, when input_path.is_dir() is true and
the Paddle files are not present, scan the directory for PyTorch checkpoint
extensions (.pkl, .pt, .pth) and if found call load_pytorch_checkpoint on that
file and then convert_uvdoc_pytorch_keys(raw_tensors, verbose) as the fallback;
keep the existing Paddle branch that uses load_paddle_inference_params and
remap_uvdoc_inference_keys, but add this PyTorch-directory fallback so directory
mode mirrors the PP-LCNet pdparams fallback behavior.

In `@crates/mlx-core/src/utils/pickle.rs`:
- Around line 112-113: The function signature for unpickle is currently pub but
lacks the #[napi] export attribute, so change its visibility to pub(crate) to
keep it internal; locate the pub fn unpickle(...) -> Result<PickleValue>
definition and update it to pub(crate) fn unpickle(...) -> Result<PickleValue>
so it remains usable by internal weight conversion modules but is not exposed as
a JS-native export.

In `@packages/vlm/src/pipeline/structure-v3.ts`:
- Around line 197-204: The code currently calls
this.docOrientation.classify(...) and then
this.docOrientation.classifyAndRotate(...), causing duplicate inference; replace
the two-step flow with a single call to
this.docOrientation.classifyAndRotate(imageBuffer), inspect the returned
rotateResult.angle (or equivalent) and only update imageBuffer =
Buffer.from(rotateResult.image) when the angle indicates rotation is needed,
thereby avoiding a prior classify() call; update references to
oriResult/rotateResult accordingly in the surrounding logic.

---

Nitpick comments:
In `@crates/mlx-core/src/models/pp_doc_ori/model.rs`:
- Around line 165-171: The ClassificationHead currently stores weight and bias
as Arc<MxArray>, which is redundant because MxArray already wraps an
Arc<MxHandle>; remove the outer Arc by changing the ClassificationHead struct
fields to MxArray (or &MxArray if appropriate), update ClassificationHead::new
to store cloned MxArray directly (not Arc::new), and adjust any call sites
(e.g., forward method references to self.weight / self.bias) to use the updated
types; ensure ownership/borrowing semantics compile (clone where needed) and
remove unnecessary Arc imports/usages related to ClassificationHead.

In `@crates/mlx-core/src/models/pp_doc_unwarp/model.rs`:
- Around line 342-349: The UnwarpResult NAPI struct currently has a success:
bool that will always be true because errors are propagated with ? before
returning Ok(UnwarpResult { ... }); update the implementation to either (A)
remove the success field from UnwarpResult (and any code constructing it) if you
intend to continue throwing on failure, or (B) change the unwarp code paths (the
function that returns UnwarpResult) to catch recoverable errors and return
Ok(UnwarpResult { image: ..., success: false }) for soft-failure semantics;
locate the UnwarpResult struct and the function(s) that construct/return it and
apply one of these two approaches so the NAPI surface reflects actual behavior.

In `@crates/mlx-core/src/models/pp_doc_unwarp/processing.rs`:
- Around line 88-149: The nested oy/ox loops in the bilinear sampling block
(inside the loop that uses sample_coords, interpolates sample[], computes
src_x/src_y, and reads from rgb_img to write to output) are CPU-bound; replace
the serial iteration with parallel iteration (e.g., rayon) over rows or tiles to
speed up processing: use (0..out_h).into_par_iter() (or par_chunks over row
indices) and compute each row's pixels in parallel, writing into a thread-safe
buffer (pre-allocated Vec<u8> or per-row Vec that is later copied into
image::RgbImage) to avoid concurrent writes to output (or use per-row mutable
slices/chunks_mut if available), and keep reads from rgb_img immutable; this
keeps the bilinear math (sample_coords, src_x/src_y, pixel assembly) unchanged
while making the outer loop parallel for better throughput.

In `@crates/mlx-core/src/models/pp_text_rec/processing.rs`:
- Around line 72-73: Replace the borrow-based conversion img.to_rgb8() with the
consuming conversion img.into_rgb8() so the DynamicImage is dropped immediately
and we avoid a potential extra copy when it's already RGB8; update the call
around process_rgb_single (keep using self.process_rgb_single(&rgb_img,
rgb_img.width(), rgb_img.height())) but ensure img is owned (DynamicImage) at
this call site so into_rgb8() can be called (if img is currently a reference,
adjust the caller to pass ownership or clone only when necessary).

In `@crates/mlx-core/src/utils/foreign_weights.rs`:
- Around line 748-758: normalize_numpy_dtype currently only matches
little-endian/native-less prefixes and lets big-endian (e.g. ">f4") or
explicit-native ("=f4") fall through, which leads to unrecognized dtype strings
and later errors in bytes_to_mxarray; update normalize_numpy_dtype to first
strip an optional endianness prefix ('<', '>', '=') or match variants with those
prefixes and map the underlying type to the correct Rust target type (e.g., map
any of "<f4", "=f4", "f4", "float32" to "f32"); additionally, detect and
explicitly error for big-endian ('>') prefixes instead of silently accepting
them so bytes_to_mxarray won’t misinterpret byte order—use the function
normalize_numpy_dtype and the caller bytes_to_mxarray as the points to change.
- Around line 219-223: The check for key == "_metadata" is redundant because
key.starts_with("_") already covers that case; update the loop over raw_tensors
in foreign_weights.rs to remove the dead equality check and only use if
key.starts_with("_") { continue; } so internal PyTorch metadata and other
underscore-prefixed keys are skipped by the single condition (locate the for
(key, array) in raw_tensors { ... } block and the if key == "_metadata" ||
key.starts_with("_") check to modify).

In `@crates/mlx-core/src/utils/pickle.rs`:
- Around line 20-43: Make the PickleValue enum and its accessor methods internal
to the crate by changing their visibility to pub(crate): update the PickleValue
declaration and all related accessor functions (as_int, as_bytes, as_tuple,
as_list, as_dict, as_object, etc.) to use pub(crate) instead of pub so these
types and accessors remain internal to the weight conversion pipeline and are
not exported as N-API surface.
- Around line 661-677: long_from_bytes currently silently truncates inputs
longer than 8 bytes; update long_from_bytes to detect bytes.len() > 8 and
surface that condition (e.g., return a Result or at minimum log a warning)
instead of silently truncating, so callers can handle unexpected large integers;
modify the function signature (or add a companion function) to return
Result<i64, Error> or log via the crate logger when bytes.len() > 8, include the
offending length and optionally the byte slice in the message, and keep the
existing sign-extension logic for lengths <= 8 to preserve current behavior.
- Around line 500-508: The MEMOIZE (0x94) handler uses memo.len() to pick a key
which can collide with explicit BINPUT/LONG_BINPUT keys; update the MEMOIZE
branch (the code handling 0x94 in crates/mlx-core/src/utils/pickle.rs where
memo.insert(key, val.clone()) is called) to choose a non-colliding key instead
of memo.len(): compute the next unused u32 key (e.g. find max key in memo and
use max+1 or loop from 0 upward until a key is missing) and insert using that
key so MEMOIZE never overwrites an existing explicit memo entry.
- Around line 200-205: The BINBYTES8 arm reads a u64 length and casts to usize
then allocates via read_bytes, which can lead to huge allocations from malformed
input; after reading len = read_u64(&mut cur) check it against a reasonable
upper bound (e.g. a new constant MAX_BINBYTES8 or reuse an existing max buffer
constant) and return a parse/error (propagate an Err) if len as usize exceeds
that bound before calling read_bytes and pushing
StackItem::Value(PickleValue::Bytes(...))). Ensure the bound is applied to the
value returned by read_u64 and referenced in the BINBYTES8 match arm that
currently calls read_bytes and pushes the StackItem.

In `@packages/core/index.d.cts`:
- Around line 2145-2154: The modelType property on ForeignConversionOptions is
declared as a plain string but should be a string literal union to restrict
values to the two valid options; update ForeignConversionOptions.modelType to
the union type "pp-lcnet-ori" | "uvdoc" (and then update any call sites that
pass modelType to use those exact literals or the generated enum bindings),
ensuring ForeignConversionOptions and any places that construct or read
modelType use the new union type for compile-time safety and IDE autocomplete.

In `@scripts/convert-model.ts`:
- Around line 168-194: The foreign-weights conversion path calls
convertForeignWeights(...) without a try-catch, allowing exceptions to bypass
the friendly error handling used elsewhere; wrap the call to
convertForeignWeights (the invocation that assigns to result) in a try-catch,
mirror the SafeTensors error handler by printing a clear "Error converting
foreign weights" message, include error.stack when verbose is true and
error.message otherwise, and call process.exit(1) on failure so
result.numTensors/result.outputPath logging only happens on success.
- Around line 83-84: The ASCII banner in scripts/convert-model.ts ("Convert
Model Weights to MLX Format") has one-character inconsistency between the
top/bottom border and the text line; fix by adjusting the banner string so the
text line and/or padding matches the box width (either extend the bottom/top
border or add one more trailing space or change padding around "Convert Model
Weights to MLX Format") so the right border aligns; locate and edit the banner
block near the header string in the file to make the box width consistent.

Comment thread packages/core/index.d.cts Resolved
Comment thread packages/core/index.d.cts Resolved
@Brooooooklyn
Brooooooklyn force-pushed the feat/doc-preprocessing-pipeline branch 3 times, most recently from bcbbe33 to fb2f045 Compare February 22, 2026 02:51

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

Caution

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

⚠️ Outside diff range comments (2)
packages/core/index.d.cts (2)

1736-1741: ⚠️ Potential issue | 🟡 Minor

Stale doc example: ocrBatch example passes string paths, but signature now takes Array<Buffer>.

Line 1738 shows model.ocrBatch(['page1.jpg', 'page2.jpg', 'page3.jpg']) but the actual signature at line 1741 is ocrBatch(images: Array<Buffer>, ...). The example should use Buffers.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/index.d.cts` around lines 1736 - 1741, The docs show a stale
example for ocrBatch using string file paths; update the example to pass an
Array<Buffer> matching the signature ocrBatch(images: Array<Buffer>, config?:
VlmChatConfig). Replace the string literals with Buffers (e.g., Buffer.from or
fs.readFileSync examples) so the example demonstrates calling model.ocrBatch
with buffers and an optional config object if needed.

1773-1778: ⚠️ Potential issue | 🟡 Minor

Stale doc example: imagePaths should be images with Buffer values.

The VLModel.load example on line 1776 still references imagePaths: ['./image.jpg'], but VlmChatConfig.images now accepts Array<Buffer> (line 3144). This will confuse consumers of the API documentation.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/index.d.cts` around lines 1773 - 1778, Update the example for
VLModel.load to use the current VlmChatConfig.images field: replace the stale
imagePaths usage with images containing Buffer values; specifically, change the
example invocation of VLModel.load(...).chat(messages, { imagePaths: [...] }) to
use chat(messages, { images: [Buffer.from(...)] }) or an appropriate Buffer
(referencing VLModel.load and VlmChatConfig.images) so the docs match the API
that expects Array<Buffer>.
🧹 Nitpick comments (9)
crates/mlx-core/src/models/pp_doc_ori/processing.rs (1)

54-85: Re-encoding to PNG is lossless but consider the overhead.

rotate always re-encodes as PNG regardless of the original format. This is correct for lossless round-tripping, but PNG encoding of a large photograph can be noticeably slower than, say, passing through raw pixel data. Since the downstream pipeline will decode these bytes again, this is a encode→decode round-trip per orientation correction.

If this becomes a bottleneck in practice, returning raw RGB bytes (or a DynamicImage directly) would avoid the round-trip. Fine for now given the clean API boundary.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/pp_doc_ori/processing.rs` around lines 54 - 85,
The rotate function currently always re-encodes to PNG (ImageFormat::Png) which
can be costly for large photos; to avoid the extra encode→decode round-trip,
change rotate to offer a non-encoded return option (e.g., return a DynamicImage
or raw RGB bytes) or add a parameter to preserve the original format instead of
forcing PNG: update the rotate signature (rotate) to return Result<DynamicImage>
or Result<(Vec<u8>, ImageFormat)> (or add a flag keep_raw: bool) and adjust
callers to handle a DynamicImage or raw pixel buffer, removing the write_to(&mut
Cursor::new(&mut buf), ImageFormat::Png) path when returning unencoded data.
crates/mlx-core/src/models/pp_text_det/model.rs (1)

85-132: New detect_crop method looks correct; consider extracting shared postprocessing.

The forward + decode + postprocess_db sequence is duplicated between detect and detect_crop. This is fine for now, but if a third entry-point is added later, a shared helper like fn postprocess_forward(&self, pixel_values, orig_h, orig_w, resized_h, resized_w, threshold) would reduce the duplication.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/pp_text_det/model.rs` around lines 85 - 132, Both
detect and detect_crop duplicate the forward + decode + postprocess_db sequence;
extract that logic into a shared helper (e.g., fn postprocess_forward(&self,
pixel_values: &[f32], orig_h: u32, orig_w: u32, resized_h: usize, resized_w:
usize, det_threshold: f64) -> Result<Vec<TextBox>>) that runs self.forward(...),
retrieves the prob_map shape, calls eval(), converts to float32 and to_vec(),
then calls postprocess_db and returns Vec<TextBox>; replace the duplicated
sequence in detect and detect_crop to call this new helper (keep existing calls
to image_processor.process / process_crop outside the helper so only the
forward+postprocess is shared).
__test__/models/doc-preprocess.test.ts (1)

14-25: Consider using top-level ESM imports instead of inline require().

The file uses ESM import at the top (line 1–3) but falls back to require('node:os') etc. inside test bodies. Using consistent ESM imports at the top is cleaner and avoids mixing module systems.

Proposed fix
 import { describe, it, expect } from 'vite-plus/test';
-import { DocOrientationModel, DocUnwarpModel } from '@mlx-node/core';
+import { DocOrientationModel, DocUnwarpModel } from '@mlx-node/vlm';
 import type { StructureV3Config, AnalyzeOptions } from '@mlx-node/vlm';
+import os from 'node:os';
+import fs from 'node:fs';
+import path from 'node:path';

Then replace the inline require calls in both test bodies (lines 16–19, 38–41) with:

-    const os = require('node:os');
-    const fs = require('node:fs');
-    const path = require('node:path');
-    const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'doc-ori-test-'));
+    const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'doc-ori-test-'));

Also applies to: 37-47

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@__test__/models/doc-preprocess.test.ts` around lines 14 - 25, Replace the
inline CommonJS requires in the test (node:os, node:fs, node:path) with
top-level ESM imports and use those imports inside the test bodies; update
__test__/models/doc-preprocess.test.ts to add imports for os, fs, and path at
the top of the file and remove the inline require(...) calls used around
DocOrientationModel.load in the tests so the test uses the same ESM module style
as the rest of the file.
crates/mlx-core/src/models/pp_doc_unwarp/processing.rs (1)

102-163: Per-pixel bilinear unwarp is correct but may be a bottleneck for large images.

The nested loop is O(img_h × img_w) with no vectorization or parallelism. For a typical document image (e.g., 2000×3000), this is ~6M iterations with multiple floating-point ops each. If latency becomes an issue, consider using rayon for row-parallel processing — the rows are independent.

This is not blocking, just a heads-up for production workloads.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/pp_doc_unwarp/processing.rs` around lines 102 -
163, The per-pixel nested loops over oy/ox (the bilinear unwarp loop using
grid_data, rgb_img and writing to output) are serial and will be a bottleneck
for large images; make the outer loop parallel (e.g., parallelize over rows/oy)
using rayon by iterating rows with par_iter or par_chunks_mut and computing each
row independently, ensuring grid_data and rgb_img remain shared read-only and
that you obtain a thread-local mutable slice/view of output (or use
output.buffer_mut()/enumerate_rows_mut equivalents) so writes don't race; keep
the same interpolation logic (gx_f/gx0/fx, sample_coords, src_x/src_y, bilinear
sampling) but run each row in parallel and preserve deterministic ordering when
needed.
crates/mlx-core/src/utils/mod.rs (1)

9-17: pickle module is not re-exported like other utility submodules.

foreign_weights, functional, and safetensors all include pub use *; re-exports, but pickle does not. For consistency, either add pub use pickle::*; to expose PickleValue at the utils level, or make it pub(crate) mod pickle; to reflect its internal-only status. Note that unpickle is already pub(crate), so only PickleValue and its methods would be re-exported.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/utils/mod.rs` around lines 9 - 17, The utils module
currently re-exports foreign_weights, functional, and safetensors but not
pickle, so PickleValue is not visible at the utils level; either add a re-export
or mark the module as crate-private. Fix by updating the module declaration for
pickle: either change to "pub use pickle::*;" alongside the other pub uses to
expose PickleValue and its methods at the utils level, or change "pub mod
pickle;" to "pub(crate) mod pickle;" to explicitly keep unpickle and PickleValue
internal; reference the module name "pickle", the type "PickleValue", and the
function "unpickle" when making the change.
packages/vlm/src/pipeline/structure-v3.ts (2)

336-348: Dynamic import('@napi-rs/image') is called on every multi-line OCR invocation.

await import('@napi-rs/image') is called inside ocrRegion (line 336) and cropElement (line 369) on every call. While Node.js caches dynamic imports after the first resolution, the repeated await still adds a microtask hop per invocation. For a document with many layout elements (each calling cropElement + potentially ocrRegion with multiple lines), this adds up.

Consider hoisting the import to module scope or caching it in a class field after first use.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/vlm/src/pipeline/structure-v3.ts` around lines 336 - 348, The
dynamic import of '@napi-rs/image' inside ocrRegion and cropElement adds an
unnecessary await/microtask hop on each call; hoist or cache the module so
Transformer is loaded once: create a module-scoped or class-scoped variable
(e.g., let ImageTransformerModule or cachedTransformer) and on first use assign
it via await import('@napi-rs/image'), then replace the inline await import(...)
usages in ocrRegion and cropElement with the cached module and use its
Transformer; ensure subsequent calls use the cached reference.

219-279: table and TEXT_LABELS branches are identical — consider consolidating.

Lines 228-242 and 243-256 perform the exact same operations (crop → OCR → join with \n). This is minor since the comment says full table parsing is deferred to Phase 4, but a small consolidation would reduce duplication now.

♻️ Consolidate duplicated branches
-      if (TEXT_LABELS.has(label)) {
-        // OCR path: detect text lines then recognize
-        const cropBuffer = await this.cropElement(imageBuffer, el);
-        const textLines = await this.ocrRegion(cropBuffer, textDetThreshold);
-
-        const fullText = textLines.map((l) => l.text).join('\n');
-
-        elements.push({
-          label,
-          score: el.score,
-          bbox: el.bbox,
-          order: el.order,
-          text: fullText,
-          lines: includeDetails ? textLines : undefined,
-        });
-      } else if (label === 'table') {
-        // Table: detect text lines in each cell (simplified - full table parsing in Phase 4)
-        const cropBuffer = await this.cropElement(imageBuffer, el);
-        const textLines = await this.ocrRegion(cropBuffer, textDetThreshold);
-        const fullText = textLines.map((l) => l.text).join('\n');
-
-        elements.push({
-          label,
-          score: el.score,
-          bbox: el.bbox,
-          order: el.order,
-          text: fullText,
-          lines: includeDetails ? textLines : undefined,
-        });
-      } else if (label === 'isolate_formula') {
+      if (TEXT_LABELS.has(label) || label === 'table') {
+        // OCR path: detect text lines then recognize
+        // (table: simplified, full table parsing in Phase 4)
+        const cropBuffer = await this.cropElement(imageBuffer, el);
+        const textLines = await this.ocrRegion(cropBuffer, textDetThreshold);
+        const fullText = textLines.map((l) => l.text).join('\n');
+
+        elements.push({
+          label,
+          score: el.score,
+          bbox: el.bbox,
+          order: el.order,
+          text: fullText,
+          lines: includeDetails ? textLines : undefined,
+        });
+      } else if (label === 'isolate_formula') {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/vlm/src/pipeline/structure-v3.ts` around lines 219 - 279, The table
branch duplicates the TEXT_LABELS OCR flow; update the loop in the method that
iterates layoutElements so 'table' is handled by the same OCR path to remove
duplication: treat label 'table' as a text-like label (either add 'table' to
TEXT_LABELS or merge the else-if that checks label === 'table' into the
TEXT_LABELS branch), reuse the existing calls cropElement and ocrRegion and the
same elements.push shape (including includeDetails behavior), and remove the
separate table-specific block to keep a single code path using cropElement,
ocrRegion, fullText join, and elements.push.
crates/mlx-core/src/models/pp_doc_unwarp/model.rs (2)

240-276: reflect_pad_2d assumes pad < H-1 and pad < W-1 — no bounds guard.

If the input spatial dimension is smaller than pad + 1, the range (1..=pad) will attempt to slice indices beyond the tensor extent (e.g., slice_axis(1, pad, pad+1) where pad >= H), causing a runtime error. Similarly, the bottom/right ranges assume at least pad + 2 elements along each axis.

Given this is an internal function called only from OutputHead::forward with a known architecture (kernel-size-derived pad on a fixed-resolution pipeline), the risk is low in practice. Consider adding a debug assertion for clarity.

🛡️ Optional: add debug assertions
     fn reflect_pad_2d(input: &MxArray, pad: i64) -> Result<MxArray> {
         if pad == 0 {
             return Ok(input.clone());
         }
+        let h = input.shape_at(1)?;
+        let w = input.shape_at(2)?;
+        debug_assert!(pad < h - 1, "reflect pad {pad} requires H >= {}", pad + 2);
+        debug_assert!(pad < w - 1, "reflect pad {pad} requires W >= {}", pad + 2);

         // Pad height (axis 1)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/pp_doc_unwarp/model.rs` around lines 240 - 276,
reflect_pad_2d currently assumes pad < H-1 and pad < W-1 which can panic when
input spatial dims are too small; update reflect_pad_2d to read the spatial
sizes (h = input.shape_at(1)?, w = input.shape_at(2)?) before building slices
and add guards — e.g., a debug_assert! or early Err return that pad >= 0 and pad
< h - 1 and pad < w - 1 (with a clear message referencing pad/h/w) so the
function fails fast and clearly instead of slicing out-of-bounds; keep the
existing pad==0 fast-path and reference reflect_pad_2d (and callers like
OutputHead::forward) when adding the check.

369-391: unwarp is synchronous — heavy image decode + forward pass + displacement on the main thread.

The unwarp method performs image decoding, a full CNN forward pass, and pixel-level displacement field application, all synchronously on the calling thread. When invoked from Node.js, this blocks the event loop. The orientation model's classify_and_rotate has the same pattern, so this may be an intentional project convention for now, but worth flagging for awareness given the heavier workload of unwarping (encoder-decoder CNN + image remap).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/mlx-core/src/models/pp_doc_unwarp/model.rs` around lines 369 - 391,
The unwarp method currently runs heavy CPU work (processing::preprocess,
self.net.forward, processing::apply_displacement_field) synchronously on the
caller thread which will block callers (e.g., Node.js event loop); convert this
to run off the main thread: change unwarp to an async API and move the blocking
work into a blocking task (e.g., tokio::task::spawn_blocking or a Rayon/worker
thread) so the forward pass and image remap run in the worker thread and return
the UnwarpResult to the caller; ensure any captured state (self.net, image_data)
is Send + 'static or cloned appropriately and preserve return type semantics
(Result<UnwarpResult>) so callers can await the operation.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@crates/mlx-core/Cargo.toml`:
- Line 33: Update the workspace-level zip dependency entry (the `zip = {
workspace = true }` declaration) to require version 2.3.0 or newer by changing
its version constraint to something like `>=2.3.0` in the root Cargo.toml so the
workspace uses zip 2.3.0+ (this addresses CVE-2025-29787); locate the `zip`
dependency line in the root Cargo.toml and replace the current loose "2" range
with a `>=2.3.0` constraint while keeping the workspace = true setting.

In `@crates/mlx-core/src/models/pp_doc_ori/processing.rs`:
- Around line 87-92: The function correction_angle currently does unchecked
subtraction and will underflow in debug builds when detected_angle > 360; update
correction_angle to normalize detected_angle first (e.g., detected_angle % 360)
or use wrapping_sub on the normalized value, then compute (360 - normalized) %
360 so the math cannot underflow; change the body of correction_angle to
normalize the input before performing the subtraction to ensure safe, defensive
arithmetic.

In `@crates/mlx-core/src/models/pp_doc_unwarp/model.rs`:
- Around line 342-347: The TypeScript declaration for UnwarpResult is out of
sync with the Rust struct UnwarpResult (which currently only has pub image:
Buffer) causing a missing success boolean at runtime; fix by either adding pub
success: bool to the Rust struct UnwarpResult (and update any
constructors/return sites like the function that builds/returns UnwarpResult) or
regenerate the TypeScript/JS bindings so the emitted index.d.ts/cts matches the
current Rust definition (ensure the code that returns UnwarpResult only exposes
the fields declared in the Rust struct).

In `@crates/mlx-core/src/utils/pickle.rs`:
- Around line 152-160: The LONG1 handler (the 0x8a match arm) must reject
lengths > 8 before calling long_from_bytes to avoid shifting by >=64 bits in
long_from_bytes; add a guard after reading n (from read_u8) that returns an
error (e.g., Error::from_reason with a descriptive message) when n > 8, and only
proceed to read buf and call long_from_bytes when n <= 8 so long_from_bytes
never receives an oversized slice.

In `@examples/vlm-inference.ts`:
- Around line 41-46: The four module-level path constants (vlmModelPath,
layoutModelPath, orientModelPath, unwarpModelPath) violate the UPPER_SNAKE_CASE
convention; rename them to VLM_MODEL_PATH, LAYOUT_MODEL_PATH, ORIENT_MODEL_PATH,
UNWARP_MODEL_PATH and update every reference in this file (and any
imports/exports) to use the new names so compilation and runtime behavior remain
unchanged.

---

Outside diff comments:
In `@packages/core/index.d.cts`:
- Around line 1736-1741: The docs show a stale example for ocrBatch using string
file paths; update the example to pass an Array<Buffer> matching the signature
ocrBatch(images: Array<Buffer>, config?: VlmChatConfig). Replace the string
literals with Buffers (e.g., Buffer.from or fs.readFileSync examples) so the
example demonstrates calling model.ocrBatch with buffers and an optional config
object if needed.
- Around line 1773-1778: Update the example for VLModel.load to use the current
VlmChatConfig.images field: replace the stale imagePaths usage with images
containing Buffer values; specifically, change the example invocation of
VLModel.load(...).chat(messages, { imagePaths: [...] }) to use chat(messages, {
images: [Buffer.from(...)] }) or an appropriate Buffer (referencing VLModel.load
and VlmChatConfig.images) so the docs match the API that expects Array<Buffer>.

---

Duplicate comments:
In `@crates/mlx-core/src/models/pp_doc_ori/model.rs`:
- Around line 157-163: The struct doc for ClassificationHead is incorrect:
update the doc comment for the field `weight` in struct `ClassificationHead` to
state the shape is `[in_channels, num_classes]` (Paddle convention
`[in_features, out_features]`) so it matches the `forward` logic where
`flat.matmul(&self.weight)` (with `flat` shape `[B, C]`) yields `[B,
num_classes]`; ensure only the comment for `weight` is changed and no code logic
is modified.
- Around line 258-266: classify_and_rotate currently returns PNG-encoded bytes
when rotation occurs (processing::rotate) but returns the raw input bytes when
angle == 0, causing inconsistent output formats; update classify_and_rotate so
both branches produce the same PNG-encoded output (for example, when
result.angle == 0 decode/normalize the input and re-encode to PNG via the
existing processing encode helper or a new processing::encode_png function) so
callers like DocUnwarpModel.unwarp() always receive PNG data; keep using
processing::correction_angle and processing::rotate for the rotated case and
ensure the non-rotated branch calls the same PNG-encoding helper before
returning.

In `@crates/mlx-core/src/models/pp_doc_unwarp/config.rs`:
- Around line 9-10: The doc comment for the struct field img_size is wrong: it
currently says "(width, height)" but the default value (488, 712) and NHWC usage
in mod.rs mean the tuple is actually (height, width). Update the doc comment for
pub img_size: (u32, u32) to "(height, width)" (or explicitly document which
element is which) and audit any code that reads img_size (.0 vs .1) to ensure
the documented ordering matches the implemented ordering (e.g., where NHWC [1,
488, 712, 3] is formed).

In `@crates/mlx-core/src/models/pp_doc_unwarp/persistence.rs`:
- Around line 225-242: The encoder construction loop currently iterates only
0..3 and therefore builds three ResLayer groups while config.block_nums and
config.stride contain four entries; update the loop in persistence.rs that fills
encoder_layers (the for layer_idx in ... block that calls load_residual_block
and ResLayer::new) to iterate over all configured groups (e.g., use
config.block_nums.len() or 0..4) so the fourth layer group is created and passed
into ResnetEncoder::new; ensure any indexing (layer_prefix, stride, block_count)
uses layer_idx consistently and that bounds match the config arrays.

In `@crates/mlx-core/src/models/pp_doc_unwarp/processing.rs`:
- Around line 82-94: The length check for grid_data in the block that computes
expected_len = grid_h * grid_w * 2 currently uses `<` and thus allows oversized
input; change the conditional to `!=` so the function returns Err when
grid_data.len() does not exactly equal expected_len. Update the error message if
needed to reflect equality instead of only "<", and keep the same
Error::new(Status::GenericFailure, ...) construction; the affected code is the
grid length validation around expected_len, grid_data.len(), grid_h and grid_w
in processing.rs.

In `@crates/mlx-core/src/utils/foreign_weights.rs`:
- Around line 913-933: In the LoD skipping loop in foreign_weights.rs (the loop
referencing lod_count, offset, level_len and data) replace the unchecked
arithmetic with checked ops: after reading level_len, compute the byte count
with level_len.checked_mul(8) and convert to usize safely, then use
offset.checked_add(8).and_then(|o| o.checked_add(byte_count)) (or equivalent) to
ensure neither the multiplication nor the offset addition overflows and that the
final offset <= data.len(); on any overflow or out-of-bounds condition return
Err(Error::from_reason("Unexpected EOF reading lod level".to_string())) as
before so crafted inputs cannot cause integer overflow or out-of-bounds access.
- Around line 1066-1080: The read_varint function can overflow shift if
malformed data has too many continuation bytes; change read_varint to validate
and error out instead of overflowing: update its signature to return Result<u64,
E> (e.g., Result<u64, ForeignWeightsError> or a new VarintError), and inside the
loop guard against excessive shifts/iterations (fail when shift >= 64 or after
>10 continuation bytes), returning an explicit error when the varint is
malformed or truncated; update all callers of read_varint to propagate the
Result accordingly.
- Around line 574-583: The arithmetic is unchecked and can overflow; fix by
using checked arithmetic and explicit errors: when computing byte_offset and
byte_len replace direct multiplications with checked_mul on storage_offset and
num_elements by elem_size and use checked_add to compute
byte_offset.checked_add(byte_len) to ensure no overflow before comparing to
data.len(), returning an Err with a clear message if any checked_* returns None;
in the LoD parsing where you do offset += level_len as usize * 8 use
level_len.checked_mul(8).and_then(|mul| offset.checked_add(mul)) and return an
error on overflow; in read_varint ensure the shift never exceeds 63 (e.g., if
shift >= 64 return an Err) or otherwise validate varint length to prevent
unbounded left shifts—reference the variables/storage_offset, num_elements,
elem_size, data.len(), offset, level_len, and the read_varint/shift logic when
making these changes.

In `@packages/core/index.d.cts`:
- Line 2022: convertForeignWeights is currently synchronous and can block the
event loop for large weight files; make it asynchronous by changing
convertForeignWeights to return Promise<ForeignConversionResult>, switch all
internal file I/O and weight deserialization in convertForeignWeights to
non-blocking async APIs (e.g., fs.promises or stream-based parsers), update any
callers (notably convertModel) to await the new async function, and update the
exported declaration to export declare function convertForeignWeights(options:
ForeignConversionOptions): Promise<ForeignConversionResult>; ensure error paths
still reject the Promise with meaningful errors.

---

Nitpick comments:
In `@__test__/models/doc-preprocess.test.ts`:
- Around line 14-25: Replace the inline CommonJS requires in the test (node:os,
node:fs, node:path) with top-level ESM imports and use those imports inside the
test bodies; update __test__/models/doc-preprocess.test.ts to add imports for
os, fs, and path at the top of the file and remove the inline require(...) calls
used around DocOrientationModel.load in the tests so the test uses the same ESM
module style as the rest of the file.

In `@crates/mlx-core/src/models/pp_doc_ori/processing.rs`:
- Around line 54-85: The rotate function currently always re-encodes to PNG
(ImageFormat::Png) which can be costly for large photos; to avoid the extra
encode→decode round-trip, change rotate to offer a non-encoded return option
(e.g., return a DynamicImage or raw RGB bytes) or add a parameter to preserve
the original format instead of forcing PNG: update the rotate signature (rotate)
to return Result<DynamicImage> or Result<(Vec<u8>, ImageFormat)> (or add a flag
keep_raw: bool) and adjust callers to handle a DynamicImage or raw pixel buffer,
removing the write_to(&mut Cursor::new(&mut buf), ImageFormat::Png) path when
returning unencoded data.

In `@crates/mlx-core/src/models/pp_doc_unwarp/model.rs`:
- Around line 240-276: reflect_pad_2d currently assumes pad < H-1 and pad < W-1
which can panic when input spatial dims are too small; update reflect_pad_2d to
read the spatial sizes (h = input.shape_at(1)?, w = input.shape_at(2)?) before
building slices and add guards — e.g., a debug_assert! or early Err return that
pad >= 0 and pad < h - 1 and pad < w - 1 (with a clear message referencing
pad/h/w) so the function fails fast and clearly instead of slicing
out-of-bounds; keep the existing pad==0 fast-path and reference reflect_pad_2d
(and callers like OutputHead::forward) when adding the check.
- Around line 369-391: The unwarp method currently runs heavy CPU work
(processing::preprocess, self.net.forward, processing::apply_displacement_field)
synchronously on the caller thread which will block callers (e.g., Node.js event
loop); convert this to run off the main thread: change unwarp to an async API
and move the blocking work into a blocking task (e.g.,
tokio::task::spawn_blocking or a Rayon/worker thread) so the forward pass and
image remap run in the worker thread and return the UnwarpResult to the caller;
ensure any captured state (self.net, image_data) is Send + 'static or cloned
appropriately and preserve return type semantics (Result<UnwarpResult>) so
callers can await the operation.

In `@crates/mlx-core/src/models/pp_doc_unwarp/processing.rs`:
- Around line 102-163: The per-pixel nested loops over oy/ox (the bilinear
unwarp loop using grid_data, rgb_img and writing to output) are serial and will
be a bottleneck for large images; make the outer loop parallel (e.g.,
parallelize over rows/oy) using rayon by iterating rows with par_iter or
par_chunks_mut and computing each row independently, ensuring grid_data and
rgb_img remain shared read-only and that you obtain a thread-local mutable
slice/view of output (or use output.buffer_mut()/enumerate_rows_mut equivalents)
so writes don't race; keep the same interpolation logic (gx_f/gx0/fx,
sample_coords, src_x/src_y, bilinear sampling) but run each row in parallel and
preserve deterministic ordering when needed.

In `@crates/mlx-core/src/models/pp_text_det/model.rs`:
- Around line 85-132: Both detect and detect_crop duplicate the forward + decode
+ postprocess_db sequence; extract that logic into a shared helper (e.g., fn
postprocess_forward(&self, pixel_values: &[f32], orig_h: u32, orig_w: u32,
resized_h: usize, resized_w: usize, det_threshold: f64) -> Result<Vec<TextBox>>)
that runs self.forward(...), retrieves the prob_map shape, calls eval(),
converts to float32 and to_vec(), then calls postprocess_db and returns
Vec<TextBox>; replace the duplicated sequence in detect and detect_crop to call
this new helper (keep existing calls to image_processor.process / process_crop
outside the helper so only the forward+postprocess is shared).

In `@crates/mlx-core/src/utils/mod.rs`:
- Around line 9-17: The utils module currently re-exports foreign_weights,
functional, and safetensors but not pickle, so PickleValue is not visible at the
utils level; either add a re-export or mark the module as crate-private. Fix by
updating the module declaration for pickle: either change to "pub use
pickle::*;" alongside the other pub uses to expose PickleValue and its methods
at the utils level, or change "pub mod pickle;" to "pub(crate) mod pickle;" to
explicitly keep unpickle and PickleValue internal; reference the module name
"pickle", the type "PickleValue", and the function "unpickle" when making the
change.

In `@packages/vlm/src/pipeline/structure-v3.ts`:
- Around line 336-348: The dynamic import of '@napi-rs/image' inside ocrRegion
and cropElement adds an unnecessary await/microtask hop on each call; hoist or
cache the module so Transformer is loaded once: create a module-scoped or
class-scoped variable (e.g., let ImageTransformerModule or cachedTransformer)
and on first use assign it via await import('@napi-rs/image'), then replace the
inline await import(...) usages in ocrRegion and cropElement with the cached
module and use its Transformer; ensure subsequent calls use the cached
reference.
- Around line 219-279: The table branch duplicates the TEXT_LABELS OCR flow;
update the loop in the method that iterates layoutElements so 'table' is handled
by the same OCR path to remove duplication: treat label 'table' as a text-like
label (either add 'table' to TEXT_LABELS or merge the else-if that checks label
=== 'table' into the TEXT_LABELS branch), reuse the existing calls cropElement
and ocrRegion and the same elements.push shape (including includeDetails
behavior), and remove the separate table-specific block to keep a single code
path using cropElement, ocrRegion, fullText join, and elements.push.

Comment thread crates/mlx-core/Cargo.toml Resolved
Comment thread crates/mlx-core/src/utils/pickle.rs Resolved
Comment thread examples/vlm-inference.ts Resolved
@Brooooooklyn
Brooooooklyn force-pushed the feat/doc-preprocessing-pipeline branch from fb2f045 to 05caae3 Compare February 22, 2026 02:53
…efactor image APIs to in-memory buffers

- Add PP-LCNet doc orientation model (0/90/180/270° classification + rotation)
- Add UVDoc document unwarping model with reflect padding fix for correct
  displacement field output (matches original PyTorch reference within 0.001)
- Add PyTorch .pkl checkpoint loader (pickle parser + weight conversion)
- Refactor all image model APIs from file paths to in-memory Buffer/&[u8],
  eliminating temp file I/O throughout the OCR pipeline
- Fix reading order: promote doc_title elements at top of page to front
  when the pairwise order model misranks them in multi-column layouts
- Update StructureV3Pipeline and vlm-inference.ts to pass buffers through
  the full chain: orient → unwarp → layout → crop → OCR

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@Brooooooklyn
Brooooooklyn force-pushed the feat/doc-preprocessing-pipeline branch from 05caae3 to 8329fe9 Compare February 22, 2026 02:59

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

Comment thread crates/mlx-core/index.d.cts Resolved
@Brooooooklyn
Brooooooklyn merged commit 4610287 into main Feb 22, 2026
6 checks passed
@Brooooooklyn
Brooooooklyn deleted the feat/doc-preprocessing-pipeline branch February 22, 2026 03:36
Brooooooklyn added a commit that referenced this pull request Apr 11, 2026
…efactor image APIs to in-memory buffers (#20)

- Add PP-LCNet doc orientation model (0/90/180/270° classification +
rotation)
- Add UVDoc document unwarping model with reflect padding fix for
correct displacement field output (matches original PyTorch reference
within 0.001)
- Add PyTorch .pkl checkpoint loader (pickle parser + weight conversion)
- Refactor all image model APIs from file paths to in-memory
Buffer/&[u8], eliminating temp file I/O throughout the OCR pipeline
- Fix reading order: promote doc_title elements at top of page to front
when the pairwise order model misranks them in multi-column layouts
- Update StructureV3Pipeline and vlm-inference.ts to pass buffers
through the full chain: orient → unwarp → layout → crop → OCR

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches core NAPI surface area and changes image I/O semantics from
paths to in-memory buffers, which can break downstream callers and alter
runtime behavior across the OCR pipeline.
> 
> **Overview**
> Adds two new NAPI-exposed preprocessing models, `DocOrientationModel`
(classify + optional rotate) and `DocUnwarpModel` (unwarp), and exports
new result types (`OrientationResult`, `ClassifyRotateResult`,
`UnwarpResult`) plus a `convertForeignWeights` API for importing
non-SafeTensors checkpoints.
> 
> Refactors the OCR/VLM and related document model APIs to take encoded
image `Buffer`s instead of file paths (including `VlmChatConfig`, `ocr`,
`ocrBatch`, and batch items), wiring image processing through
`process_many` and updating the generated JS/TS bindings and exports
accordingly. Adds `zip` as a workspace dependency and introduces a small
TS test suite to validate preprocessing model loading errors and
type-level integration for preprocessing config/options.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
8329fe9. 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**
* Doc orientation (classify & auto-rotate) and document unwarp models
exposed to JS; weight-conversion tool to import pretrained models.
* Image APIs now accept encoded image buffers (replacing file-path
inputs); pipeline supports optional orient/unwarp preprocessing and new
CLI flags.
* Updated examples demonstrating unwarp, buffer-based workflows, and
preprocessing options.

* **Bug Fixes**
  * Improved reading-order handling for document title elements.

* **Tests**
* Added tests for document preprocessing models and pipeline
integration.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Opus 4.6 <[email protected]>
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