Repository navigation
feat(models): add Falcon-OCR (falcon_ocr) early-fusion VLM support - #1075
Conversation
Adds native support for Falcon-OCR (`model_type: falcon_ocr`, ~300M), TII's early-fusion document-OCR VLM. It is the first VLM in the tree with no vision tower at all: each 16x16 RGB patch is flattened and pushed through a single linear `img_projector` straight into the token stream, and one 22-layer decoder reads image and text together under a hybrid mask that is bidirectional inside every image block and causal everywhere else. The checkpoint ships its own vendor implementation (`modeling_falcon_ocr.py`, `rope.py`, `attention.py`, `processing_falcon_ocr.py`), and that is what this port follows; mlx-vlm's `falcon_ocr` module was used as a cross-check and agrees everywhere it overlaps. ## Decoder Llama-derived with five differences, all visible in the shipped weights: - Fused `wqkv`, split `q | k | v` on the last axis. - Weightless RMSNorm everywhere except the final `norm`. The issue expected per-head Q/K RMSNorm weights, and the checkpoint ships exactly five tensors per layer with no `attention_norm`, `ffn_norm`, `q_norm` or `k_norm`. The reference resolves this: every pre-norm, including the per-head Q and K norms, is `F.rms_norm(x, (dim,))` with no learnable weight. The norms are not missing, they are non-parametric, and they run through `fast_rms_norm_no_weight`. PyTorch resolves their `eps=None` to `torch.finfo(float32).eps`, so the constant is `f32::EPSILON` rather than the config's `norm_eps`, which applies only to the single parametric norm before the LM head. - Per-head learned attention sinks, fed to MLX's sink-aware SDPA (the same entry point gpt-oss uses). - Squared-ReLU gated MLP over a row-interleaved fused `w13`, de-interleaved at load. - A 3-D rotary: a 1-D temporal rotary on the low half of each head and a 2-D per-head spatial rotary on the high half, driven by the checkpoint's own `freqs_cis_golden` table. Both halves use the interleaved pair convention, not half-split. K and V are expanded to `n_heads` before the rotary rather than after, because the spatial rotary has per-head frequencies and each repeated copy must receive its own rotation; the KV cache therefore holds `n_heads` heads. An entire image block collapses onto one temporal position, so the decode step adds a negative, image-size-dependent delta to the cache offset to recover the absolute position. That state is written by the image stage and consumed by prefill and every decode step, which makes its lifecycle the interesting part: `reset_runtime_state` is deliberately not overridden, because the generate loop calls it after the image stage has written the state and before prefill consumes it. Staleness is instead handled at the prefill boundary, where a prompt length that does not match the stashed positions evicts the entry so an image turn cannot shift the positions of a following text-only turn. `supports_chunked_prefill` returns false, matching upstream's `no_chunked_prefill`: `chunked_prefill_last_logits` re-enters `forward` with `mask = None` and a slice of the tokens, which would drop the bidirectional image block and misalign every position after the first chunk. Padded prefill is off for the same reason. ## Prompt and preprocessing Image blocks are prepended (or substituted for an existing `<|image|>` placeholder) and `<|OCR_PLAIN|>` is appended when the prompt does not already end with it. The task token is load-bearing rather than decoration: without it the model narrates the page instead of transcribing it, confirmed against the reference on a rendered document. `<|end_of_query|>` joins the stop set, matching the reference's `[eos_id, <|end_of_query|>]`, so the decode stops on the marker instead of printing it. Preprocessing mirrors the two back-to-back resize stages of `processing_falcon_ocr.py` and skips a resize whose target equals the source, the way PIL does, so an already patch-aligned document reaches the model bit-identical to the reference. `smart_resize` uses banker's rounding because Python's `round` does, and the two rules disagree at every `height % 16 == 8`, which would change the image-token budget. ## Layout stage `src/vision/falcon_ocr_layout.rs` ports the layout-aware second stage from `layout.py`: category routing, nested-box suppression, region cropping, and the per-category instructions. It is expressed over `vision::detection::Detection`, the shape mlxcel's existing RT-DETR-family detector already produces. The PP-DocLayoutV3 detector that feeds it upstream is a separate object-detection architecture and is not included. ## Validation GB10, CUDA (sm_121), release build, real `tiiuae/Falcon-OCR` checkpoint. Two rendered document images, one already patch-aligned (640x224, 560 patches) and one not (617x213 resized to 624x208, 507 patches), both transcribe exactly and token-for-token match a PyTorch reference built from the checkpoint's own vendor code. Switching the instruction to the table category makes the same page come back as an HTML table, so the category prompts reach the task head. Local gate: 56 unit tests plus 4 synthetic parity tests, `cargo clippy --features cuda --lib --tests -- -D warnings` clean. Closes #848
Falcon-OCR stores every request's KV in the caller-supplied cache slice, but it returns `supports_batching() == false` because its per-request positional state (temporal positions, spatial coordinates, rope delta) is single-row. The `LanguageModel::sequence_state_layout()` default infers the layout from `supports_batching()`, so the server classified the model as a model-owned SSM/recurrent runtime and allocated `SequenceStateLayout::model_owned`, whose external cache vector is empty. `forward_impl` walks `self.layers.iter().zip(caches.iter_mut())`, so an empty slice ran the loop zero times: all 22 decoder layers were skipped and the LM head read the raw token embedding. Nothing panicked and nothing logged, so both image and text-only server requests returned fluent garbage while the CLI path (which builds its own caches from `make_caches()`) stayed correct. On the real `tiiuae/Falcon-OCR` checkpoint, `mlxcel-server` transcribed a rendered document as "anner'\td colspan others than any of these two disl_i because if you may not quite" and returned byte-identical output for two differently sized pages. `FalconOcrTextModel` now declares `SequenceStateLayout::dense_kv_cache(n_layers)` explicitly and `FalconOcrVlModel` delegates it, mirroring the same override on Phi4MM, which declines batching for an unrelated reason and hits the same default. After the fix the server reproduces the CLI output exactly: the same document transcribes to "Review probe line one: 12345. / Second line: alpha beta gamma. / THIRD LINE END", and an image, text-only, image, image request sequence keeps every response correct. Two regression tests cover it: one asserts the declared layout is `DenseKvCache` with one cache per layer on both the text model and the VLM wrapper, and one asserts a forward pass handed an empty cache slice does not produce the same logits as a real one, so the layer loop stays observable. Verified on GB10 (CUDA sm_121, release): `falcon_ocr` lib tests 56 passed, `falcon_ocr_parity` 6 passed, `models::detection` 26 passed, `model_metadata` 8 passed, clippy clean, plus real-checkpoint CLI and server runs. Refs #848
Implementation Review SummaryIntent
Reviewed against the checkpoint's own vendor code ( Findings Addressed
Remaining Items
Verdicts on the focus areas1. Cross-cutting generation-state change: no regression risk. The PR does not touch shared generation code for this. Second-and-later-request behavior verified empirically on the live server (see above) and by tracing every path: the server drains the fallback slot into a per- 2. Non-parametric RMSNorm eps: both claims correct. 3. Hybrid mask: correct, and the tests do not validate the bug against itself. Derived independently from Other focus areas
Verification
|
`src/vision/falcon_ocr_layout.rs` shipped in this branch with nothing referring to it but its own `pub mod` line. Issue #848 lists layout-aware post-processing from `layout.py` as an acceptance criterion, and an unreachable module does not meet it, so the stage now runs from the real user-facing flow. `mlxcel generate --layout-detections <FILE>` reads already-detected page regions, plans them through the existing layout primitives (nested-box suppression, layout-class to OCR-category routing, cropping), and OCRs each survivor with the instruction its category was trained on, printing them in the file's order with class, score, and pixel box. The driver early-exits `run_generate_once` after the model load, mirroring the Florence-2 task pipeline, because one page becomes a sequence of per-region generations and cannot share the single-prompt loop below it. Each region routes through the existing `prepare_and_compute_vlm_embeddings_with_budget` and `run_generation_mode` path, so sampling, reserved-token suppression, and KV-cache mode behave as they do on every other generation. `-p/--prompt` carries nothing here, so it is optional and a non-empty one prints a note rather than being silently ignored. Detection itself is still not in the tree: the reference's first stage loads PP-DocLayoutV3 through `transformers.AutoModelForObjectDetection`, a separate object-detection architecture whose port is out of scope for this issue. The detections are therefore an input, and the accepted JSON is exactly the shape `mlxcel detect --format json` prints, so an in-tree detector added later needs no format change. Parsing is hand-written rather than serde-derived so every rejection names the offending entry by index, and the whole file is validated before the tokenizer or the model weights are touched. `layout_to_ocr_category` gained the four DocLayNet underscore spellings (`list_item`, `page_footer`, `page_header`, `section_header`) alongside the reference's hyphenated PP-DocLayoutV3 keys. An unmapped class is silently skipped, so without the aliases a page's list items and running heads would disappear from the output with nothing to explain it. For the same reason the command prints a one-line account of what the stage dropped, not only what survived. Validated on the real `tiiuae/Falcon-OCR` checkpoint (GB10, CUDA sm_121, release build) against a five-region PIL-rendered page with hand-written detections: all five regions return their exact drawn text in file order, the nested formula box is suppressed, the textless picture box is skipped, and the per-category instructions are visibly active (title as `#`, section header as `##`, table as HTML). Refs #848
The --layout-detections path had solid per-entry validation but no aggregate bound, so a few kilobytes of JSON could cost gigabytes of resident memory and quadratic CPU before a single OCR token was generated. Three input bounds. load_layout_detections reads through a Take-limited reader capped at MAX_LAYOUT_DETECTIONS_BYTES (32 MiB) instead of fs::read_to_string, and the ceiling is enforced on the bytes actually read because metadata().len() reports zero for a fifo. parse_layout_detections rejects an array over MAX_LAYOUT_DETECTIONS (4096) before building the Detection vector, since the nested-box suppression is quadratic in the entry count. parse_detection rejects a class name that carries a control character or runs longer than MAX_LAYOUT_CLASS_NAME_CHARS (64): that name is echoed back to the operator verbatim in the summary's `no text category:` list, which made it an unbounded escape-sequence injection channel into their terminal. The load-bearing change is lifetime rather than count. plan_layout_regions materialized one full DynamicImage crop per surviving detection and held them all before the first token; crop_imm copies, and the shared image admission limits allow a 512 MB decoded page, so twenty whole-page boxes cost roughly 10 GB up front. crop_region is now a thin wrapper over a new crop_rect geometry predicate, plan_layout_region_boxes plans into a LayoutOcrPlan carrying the crop rect instead of the pixels, and the driver cuts each region inside its per-region loop so the crop is dropped when that region finishes. Peak resident image memory becomes the page plus one crop, for any entry count. plan_layout_regions keeps its exact behavior by delegating to the same planner, so the two cannot drift apart. plan_summary now takes the nested-box survivors from the driver rather than recomputing filter_nested_detections a second time. Its printed wording is unchanged. Accepted JSON shapes, alias key lists, existing error wordings, CONTAINMENT_THRESHOLD, MIN_CROP_DIM and every OCR/category/instruction behavior are untouched. Validated with cargo test -p mlxcel --bin mlxcel generate_falcon_ocr (26 passed) and --lib falcon_ocr (61 passed) on CUDA, plus cargo clippy --features cuda --lib --bins --tests -D warnings. Refs #848
FalconOcrTextModel::forward_impl runs on every decode step, and for l == 1 it resolved the stashed prefill state by duplicating it: a heap clone of the whole prompt's position vector plus an mlx::core::copy of the [1, L, 2] spatial-coordinate array, which allocates a new MLX array node and crosses the FFI boundary. Both results were then thrown away. The l == 1 arm reads only the scalar rope_delta, and golden is unconditionally None there. An image prompt is thousands of tokens (the validation runs show 560 and 507 patch tokens, and the processor admits up to about 4000 patches), so decode did O(prompt_len) work per generated token, making total decode cost quadratic in prompt length on both the CLI and the server path. FalconOcrRuntimeState gains with_entry, the borrow-based accessor pattern qwen_mrope_state already uses, and decode_rope_delta built on top of it. The decode branch of forward_impl now allocates nothing beyond the one-element positions vector it actually needs. take_for_prefill compares the stashed length through with_entry and duplicates only on a match, so the eviction path no longer pays for a duplicate it immediately discards, and the prefill arm consumes the taken state's positions by value rather than cloning them a second time. forward_impl is restructured so its three cases read directly: a prefill with a matching stashed state (stashed positions, golden from pos_hw), a prefill without one (contiguous positions, no golden), and a decode step (offset plus the delta when one is available, contiguous otherwise, never golden). Behavior is bit-identical, including the l == 0 degenerate case. reset_runtime_state stays deliberately unoverridden and sequence_state_layout still declares a dense per-layer cache. Validated with cargo test -p mlxcel --lib falcon_ocr (61 passed) and --test falcon_ocr_parity (6 passed) on CUDA; the parity suite's incremental_decode_matches_a_full_sequence_pass is what catches a wrong rope delta. cargo clippy --features cuda --lib --bins --tests -D warnings is clean. Refs #848
Security and performance reviewReviewed HIGH: unbounded memory and CPU amplification in
|
…chain (#1081) Bilingual technical reports for the three VLM ports merged on 2026-08-07, following the existing `TECHNICAL_REPORTS/` convention. Each report is dated by its PR's merge date rather than the authoring date, and each Korean file mirrors its English counterpart section for section. - `1070-locateanything-vlm-20260807.{en,ko}.md` for PR #1070 (issue #847), LocateAnything grounding VLM. - `1075-falcon-ocr-early-fusion-20260807.{en,ko}.md` for PR #1075 (issue #848), Falcon-OCR early-fusion VLM. - `1076-jina-vlm-20260807.{en,ko}.md` for PR #1076 (issue #849), Jina VLM. The reports concentrate on what real-checkpoint validation caught and synthetic parity would have missed. The LocateAnything report records that the released checkpoint is `mixed_4_8` rather than uniform 4-bit, which hard-errors in `FusedQKVLinear::from_weights_separate`, and that this breaks any family loading an `mlx_lm --quant-predicate mixed_4_8` conversion rather than LocateAnything alone. The Falcon-OCR report records the `sequence_state_layout()` trait default that let the scheduler allocate an empty cache vector, so the server ran zero of 22 decoder layers with no panic and no log line while the CLI stayed correct because it builds its own caches. The Jina VLM report records that the checkpoint declares `model_type: jvlm` rather than the `jina_vlm` the issue assumed, and that the chat-template fallback's matching 824 prompt-token count across CLI and server was coincidence rather than evidence that the two front ends rendered the same prompt. Each report also carries an explicit section for what was not verified, so the gaps are on the record: no numeric oracle parity for Jina VLM, the Apple Silicon bf16 branch that cannot be exercised on the Linux CUDA box, absent layout detection for Falcon-OCR, and the pre-existing failures on `main` that were control-run before being attributed anywhere. Documentation only. No source, test, or build changes.
…1127) `mlxcel detect` returned boxes that matched no page content: on a portrait page every detection collapsed onto one origin-anchored rectangle that stopped near the middle of the page, with `page_footer` scoring highest despite nothing being detected near the footer. The cause is the host readback in `predictor`, not the coordinate mapping. The forward graph inherits the checkpoint dtype: `pixel_values` is cast to f32, but the first conv against a bf16 weight settles the graph into bf16, so `pred_logits` and `pred_boxes` come back as bf16 for the shipped checkpoints. `to_f32_vec` parsed that buffer as 4-byte little-endian f32. bf16 is the high half of an f32, so a 4-byte parse fuses each adjacent pair of values into one bogus float and returns half the elements. The decode then indexed `query * num_labels` and `query * 4` into buffers half the advertised size, misaligning every query, label, and box association without erroring. Three module doc comments asserted the whole graph ran in f32, which is what let the mismatch sit unnoticed. The reported aspect-ratio dependence was a coincidence of which garbage indices survived: the same collapse reproduces on a square page. The box mapping itself was already correct. The RT-DETRv2 preprocessor resizes straight to a square with `do_pad: false`, so there is no letterbox to undo and the inverse is an independent per-axis scale, identical for tall, wide, and square inputs. The readback now casts to f32 before touching raw bytes, and the decode rejects a length mismatch instead of silently consuming a short buffer. `decode_detections` and `denormalize_box` are split out of the predictor method so the seam is unit-testable without a checkpoint. Verified on GB10 / CUDA sm_121 against `docling-layout-heron-mlx-bf16` with synthetic pages of known geometry at 1000x1300, 1300x1000, and 1000x1000. Every drawn element now returns a distinct in-range box on its content: a heading drawn at x 80, y 55-105 returns (80.08, 60.14)-(771.48, 108.70), and a footer drawn at x 80, y 1200 returns (78.13, 1200.34)-(671.88, 1237.16) labelled `page_footer`. Two consequences for the `detect | generate --layout-detections` pipeline that #1075 built: `detect` now emits reading order (top to bottom, then left to right) rather than descending confidence. The Falcon-OCR layout path deliberately preserves the order of the file it is handed, because the reference detector carries an order head, so the detector's order becomes the order the per-region OCR prints. RT-DETRv2 has no order head, so the order is derived from geometry. The comparison is a strict total order, with confidence and class id as tiebreaks, so output is reproducible. The layout planner now collapses same-box detections to one region. A DETR-style head takes no per-query argmax, so one query clearing the threshold under several classes emits one detection per class, all carrying that query's box. That is the reference head's intended output and `detect` still prints all of it, but OCRing each entry would repeat the same text once per label. The collapse runs after the OCR category mapping, so a box labelled both `picture` and `text` is still read as text rather than dropped on the un-OCRable label. `filter_nested_detections` stays a pure geometry filter mirroring the reference. Closes #1089
…ablup#1075) ## Summary Adds native support for Falcon-OCR (`model_type: falcon_ocr`, ~300M), TII's early-fusion document-OCR VLM, and the first VLM in the tree with no vision tower at all. Each 16x16 RGB patch is flattened and pushed through a single linear `img_projector` straight into the token stream, and one 22-layer decoder reads image and text together under a hybrid mask that is bidirectional inside every image block and causal everywhere else. Validated end to end on the real `tiiuae/Falcon-OCR` checkpoint against a PyTorch reference built from the checkpoint's own vendor code. The issue suggested reusing the Falcon-H1 backbone. That is not what the weights describe, so this is a dedicated module: Falcon-H1 is a Mamba2 + attention hybrid, and Falcon-OCR is a small Llama-derived decoder with five bespoke pieces. ## Resolving the per-layer-norm discrepancy The issue expected per-head Q/K RMSNorm weights. The checkpoint ships exactly five tensors per layer (`attention.wqkv`, `attention.wo`, `attention.sinks`, `feed_forward.w13`, `feed_forward.w2`) and no `attention_norm`, `ffn_norm`, `q_norm` or `k_norm`. The checkpoint's own `modeling_falcon_ocr.py` settles it: every pre-norm in the stack, including the per-head Q and K norms, is `F.rms_norm(x, (dim,))` with **no learnable weight**. The norms are not missing and must not be skipped; they are non-parametric, and they run through `fast_rms_norm_no_weight`. PyTorch resolves their `eps=None` to `torch.finfo(float32).eps`, so the constant is `f32::EPSILON` rather than the config's `norm_eps` (1e-5), which applies only to the single parametric `norm` before the LM head. ## Decoder Llama-derived with five differences, all visible in the shipped weights: a fused `wqkv`; weightless RMSNorm everywhere except the final norm; per-head learned attention sinks fed to MLX's sink-aware SDPA (the same entry point gpt-oss uses); a squared-ReLU gated MLP over a row-interleaved fused `w13`; and a 3-D rotary that puts a 1-D temporal rotary on the low half of each head and a 2-D per-head spatial rotary (driven by the checkpoint's `freqs_cis_golden` table) on the high half. Both rotary halves use the interleaved pair convention, not half-split, because the reference builds complex numbers with `view_as_complex(x.reshape(..., -1, 2))`. K and V are expanded to `n_heads` **before** the rotary rather than after, because the spatial rotary has per-head frequencies and each repeated copy must receive its own rotation. The KV cache therefore holds `n_heads` heads rather than `n_kv_heads`. ## Per-request positional state and its lifecycle An entire image block collapses onto one temporal position, so a decode step adds a negative, image-size-dependent delta to the cache offset to recover the absolute position. That state is written by the image stage and consumed by prefill and every decode step, which makes its lifecycle the subtle part. `reset_runtime_state` is deliberately **not** overridden: the generate loop calls it after the image stage has written the state and before prefill consumes it, so clearing there throws away the positions for the request about to run (this was a real bug during development, and it produced fluent LaTeX garbage rather than a crash). Staleness is instead handled at the prefill boundary, where a prompt length that does not match the stashed positions evicts the entry so an image turn cannot shift the positions of a following text-only turn. The server gets per-sequence isolation through `bind_falcon_ocr_state_to_sequence`, alongside the existing Qwen-MRoPE and Gemma-4 binders. ## Chunked prefill `supports_chunked_prefill` returns false, matching upstream's `Model.no_chunked_prefill = True`. Checked against mlxcel's actual prefill path rather than taken on faith: `chunked_prefill_last_logits` re-enters `forward` with `mask = None` and a slice of the tokens, which would drop the bidirectional image block and misalign every position after the first chunk. `supports_padded_prefill` is off for the same reason (tile padding would desync the per-token position vector and the `[1, 1, S, S]` mask). The embeddings path never chunked anyway, so this only closes the text-only door. ## Prompt and preprocessing Image blocks are prepended (or substituted for an existing `<|image|>` placeholder), and `<|OCR_PLAIN|>` is appended when the prompt does not already end with it. The task token is load-bearing rather than decoration: measured against the reference on a rendered document, dropping it makes the model narrate the page (`formally named *The quick brown fox...*`) instead of transcribing it. `<|end_of_query|>` joins the stop set, matching the reference's `[eos_id, <|end_of_query|>]`, so decode stops on the marker instead of printing it. Preprocessing mirrors the two back-to-back resize stages of `processing_falcon_ocr.py` and skips a resize whose target equals the source, the way PIL does, so an already patch-aligned document reaches the model bit-identical to the reference. `smart_resize` uses banker's rounding because Python's `round` does; the two rules disagree at every `height % 16 == 8` and would change the image-token budget. ## Weight loading The checkpoint uses the original Falcon naming (`tok_embeddings`, `layers.N.attention.*`, `layers.N.feed_forward.*`, `output`) rather than the HF scheme, so only `w13` needs rewriting. The interleaving order was verified empirically rather than assumed: the reference triton kernel reads gate at `2 * col` and up at `2 * col + 1`, mlx-vlm's `sanitize` undoes it with `concatenate([v[0::2], v[1::2]])`, and a PyTorch reference using `packed[..., 0::2]` as gate reproduces the checkpoint's text exactly. So gate is the even rows and up the odd rows, and the split is applied to every tensor under a `w13` prefix (not just `.weight`) so a future affine-quantized conversion's `scales`/`biases` follow their weight. ## Layout stage, and how it reaches the user `src/vision/falcon_ocr_layout.rs` ports the layout-aware second stage from `layout.py`: category routing (`LAYOUT_TO_OCR_CATEGORY`), nested-box suppression, region cropping with the reference's post-resize sliver rejection, and the per-category instruction sentences. It is expressed over `vision::detection::Detection`, the shape mlxcel's existing RT-DETR-family detector already produces. That module started out unreachable: nothing but its own `pub mod` line referred to it. An orphaned module does not satisfy the issue's "layout-aware post-processing from `layout.py`" criterion, so it is now wired to the real CLI flow through `mlxcel generate --layout-detections <FILE>`. The seam is a driver that early-exits `run_generate_once` after the model load, the same shape the Florence-2 task pipeline uses, because one page becomes a sequence of per-region generations and cannot share the single-prompt loop below it. Each surviving region is cropped from `--image`, tokenized as the reference's `f"{instruction}\n"` (the Falcon-OCR prompt builder appends the image block and the `<|OCR_PLAIN|>` task token itself), and run through the existing `prepare_and_compute_vlm_embeddings_with_budget` plus `run_generation_mode` path, so sampling, reserved-token suppression, and KV-cache mode behave exactly as they do on every other generation. Regions print in the file's order with their class, score, and pixel box. `-p/--prompt` carries nothing here, so it is optional (an absent `-p` no longer means "interactive chat" when the flag is set) and a non-empty one prints a note instead of being silently dropped. **Detection is still not included.** The reference's first stage loads PP-DocLayoutV3 through `transformers.AutoModelForObjectDetection`; that is a separate object-detection architecture and porting it is out of scope for this issue. The detections are therefore an input. The accepted JSON is exactly the shape `mlxcel detect --format json` prints, so a document-layout detector mlxcel gains later feeds this path without a format change; a bare top-level array and the `{"category", "bbox", "score"}` spelling `layout.py` itself emits are also accepted. Validation is hand-written rather than serde-derived so every rejection names the offending entry by index, and the whole file is parsed before the model is loaded: ``` $ mlxcel generate -m models/mlx/falcon-ocr --image page.png --layout-detections bad.json Error: --layout-detections bad.json: detection lablup#1: the bounding box is empty or inverted (left=60.00, top=450.00, right=940.00, bottom=295.00); expected right > left and bottom > top ``` `layout_to_ocr_category` gained four aliases. DocLayNet-derived detectors (docling-layout, and therefore anything routed through `mlxcel detect`) spell `list_item` / `page_footer` / `page_header` / `section_header` with underscores where PP-DocLayoutV3 hyphenates them. An unmapped class is silently skipped, so without the aliases a page's list items and running heads would disappear from the output with nothing to explain it. The reference's own keys are untouched, and `paragraph_title` / `doc_title` / `figure_title` keep their reference spelling because no detector hyphenates those. For the same "nothing should vanish quietly" reason the command prints a one-line account of what the stage kept and dropped, not just the surviving regions. ## What changed - `src/models/falcon_ocr.rs`, `src/models/falcon_ocr_rope.rs`: config (raw `dim`/`n_layers`/`ffn_dim` keys with HF aliases), decoder, per-request state, 3-D rotary, temporal/spatial positions, hybrid mask builder. - `src/vision/falcon_ocr.rs`: VLM runtime (patch projection, LLaVA-style scatter, positional state, mask). - `src/vision/processors/falcon_ocr.rs`: two-stage resize, normalization, patchification to `[total_patches, patch_dim]`. - `src/vision/falcon_ocr_layout.rs`: layout-aware post-processing, plus the four DocLayNet underscore aliases. - `src/commands/generate_falcon_ocr.rs` (new): `--layout-detections` parsing and validation, and the per-region OCR driver. - `src/commands/generate_falcon_ocr_tests.rs` (new): 20 tests over the parser, the plan-to-regions path, reading order, and the drop summary. - `src/commands/generate.rs`: the `--layout-detections` preflight (run before the tokenizer and the weights are touched), the driver early exit, `pub(super)` on `run_generation_mode` / `decode_generated_text`, and the no-`-p` routing. - `src/main.rs`: the `--layout-detections` flag. - `src/multimodal/falcon_ocr_prompt.rs`: image-block expansion and task-token append. - `src/loading/vlm_falcon_ocr.rs`: `w13` de-interleaving, tokenizer-derived special tokens, model assembly. - Control-plane wiring: `ModelType::FalconOcrVL`, the `"falcon_ocr"` detection arm, `for_each_model_registration!`, `LoadedModel`, `VlmRuntimeRef::FalconOcr`, `try_load_vlm_model_from_dir`, the `generate_vlm` summary line, the TP arch-string table, and the scheduler's per-sequence state binder. - `docs/supported-models.md`. ## Real-checkpoint validation GB10, CUDA (sm_121), release build, `models/mlx/falcon-ocr` (`tiiuae/Falcon-OCR`, float32). Two rendered document images with known text, one already patch-aligned and one not, so both the identity and the resize path are exercised. Image 1, `doc_text.png`, 640x224 (patch-aligned, 14x40 = 560 patches). Expected text: `The quick brown fox jumps over the lazy dog.` / `Invoice No. 2026-0847` / `Total amount due: $1,234.56`. ``` $ ./target/release/mlxcel generate -m models/mlx/falcon-ocr --image doc_text.png \ -p "Extract the text content from this image." -n 128 --temp 0.0 Falcon-OCR: inserted 1 image block(s) (560 patch tokens, OCR task token appended) The quick brown fox jumps over the lazy dog. Invoice No. 2026-0847 Total amount due: $1,234.56 [Generated 40 tokens in 1.22s = 32.81 tok/s] ``` Image 2, `doc_text2.png`, 617x213 (not aligned; resized to 624x208, 13x39 = 507 patches). Expected text: `Falcon OCR early fusion test` / `Line two: 42 apples, 7 oranges.` / `END OF PAGE`. ``` $ ./target/release/mlxcel generate -m models/mlx/falcon-ocr --image doc_text2.png \ -p "Extract the text content from this image." -n 128 --temp 0.0 Falcon-OCR: inserted 1 image block(s) (507 patch tokens, OCR task token appended) Falcon OCR early fusion test Line two: 42 apples, 7 oranges. END OF PAGE [Generated 26 tokens in 1.02s = 25.52 tok/s] ``` Both outputs are exactly the text in the images and token-for-token identical to a PyTorch reference transcribed from the checkpoint's own vendor code (float32, CPU, dense masks in place of FlexAttention and a python squared-ReLU gate in place of the triton kernel). Switching the instruction to the table category returns the same page as `<table><tr><td>The quick brown fox...</td></tr>...</table>`, so the category prompts reach the task head rather than being ignored. Intermediate hidden states were compared layer by layer against the reference during bring-up: the merged embedding matches to the printed precision (`first=[-0.47189316, -0.07527875, 0.21209943, -0.07072593]` on both sides), which pins down the image preprocessing and the patch projection, and layer 0 agrees to about 1e-3 with TF32 left at its default. `./target/release/mlxcel arch` lists `Falcon-OCR (early fusion)` under the Falcon family. ### Layout-aware OCR end to end A five-region page rendered with PIL (title, section header, body paragraph, a bordered 3x3 table, page footer) plus hand-written detections that also carry a nested `formula` box inside the paragraph and a textless `picture` box, so the suppression and skip paths are exercised rather than asserted: ``` $ ./target/release/mlxcel generate -m models/mlx/falcon-ocr \ --image page.png --layout-detections regions.json -n 256 --temp 0.0 Falcon-OCR layout: 7 detection(s); 1 nested box(es) dropped; no text category: picture; 5 region(s) to OCR [1] title (score 0.960) bbox=[60.0, 55.0, 940.0, 140.0] # Quarterly Revenue Report [2] section_header (score 0.930) bbox=[60.0, 195.0, 940.0, 260.0] ## Executive Summary [3] text (score 0.950) bbox=[60.0, 295.0, 940.0, 450.0] Revenue grew steadily across all three regions during the quarter. The northern division led the increase, followed by the coastal offices. Operating costs remained flat. [4] table (score 0.910) bbox=[100.0, 540.0, 800.0, 760.0] <table><thead><tr><th>Region</th><th>Q1</th><th>Q2</th></tr></thead><tbody><tr><td>North</td><td>120</td><td>145</td></tr><tr><td>Coast</td><td>98</td><td>104</td></tr></tbody></table> [5] page_footer (score 0.880) bbox=[60.0, 1205.0, 400.0, 1260.0] Page 1 of 4 [Layout OCR: 5 region(s), 107 tokens in 2.14s = 50.11 tok/s] ``` Every region is the exact text drawn into it, in the order the file lists them. The per-category instruction is doing real work rather than being decoration: the same model returns the title as `#` and the section header as `##` from otherwise identical single-line crops, and the table region comes back as HTML rather than as the flat cell text a `plain` prompt yields. ## Test plan - [x] `MLX_ENABLE_TF32=0 cargo test --profile test-fast --features cuda -p mlxcel --lib falcon_ocr -- --test-threads=1` -> 57 passed - [x] `MLX_ENABLE_TF32=0 cargo test --profile test-fast --features cuda -p mlxcel --bin mlxcel generate_falcon_ocr -- --test-threads=1` -> 20 passed - [x] `MLX_ENABLE_TF32=0 cargo test --profile test-fast --features cuda -p mlxcel --test falcon_ocr_parity -- --test-threads=1` -> 4 passed - [x] `MLX_ENABLE_TF32=0 cargo test --profile test-fast --features cuda -p mlxcel --lib models::detection -- --test-threads=1` -> 26 passed - [x] `MLX_ENABLE_TF32=0 cargo test --profile test-fast --features cuda -p mlxcel --lib model_metadata -- --test-threads=1` -> 8 passed - [x] `MLX_ENABLE_TF32=0 cargo test --profile test-fast --features cuda -p mlxcel --lib models::metadata_tests -- --test-threads=1` -> 4 passed - [x] `cargo clippy --features cuda --lib --bins --tests -- -D warnings` clean - [x] `cargo fmt --all` clean - [x] `cargo build --release --features cuda --bin mlxcel` plus the two whole-page OCR runs and the five-region layout run above The synthetic parity test covers the three pieces easiest to get subtly wrong without a crash: that the hybrid mask actually reaches SDPA (a hybrid prefill must differ from a causal one), that an incremental decode lands on the same logits as a single full-sequence pass (which is what catches a wrong rope delta, since the image block collapses ten sequence slots onto one temporal index), and that the sinks tensor is consumed rather than merely loaded. ## Not verified Multi-image prompts, quantized conversions (none exist yet; the `w13` split handles the sidecars but is untested against a real quantized checkpoint), and concurrent server requests. The per-sequence state binding is wired the same way the Qwen-MRoPE and Gemma-4 binders are and is unit-tested, but was not exercised under a live multi-request server load. Layout DETECTION remains outside the tree, so `--layout-detections` cannot close the loop on its own: the boxes have to come from a detector mlxcel does not ship. `mlxcel detect` does load RT-DETRv2 checkpoints and its JSON is the format this flag consumes, but pointing it at the docling-layout-heron document-layout checkpoint on a rendered page returned boxes that do not correspond to the page content (a `page_footer` at `[0, 103, 759, 124]` on a 1000x1300 page whose footer sits at y=1220), so that pairing is not offered as a working recipe here. Whether that is a predictor bug, a preprocessing mismatch for this checkpoint family, or simply the wrong model for the input is a separate question from this issue and is worth its own investigation. The layout path also does not batch: the reference OCRs crops in chunks of 32, while this driver runs one region per generation. Region count is small for a page, so this is a throughput note rather than a correctness one. Closes lablup#848
…blup#849 VLM port chain (lablup#1081) Bilingual technical reports for the three VLM ports merged on 2026-08-07, following the existing `TECHNICAL_REPORTS/` convention. Each report is dated by its PR's merge date rather than the authoring date, and each Korean file mirrors its English counterpart section for section. - `1070-locateanything-vlm-20260807.{en,ko}.md` for PR lablup#1070 (issue lablup#847), LocateAnything grounding VLM. - `1075-falcon-ocr-early-fusion-20260807.{en,ko}.md` for PR lablup#1075 (issue lablup#848), Falcon-OCR early-fusion VLM. - `1076-jina-vlm-20260807.{en,ko}.md` for PR lablup#1076 (issue lablup#849), Jina VLM. The reports concentrate on what real-checkpoint validation caught and synthetic parity would have missed. The LocateAnything report records that the released checkpoint is `mixed_4_8` rather than uniform 4-bit, which hard-errors in `FusedQKVLinear::from_weights_separate`, and that this breaks any family loading an `mlx_lm --quant-predicate mixed_4_8` conversion rather than LocateAnything alone. The Falcon-OCR report records the `sequence_state_layout()` trait default that let the scheduler allocate an empty cache vector, so the server ran zero of 22 decoder layers with no panic and no log line while the CLI stayed correct because it builds its own caches. The Jina VLM report records that the checkpoint declares `model_type: jvlm` rather than the `jina_vlm` the issue assumed, and that the chat-template fallback's matching 824 prompt-token count across CLI and server was coincidence rather than evidence that the two front ends rendered the same prompt. Each report also carries an explicit section for what was not verified, so the gaps are on the record: no numeric oracle parity for Jina VLM, the Apple Silicon bf16 branch that cannot be exercised on the Linux CUDA box, absent layout detection for Falcon-OCR, and the pre-existing failures on `main` that were control-run before being attributed anywhere. Documentation only. No source, test, or build changes.
…ablup#1127) `mlxcel detect` returned boxes that matched no page content: on a portrait page every detection collapsed onto one origin-anchored rectangle that stopped near the middle of the page, with `page_footer` scoring highest despite nothing being detected near the footer. The cause is the host readback in `predictor`, not the coordinate mapping. The forward graph inherits the checkpoint dtype: `pixel_values` is cast to f32, but the first conv against a bf16 weight settles the graph into bf16, so `pred_logits` and `pred_boxes` come back as bf16 for the shipped checkpoints. `to_f32_vec` parsed that buffer as 4-byte little-endian f32. bf16 is the high half of an f32, so a 4-byte parse fuses each adjacent pair of values into one bogus float and returns half the elements. The decode then indexed `query * num_labels` and `query * 4` into buffers half the advertised size, misaligning every query, label, and box association without erroring. Three module doc comments asserted the whole graph ran in f32, which is what let the mismatch sit unnoticed. The reported aspect-ratio dependence was a coincidence of which garbage indices survived: the same collapse reproduces on a square page. The box mapping itself was already correct. The RT-DETRv2 preprocessor resizes straight to a square with `do_pad: false`, so there is no letterbox to undo and the inverse is an independent per-axis scale, identical for tall, wide, and square inputs. The readback now casts to f32 before touching raw bytes, and the decode rejects a length mismatch instead of silently consuming a short buffer. `decode_detections` and `denormalize_box` are split out of the predictor method so the seam is unit-testable without a checkpoint. Verified on GB10 / CUDA sm_121 against `docling-layout-heron-mlx-bf16` with synthetic pages of known geometry at 1000x1300, 1300x1000, and 1000x1000. Every drawn element now returns a distinct in-range box on its content: a heading drawn at x 80, y 55-105 returns (80.08, 60.14)-(771.48, 108.70), and a footer drawn at x 80, y 1200 returns (78.13, 1200.34)-(671.88, 1237.16) labelled `page_footer`. Two consequences for the `detect | generate --layout-detections` pipeline that lablup#1075 built: `detect` now emits reading order (top to bottom, then left to right) rather than descending confidence. The Falcon-OCR layout path deliberately preserves the order of the file it is handed, because the reference detector carries an order head, so the detector's order becomes the order the per-region OCR prints. RT-DETRv2 has no order head, so the order is derived from geometry. The comparison is a strict total order, with confidence and class id as tiebreaks, so output is reproducible. The layout planner now collapses same-box detections to one region. A DETR-style head takes no per-query argmax, so one query clearing the threshold under several classes emits one detection per class, all carrying that query's box. That is the reference head's intended output and `detect` still prints all of it, but OCRing each entry would repeat the same text once per label. The collapse runs after the OCR category mapping, so a box labelled both `picture` and `text` is still read as text rather than dropped on the un-OCRable label. `filter_nested_detections` stays a pure geometry filter mirroring the reference. Closes lablup#1089
Summary
Adds native support for Falcon-OCR (
model_type: falcon_ocr, ~300M), TII's early-fusion document-OCR VLM, and the first VLM in the tree with no vision tower at all. Each 16x16 RGB patch is flattened and pushed through a single linearimg_projectorstraight into the token stream, and one 22-layer decoder reads image and text together under a hybrid mask that is bidirectional inside every image block and causal everywhere else. Validated end to end on the realtiiuae/Falcon-OCRcheckpoint against a PyTorch reference built from the checkpoint's own vendor code.The issue suggested reusing the Falcon-H1 backbone. That is not what the weights describe, so this is a dedicated module: Falcon-H1 is a Mamba2 + attention hybrid, and Falcon-OCR is a small Llama-derived decoder with five bespoke pieces.
Resolving the per-layer-norm discrepancy
The issue expected per-head Q/K RMSNorm weights. The checkpoint ships exactly five tensors per layer (
attention.wqkv,attention.wo,attention.sinks,feed_forward.w13,feed_forward.w2) and noattention_norm,ffn_norm,q_normork_norm. The checkpoint's ownmodeling_falcon_ocr.pysettles it: every pre-norm in the stack, including the per-head Q and K norms, isF.rms_norm(x, (dim,))with no learnable weight. The norms are not missing and must not be skipped; they are non-parametric, and they run throughfast_rms_norm_no_weight. PyTorch resolves theireps=Nonetotorch.finfo(float32).eps, so the constant isf32::EPSILONrather than the config'snorm_eps(1e-5), which applies only to the single parametricnormbefore the LM head.Decoder
Llama-derived with five differences, all visible in the shipped weights: a fused
wqkv; weightless RMSNorm everywhere except the final norm; per-head learned attention sinks fed to MLX's sink-aware SDPA (the same entry point gpt-oss uses); a squared-ReLU gated MLP over a row-interleaved fusedw13; and a 3-D rotary that puts a 1-D temporal rotary on the low half of each head and a 2-D per-head spatial rotary (driven by the checkpoint'sfreqs_cis_goldentable) on the high half. Both rotary halves use the interleaved pair convention, not half-split, because the reference builds complex numbers withview_as_complex(x.reshape(..., -1, 2)).K and V are expanded to
n_headsbefore the rotary rather than after, because the spatial rotary has per-head frequencies and each repeated copy must receive its own rotation. The KV cache therefore holdsn_headsheads rather thann_kv_heads.Per-request positional state and its lifecycle
An entire image block collapses onto one temporal position, so a decode step adds a negative, image-size-dependent delta to the cache offset to recover the absolute position. That state is written by the image stage and consumed by prefill and every decode step, which makes its lifecycle the subtle part.
reset_runtime_stateis deliberately not overridden: the generate loop calls it after the image stage has written the state and before prefill consumes it, so clearing there throws away the positions for the request about to run (this was a real bug during development, and it produced fluent LaTeX garbage rather than a crash). Staleness is instead handled at the prefill boundary, where a prompt length that does not match the stashed positions evicts the entry so an image turn cannot shift the positions of a following text-only turn. The server gets per-sequence isolation throughbind_falcon_ocr_state_to_sequence, alongside the existing Qwen-MRoPE and Gemma-4 binders.Chunked prefill
supports_chunked_prefillreturns false, matching upstream'sModel.no_chunked_prefill = True. Checked against mlxcel's actual prefill path rather than taken on faith:chunked_prefill_last_logitsre-entersforwardwithmask = Noneand a slice of the tokens, which would drop the bidirectional image block and misalign every position after the first chunk.supports_padded_prefillis off for the same reason (tile padding would desync the per-token position vector and the[1, 1, S, S]mask). The embeddings path never chunked anyway, so this only closes the text-only door.Prompt and preprocessing
Image blocks are prepended (or substituted for an existing
<|image|>placeholder), and<|OCR_PLAIN|>is appended when the prompt does not already end with it. The task token is load-bearing rather than decoration: measured against the reference on a rendered document, dropping it makes the model narrate the page (formally named *The quick brown fox...*) instead of transcribing it.<|end_of_query|>joins the stop set, matching the reference's[eos_id, <|end_of_query|>], so decode stops on the marker instead of printing it.Preprocessing mirrors the two back-to-back resize stages of
processing_falcon_ocr.pyand skips a resize whose target equals the source, the way PIL does, so an already patch-aligned document reaches the model bit-identical to the reference.smart_resizeuses banker's rounding because Python'srounddoes; the two rules disagree at everyheight % 16 == 8and would change the image-token budget.Weight loading
The checkpoint uses the original Falcon naming (
tok_embeddings,layers.N.attention.*,layers.N.feed_forward.*,output) rather than the HF scheme, so onlyw13needs rewriting. The interleaving order was verified empirically rather than assumed: the reference triton kernel reads gate at2 * coland up at2 * col + 1, mlx-vlm'ssanitizeundoes it withconcatenate([v[0::2], v[1::2]]), and a PyTorch reference usingpacked[..., 0::2]as gate reproduces the checkpoint's text exactly. So gate is the even rows and up the odd rows, and the split is applied to every tensor under aw13prefix (not just.weight) so a future affine-quantized conversion'sscales/biasesfollow their weight.Layout stage, and how it reaches the user
src/vision/falcon_ocr_layout.rsports the layout-aware second stage fromlayout.py: category routing (LAYOUT_TO_OCR_CATEGORY), nested-box suppression, region cropping with the reference's post-resize sliver rejection, and the per-category instruction sentences. It is expressed overvision::detection::Detection, the shape mlxcel's existing RT-DETR-family detector already produces.That module started out unreachable: nothing but its own
pub modline referred to it. An orphaned module does not satisfy the issue's "layout-aware post-processing fromlayout.py" criterion, so it is now wired to the real CLI flow throughmlxcel generate --layout-detections <FILE>.The seam is a driver that early-exits
run_generate_onceafter the model load, the same shape the Florence-2 task pipeline uses, because one page becomes a sequence of per-region generations and cannot share the single-prompt loop below it. Each surviving region is cropped from--image, tokenized as the reference'sf"{instruction}\n"(the Falcon-OCR prompt builder appends the image block and the<|OCR_PLAIN|>task token itself), and run through the existingprepare_and_compute_vlm_embeddings_with_budgetplusrun_generation_modepath, so sampling, reserved-token suppression, and KV-cache mode behave exactly as they do on every other generation. Regions print in the file's order with their class, score, and pixel box.-p/--promptcarries nothing here, so it is optional (an absent-pno longer means "interactive chat" when the flag is set) and a non-empty one prints a note instead of being silently dropped.Detection is still not included. The reference's first stage loads PP-DocLayoutV3 through
transformers.AutoModelForObjectDetection; that is a separate object-detection architecture and porting it is out of scope for this issue. The detections are therefore an input. The accepted JSON is exactly the shapemlxcel detect --format jsonprints, so a document-layout detector mlxcel gains later feeds this path without a format change; a bare top-level array and the{"category", "bbox", "score"}spellinglayout.pyitself emits are also accepted. Validation is hand-written rather than serde-derived so every rejection names the offending entry by index, and the whole file is parsed before the model is loaded:layout_to_ocr_categorygained four aliases. DocLayNet-derived detectors (docling-layout, and therefore anything routed throughmlxcel detect) spelllist_item/page_footer/page_header/section_headerwith underscores where PP-DocLayoutV3 hyphenates them. An unmapped class is silently skipped, so without the aliases a page's list items and running heads would disappear from the output with nothing to explain it. The reference's own keys are untouched, andparagraph_title/doc_title/figure_titlekeep their reference spelling because no detector hyphenates those. For the same "nothing should vanish quietly" reason the command prints a one-line account of what the stage kept and dropped, not just the surviving regions.What changed
src/models/falcon_ocr.rs,src/models/falcon_ocr_rope.rs: config (rawdim/n_layers/ffn_dimkeys with HF aliases), decoder, per-request state, 3-D rotary, temporal/spatial positions, hybrid mask builder.src/vision/falcon_ocr.rs: VLM runtime (patch projection, LLaVA-style scatter, positional state, mask).src/vision/processors/falcon_ocr.rs: two-stage resize, normalization, patchification to[total_patches, patch_dim].src/vision/falcon_ocr_layout.rs: layout-aware post-processing, plus the four DocLayNet underscore aliases.src/commands/generate_falcon_ocr.rs(new):--layout-detectionsparsing and validation, and the per-region OCR driver.src/commands/generate_falcon_ocr_tests.rs(new): 20 tests over the parser, the plan-to-regions path, reading order, and the drop summary.src/commands/generate.rs: the--layout-detectionspreflight (run before the tokenizer and the weights are touched), the driver early exit,pub(super)onrun_generation_mode/decode_generated_text, and the no--prouting.src/main.rs: the--layout-detectionsflag.src/multimodal/falcon_ocr_prompt.rs: image-block expansion and task-token append.src/loading/vlm_falcon_ocr.rs:w13de-interleaving, tokenizer-derived special tokens, model assembly.ModelType::FalconOcrVL, the"falcon_ocr"detection arm,for_each_model_registration!,LoadedModel,VlmRuntimeRef::FalconOcr,try_load_vlm_model_from_dir, thegenerate_vlmsummary line, the TP arch-string table, and the scheduler's per-sequence state binder.docs/supported-models.md.Real-checkpoint validation
GB10, CUDA (sm_121), release build,
models/mlx/falcon-ocr(tiiuae/Falcon-OCR, float32). Two rendered document images with known text, one already patch-aligned and one not, so both the identity and the resize path are exercised.Image 1,
doc_text.png, 640x224 (patch-aligned, 14x40 = 560 patches). Expected text:The quick brown fox jumps over the lazy dog./Invoice No. 2026-0847/Total amount due: $1,234.56.Image 2,
doc_text2.png, 617x213 (not aligned; resized to 624x208, 13x39 = 507 patches). Expected text:Falcon OCR early fusion test/Line two: 42 apples, 7 oranges./END OF PAGE.Both outputs are exactly the text in the images and token-for-token identical to a PyTorch reference transcribed from the checkpoint's own vendor code (float32, CPU, dense masks in place of FlexAttention and a python squared-ReLU gate in place of the triton kernel). Switching the instruction to the table category returns the same page as
<table><tr><td>The quick brown fox...</td></tr>...</table>, so the category prompts reach the task head rather than being ignored. Intermediate hidden states were compared layer by layer against the reference during bring-up: the merged embedding matches to the printed precision (first=[-0.47189316, -0.07527875, 0.21209943, -0.07072593]on both sides), which pins down the image preprocessing and the patch projection, and layer 0 agrees to about 1e-3 with TF32 left at its default../target/release/mlxcel archlistsFalcon-OCR (early fusion)under the Falcon family.Layout-aware OCR end to end
A five-region page rendered with PIL (title, section header, body paragraph, a bordered 3x3 table, page footer) plus hand-written detections that also carry a nested
formulabox inside the paragraph and a textlesspicturebox, so the suppression and skip paths are exercised rather than asserted:Every region is the exact text drawn into it, in the order the file lists them. The per-category instruction is doing real work rather than being decoration: the same model returns the title as
#and the section header as##from otherwise identical single-line crops, and the table region comes back as HTML rather than as the flat cell text aplainprompt yields.Test plan
MLX_ENABLE_TF32=0 cargo test --profile test-fast --features cuda -p mlxcel --lib falcon_ocr -- --test-threads=1-> 57 passedMLX_ENABLE_TF32=0 cargo test --profile test-fast --features cuda -p mlxcel --bin mlxcel generate_falcon_ocr -- --test-threads=1-> 20 passedMLX_ENABLE_TF32=0 cargo test --profile test-fast --features cuda -p mlxcel --test falcon_ocr_parity -- --test-threads=1-> 4 passedMLX_ENABLE_TF32=0 cargo test --profile test-fast --features cuda -p mlxcel --lib models::detection -- --test-threads=1-> 26 passedMLX_ENABLE_TF32=0 cargo test --profile test-fast --features cuda -p mlxcel --lib model_metadata -- --test-threads=1-> 8 passedMLX_ENABLE_TF32=0 cargo test --profile test-fast --features cuda -p mlxcel --lib models::metadata_tests -- --test-threads=1-> 4 passedcargo clippy --features cuda --lib --bins --tests -- -D warningscleancargo fmt --allcleancargo build --release --features cuda --bin mlxcelplus the two whole-page OCR runs and the five-region layout run aboveThe synthetic parity test covers the three pieces easiest to get subtly wrong without a crash: that the hybrid mask actually reaches SDPA (a hybrid prefill must differ from a causal one), that an incremental decode lands on the same logits as a single full-sequence pass (which is what catches a wrong rope delta, since the image block collapses ten sequence slots onto one temporal index), and that the sinks tensor is consumed rather than merely loaded.
Not verified
Multi-image prompts, quantized conversions (none exist yet; the
w13split handles the sidecars but is untested against a real quantized checkpoint), and concurrent server requests. The per-sequence state binding is wired the same way the Qwen-MRoPE and Gemma-4 binders are and is unit-tested, but was not exercised under a live multi-request server load.Layout DETECTION remains outside the tree, so
--layout-detectionscannot close the loop on its own: the boxes have to come from a detector mlxcel does not ship.mlxcel detectdoes load RT-DETRv2 checkpoints and its JSON is the format this flag consumes, but pointing it at the docling-layout-heron document-layout checkpoint on a rendered page returned boxes that do not correspond to the page content (apage_footerat[0, 103, 759, 124]on a 1000x1300 page whose footer sits at y=1220), so that pairing is not offered as a working recipe here. Whether that is a predictor bug, a preprocessing mismatch for this checkpoint family, or simply the wrong model for the input is a separate question from this issue and is worth its own investigation.The layout path also does not batch: the reference OCRs crops in chunks of 32, while this driver runs one region per generation. Region count is small for a page, so this is a throughput note rather than a correctness one.
Closes #848