Skip to content

feat(models): add Falcon-OCR (falcon_ocr) early-fusion VLM support - #1075

Merged
inureyes merged 5 commits into
mainfrom
feature/issue-848-falcon-ocr-vlm
Aug 7, 2026
Merged

inureyes merged 5 commits into
mainfrom
feature/issue-848-falcon-ocr-vlm

Conversation

@inureyes

@inureyes inureyes commented Aug 7, 2026 •

Copy link
Copy Markdown
Member

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 #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

  • MLX_ENABLE_TF32=0 cargo test --profile test-fast --features cuda -p mlxcel --lib falcon_ocr -- --test-threads=1 -> 57 passed
  • MLX_ENABLE_TF32=0 cargo test --profile test-fast --features cuda -p mlxcel --bin mlxcel generate_falcon_ocr -- --test-threads=1 -> 20 passed
  • MLX_ENABLE_TF32=0 cargo test --profile test-fast --features cuda -p mlxcel --test falcon_ocr_parity -- --test-threads=1 -> 4 passed
  • MLX_ENABLE_TF32=0 cargo test --profile test-fast --features cuda -p mlxcel --lib models::detection -- --test-threads=1 -> 26 passed
  • MLX_ENABLE_TF32=0 cargo test --profile test-fast --features cuda -p mlxcel --lib model_metadata -- --test-threads=1 -> 8 passed
  • MLX_ENABLE_TF32=0 cargo test --profile test-fast --features cuda -p mlxcel --lib models::metadata_tests -- --test-threads=1 -> 4 passed
  • cargo clippy --features cuda --lib --bins --tests -- -D warnings clean
  • cargo fmt --all clean
  • 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 #848

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
@inureyes inureyes added type:enhancement New features, capabilities, or significant additions priority:medium Medium priority area:models Model architectures, weights, loading, metadata status:review Under review labels Aug 7, 2026
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
@inureyes

inureyes commented Aug 7, 2026

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Add native falcon_ocr support: an early-fusion, vision-tower-free OCR VLM whose 16x16 patches are linearly projected into the token stream and read by one 22-layer decoder under a hybrid bidirectional-in-image / causal-elsewhere mask.

Reviewed against the checkpoint's own vendor code (modeling_falcon_ocr.py, attention.py, rope.py, processing_falcon_ocr.py) as the authority, with mlx-vlm as a secondary reference, plus real-checkpoint CLI and server runs on GB10 (CUDA sm_121, release).

Findings Addressed

  • Server path skipped all 22 decoder layers (CRITICAL) - fixed in 95738d87

    sequence_state_layout() was not overridden. The trait default infers the layout from supports_batching(), so returning false made the scheduler allocate SequenceStateLayout::model_owned, whose external cache vector is empty. forward_impl walks self.layers.iter().zip(caches.iter_mut()), so the loop ran zero times and the LM head read the raw token embedding. No panic, no log line. 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; the CLI was unaffected because it builds its own caches from make_caches(). Text-only server requests were equally broken.

    Fix declares SequenceStateLayout::dense_kv_cache(n_layers) on FalconOcrTextModel and delegates it from FalconOcrVlModel, mirroring the identical override on Phi4MM (src/vision/phi4mm_vl.rs:629), which declines batching for an unrelated reason and hits the same default. Two regression tests were added: one pins the declared layout on both types, one asserts a forward handed an empty cache slice does not match a real one, so the layer loop stays observable.

    After the fix the server reproduces the CLI byte for byte, and an image -> text-only -> different image -> same image request sequence keeps every response correct.

Remaining Items

  • Reference prompt is missing the newline before <|OCR_PLAIN|> (MEDIUM) - src/multimodal/falcon_ocr_prompt.rs:104. Upstream builds f"<|image|>{instruction}\n<|OCR_PLAIN|>"; the task token is appended directly here, so the shipped tokenizer's newline token is absent. Measured impact on this checkpoint is nil (a run with an explicit trailing newline in -p produced byte-identical output), but it is a real divergence in the primary path. Fixing it needs a newline token id plumbed from the loader.
  • VLM prefix-cache continuation loses the positional state (MEDIUM) - src/models/falcon_ocr.rs:282. Under --enable-vlm-prefix-cache (off by default, experimental) an adopted whole-entry prefix feeds only the appended suffix to forward. take_for_prefill compares against the full-prompt length, evicts, and falls back to contiguous positions, discarding the image-dependent negative rope_delta for the rest of the request. Either slice the stored positions by the adopted offset or exclude Falcon-OCR from vlm_prefix_sharing_allowed the way Phi4MM already is.
  • Preemption drops the positional state (MEDIUM) - src/vision/falcon_ocr.rs:205. With --enable-preemption (off by default) an evicted sequence reaches release_sequence_state_by_id, which removes its only copy. The scheduler snapshots and reinstalls equivalent state for Qwen MRoPE and Gemma 4; Falcon-OCR has no equivalent, so a re-prefilled victim runs on contiguous positions.
  • src/vision/falcon_ocr_layout.rs is not reachable from any code flow (MEDIUM). Nothing outside src/vision/mod.rs:45 references it. This is honestly documented in the PR body and the module docs (the PP-DocLayoutV3 detector that would feed it is a separate architecture and is out of scope), so it is blocked on a missing dependency rather than merely unwired, but issue feat(models): add Falcon OCR (falcon_ocr) VLM support #848 lists layout post-processing as its own acceptance item. A follow-up issue for the detector plus the CLI surface would close it.
  • OcrCategory::parse documents an --ocr-category flag that does not exist (LOW) - src/vision/falcon_ocr_layout.rs:75.
  • build_hybrid_mask omits the reference's document-boundary term (LOW) - src/models/falcon_ocr_rope.rs:179. attention.py ANDs a cumsum(tok == eos_id) segmentation into the causal term. It is a no-op for a single unpadded sequence that carries no <|end_of_text|> (id 11), which is the case mlxcel prefills, so this is a documented-scope reduction rather than a bug; worth a note in the doc comment.
  • KV memory estimate is 2x low (LOW). K and V are correctly expanded to n_heads before the rotary (the spatial rotary is per-head), so the cache holds 16 heads, but resolve_num_kv_heads reads n_kv_heads: 8. Immaterial at 300M (about 1.5 GB vs 0.75 GB at 8k context).
  • Mask tests cover one image only (LOW). Multi-image and image-at-end-of-prompt are not exercised. The implementation is correct for them by construction (block_of is literally acc_soi * ((acc_soi - acc_eoi) > 0)), and a multi-image CLI run behaved correctly, but the cases deserve a test.

Verdicts on the focus areas

1. Cross-cutting generation-state change: no regression risk. The PR does not touch shared generation code for this. reset_runtime_state is a no-op trait default (src/lib/mlxcel-core/src/generate.rs:496); not overriding it changes nothing for any other family, and every model that needs it (Qwen MRoPE, Gemma 3/4, Llama 4, Qwen3-Next, AFMoE, ...) keeps its own override. CxxGenerator::reset_with_model is indeed called after the image stage writes state and before prefill consumes it, so the staleness-at-the-prefill-boundary design is the right shape.

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-SequenceId map immediately after preparation (scheduler.rs:3248), so a following text-only request resolves to nothing and gets contiguous positions. The residual hazard is a stale fallback whose length coincidentally equals a following text-only prompt, which is unreachable in-tree because the fallback is always drained by the bind. The two genuine lifecycle gaps are the prefix-cache and preemption items above, both behind default-off flags.

2. Non-parametric RMSNorm eps: both claims correct. modeling_falcon_ocr.py uses F.rms_norm(x, (x.size(-1),)) with no weight and no eps at every pre-norm: the attention input (line 140), the per-head Q and K norms (145-146), and the FFN input (230). The only parametric norm is self.norm = nn.RMSNorm(config.dim, eps=config.norm_eps) (339), which is where norm_eps belongs and where the PR applies it. Keeping f32::EPSILON for the weightless norms rather than 1e-5 is the right call: note that mlx-vlm's language.py uses rms_norm_eps for all of them, so this deliberately follows the vendor code over the port. (The exact PyTorch eps=None constant is a doc-level detail; at f32 activation scale the choice between finfo(f32).eps and finfo(f64).eps is below representable precision either way, while 1e-5 is about 40x f32 eps.)

3. Hybrid mask: correct, and the tests do not validate the bug against itself. Derived independently from attention.py::get_image_prefix_mask_mod: with inclusive cumsums, img_mask = (acc_soi - acc_eoi) > 0 puts <|image_cls|> (soi is image_cls_token_id, not img_start_id) inside the bidirectional block and <|end_of_image|> outside it, and img_indices = acc_soi * img_mask keys the block. build_hybrid_mask computes exactly that and ORs it with causal, matching or_masks(image_prefix_mask_mod, block_causal_mask_mod) modulo the document and left-pad terms, which are constant for a single unpadded sequence. The reference_allowed helper in falcon_ocr_rope_tests.rs:116 is a genuine independent re-derivation from the rule and agrees with mine. Multi-image and image-at-end are correct by the same construction (no case analysis needed) but untested; a multi-image CLI run produced 1067 patch tokens across two blocks and behaved correctly.

Other focus areas

  • 4. w13 de-interleaving: correct. The reference triton kernel reads gate_idx = 2 * col / up_idx = 2 * col + 1 over the w13 output features, so gate is the even rows of [4608, 768] and up the odd rows. sanitize_falcon_ocr_weights reshapes to [2304, 2, 768] and takes index 0 as gate, 1 as up, matching both the kernel and mlx-vlm's concatenate([v[0::2], v[1::2]]). Sidecar split for a future quantized conversion is on the right (row) axis.
  • 5. 3-D rotary and freqs_cis_golden: correct. Low half takes the 1-D temporal rotary over precompute_freqs_cis(head_dim/2), high half the 2-D golden rotary contracted as theta[t,h,f] = h_pos * G[h,f,0] + w_pos * G[h,f,1] against the shipped [16,16,2] table; both interleaved-pair, matching view_as_complex(x.reshape(..., -1, 2)). Text tokens get (0, 0) instead of the reference's NaN-masked scatter, which is the same rotation (identity), and decode skips the golden branch exactly as freqs_cis_2d = None does upstream. Temporal positions match get_pos_thw: image_cls advances the counter, the four registers, the patches and <|end_of_image|> all hold it, so a whole block collapses onto one index.
  • 6. Attention sinks: correct. The reference's sigmoid(lse - sinks) * output is algebraically an extra logit column in the softmax denominator, which is what mx.fast.scaled_dot_product_attention(..., sinks) implements, and K/V are expanded to n_heads before the rotary because the spatial frequencies are per-head. The parity test proves the tensor is consumed rather than merely loaded.
  • 7. Chunked prefill: no conflict. supports_chunked_prefill() is false on both types and effective_prefill_chunk honors it (generate.rs:1225, :1921); the embeddings paths never chunk. Verified empirically: MLXCEL_PREFILL_CHUNK=128 on a 566-token image prompt produced byte-identical output. The server gates on seq.vlm_embeddings.is_none() instead, so image requests always take the full-prefill path; a long text-only prompt can still be chunked there despite the flag, which is harmless for this model (contiguous positions, causal mask) but is a general server-gate asymmetry.
  • 8. Integration and reuse: complete after the fix. Detection arm, for_each_model_registration!, LoadedModel, VlmRuntimeRef, loader route, generate_vlm summary, TP arch string, scheduler binder and docs are all wired, and the diff is purely additive to the control plane. Reuses vision::merge::merge_llava, UnifiedLinear/UnifiedEmbedding, fast_rms_norm_no_weight, the gpt-oss sink SDPA entry point and create_causal_mask rather than reimplementing them. No placeholder, mock or TODO stub anywhere in the diff.

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow (CLI and server both verified on the real checkpoint after the fix)
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass: falcon_ocr lib 56, falcon_ocr_parity 6, models::detection 26, model_metadata 8, models::metadata_tests 4; clippy and rustfmt clean

`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
@inureyes

inureyes commented Aug 7, 2026

Copy link
Copy Markdown
Member Author

Security and performance review

Reviewed d5922eca against main 8309a3b0, focused on the new untrusted-input parser, the image and patch geometry, the rotary index safety, the per-region driver's resource behavior, and the decode hot path. Two HIGH findings, both fixed on this branch (ad604cb0, 23be5416). No CRITICAL.

HIGH: unbounded memory and CPU amplification in --layout-detections (fixed, ad604cb0)

Per-entry validation was solid; the aggregate level had no bound at all.

The load-bearing one was lifetime, not count: plan_layout_regions materialized one full DynamicImage crop per surviving detection and held them all before the first OCR token. crop_imm copies, and the shared image admission limits allow a 512 MB decoded page, so a few kilobytes of JSON listing twenty whole-page boxes cost roughly 10 GB of resident memory up front. Alongside that, load_layout_detections read the file with an unbounded read_to_string, the entry count was uncapped over an O(n^2) nested-box suppression, and the class name (arbitrary attacker-controlled text) was echoed verbatim to the terminal in the summary's no text category: list with no length bound and no control-character rejection, which made it an escape-sequence injection channel.

Fixes: crop_region split into a crop_rect geometry predicate plus the crop, a new plan_layout_region_boxes planning into a LayoutOcrPlan that carries the rect instead of the pixels, and the driver cutting each region inside its own loop so peak image memory is the page plus one crop for any entry count. plan_layout_regions now delegates to the same planner so the two cannot drift. Plus a 32 MiB bounded read (enforced on bytes actually read, since metadata().len() is zero for a fifo), a 4096-entry cap checked before the Detection vector is built, and a 64-character control-character-free class name.

HIGH: per-token clone and device-array copy in the decode hot path (fixed, 23be5416)

forward_impl runs on every decode step and 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 across the FFI boundary. Both were discarded. The l == 1 arm reads only the scalar rope_delta, and golden is unconditionally None there. With an image prompt of thousands of tokens this made decode O(prompt_len) per token, so total decode cost was quadratic in prompt length, on both the CLI and the server path.

Fixed with a borrow-based with_entry accessor (the pattern qwen_mrope_state.rs already uses) and a decode_rope_delta built on it. take_for_prefill now compares the stashed length through the borrow and duplicates only on a match, and the prefill arm consumes positions by value. Behavior is bit-identical, including the degenerate l == 0 case.

Verified, not a finding

  • Every crop reaching image indexing is clamped to real bounds before it becomes a slice or an MLX shape. crop_rect clamps to [0, w] / [0, h], rejects x2 <= x1 / y2 <= y1, and crop_imm clamps again. Negative, inverted, zero-area-after-clamping, off-page and larger-than-image boxes all resolve to a rejection or a clamp, never to an out-of-range index.
  • The 2-D spatial rotary does not index freqs_cis_golden. golden_cos_sin contracts it as a broadcast multiply-add (the reference's einsum("bsp,hfp->bshf")), so there is no gather to go out of range for a large image, and the (h, w) coordinates are a bounded centered linspace independent of absolute image size.
  • No per-region state leak. Each region gets a fresh session and KV cache from generate_with_embeddings, and the prefill state is rewritten per region by input_embeddings, with take_for_prefill evicting on a prompt-length mismatch. Region K cannot see region K-1's context.
  • The sequence_state_layout override that fixed the earlier zero-decoder-layers CRITICAL is intact on both FalconOcrTextModel and FalconOcrVlModel, and is pinned by the_declared_sequence_state_layout_is_a_dense_cache_per_layer.
  • Processor geometry is bounded. min_dimension / max_dimension / min_pixels / max_pixels come from Default, not from config.json, so a hostile config cannot drive the patch budget; spatial_patch_size goes through .max(1) at construction, and the zero-config divisions resolve to a clamp rather than a panic.
  • One region per generation instead of the reference's chunks of 32 is a throughput note only. With the crop now cut lazily it is also the memory-cheaper shape.

Remaining, not fixed

  • filter_nested_detections still runs twice per page (once in the driver for the summary, once inside the planner). With the 4096-entry cap that is bounded to a sub-second pass, so it is a tidiness item rather than a DoS.
  • A box that survives suppression and has a text category but is then rejected by the crop viability rules is dropped without its own line in the summary. The region count still reflects it, so nothing is hidden, but the reason is not stated.
  • label_id that is negative or non-integer silently defaults to 0 instead of being rejected by index like every other field. label is unused downstream.
  • When a seq_id is supplied but has no entry in the per-sequence map, resolve falls back to the shared CLI slot. This matches the existing Qwen-MRoPE and Gemma-4 binders, and take_for_prefill's length check narrows the window further, so it is noted rather than changed here.

Verdict on the --layout-detections parser's input validation

Per-entry validation is complete, not representative. Every reachable path was traced: top-level shape, entry type, class-name presence and type across all four alias keys, bounding-box presence and type across all three alias keys and both spellings, exact arity for the array form, per-axis numeric type, finiteness checked after the f32 downcast (so a large exponent that overflows to infinity is caught), and the inverted-or-empty geometry rejection. No malformed value reaches arithmetic or indexing, and serde_json's 128-deep recursion limit covers nesting. The gaps were all at the aggregate level (file size, entry count, class-name length and control characters) and are now closed.

Verification

MLX_ENABLE_TF32=0 cargo test --profile test-fast --features cuda -p mlxcel on GB10 / CUDA sm_121, --test-threads=1:

  • --bin mlxcel generate_falcon_ocr: 26 passed (was 20)
  • --lib falcon_ocr: 61 passed (was 57)
  • --test falcon_ocr_parity: 6 passed, including incremental_decode_matches_a_full_sequence_pass, which is the gate on the rope delta the decode restructure touched
  • cargo clippy --features cuda --lib --bins --tests -- -D warnings: clean

@inureyes inureyes added status:done Completed and removed status:review Under review labels Aug 7, 2026
@inureyes
inureyes merged commit 6029c96 into main Aug 7, 2026
7 checks passed
@inureyes
inureyes deleted the feature/issue-848-falcon-ocr-vlm branch August 7, 2026 12:51
inureyes added a commit that referenced this pull request Aug 7, 2026
…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.
inureyes added a commit that referenced this pull request Aug 13, 2026
…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
@inureyes inureyes self-assigned this Aug 27, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…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
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…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.
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:models Model architectures, weights, loading, metadata priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(models): add Falcon OCR (falcon_ocr) VLM support

1 participant