Skip to content

fix(detect): read RT-DETRv2 outputs by dtype instead of assuming f32 - #1127

Merged
inureyes merged 1 commit into
mainfrom
fix/issue-1089-detect-tall-page-boxes
Aug 13, 2026
Merged

inureyes merged 1 commit into
mainfrom
fix/issue-1089-detect-tall-page-boxes

Conversation

@inureyes

Copy link
Copy Markdown
Member

Summary

mlxcel detect returned boxes that matched no page content. The cause is the host readback in predictor, not the coordinate mapping: the forward graph inherits the checkpoint dtype (bf16), but the readback parsed the raw buffer as 4-byte f32, fusing each adjacent pair of bf16 values into one bogus float and returning 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.

Root cause, and how it differs from the issue's hypothesis

The issue hypothesised that the letterbox/resize normalization was not being undone for tall aspect ratios. That is not what was wrong, and the aspect-ratio dependence was a coincidence of which garbage indices happened to survive: the same collapse reproduces on a square page.

There is no letterbox to undo. The checkpoint's own preprocessor_config.json sets do_pad: false and resizes straight to 640x640, so the forward transform is an independent per-axis scale and its inverse is the same independent per-axis scale. That code was already correct and is unchanged in behavior.

What was wrong sits one layer later. pixel_values is cast to f32, but the first conv against a bf16 weight settles the graph back into bf16, so pred_logits and pred_boxes are bf16 for the shipped checkpoints. bf16 is the high half of an f32, so a 4-byte little-endian parse over that buffer returns n/2 values that are the odd-indexed elements polluted with the even ones' bits. Three module doc comments asserted the whole graph ran in f32, which is what let the mismatch sit unnoticed; they now describe what actually happens.

What changed

  • src/vision/detection/rt_detr_v2/predictor.rs: read_output_f32 (was to_f32_vec) casts to f32 before reading raw bytes. predict_path rejects a readback 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.
  • src/vision/detection/rt_detr_v2/{mod,model,common}.rs: correct the doc comments that claimed the graph runs in f32.
  • src/commands/detect.rs: emit detections in reading order (top to bottom, then left to right) instead of descending confidence, as a strict total order with confidence and class id as tiebreaks.
  • src/vision/falcon_ocr_layout.rs: the region planner collapses same-box detections to one region, after the OCR category mapping. filter_nested_detections stays a pure geometry filter mirroring the reference.
  • docs/supported-models.md: document the pipe, the reading order, and the duplicate-label collapse.
  • Tests in src/vision/detection/rt_detr_v2/tests.rs, src/commands/detect_tests.rs, src/vision/falcon_ocr_layout_tests.rs, src/commands/generate_falcon_ocr_tests.rs.

Multi-label duplication: settled as intended head behavior

Confirmed intended, and kept. The top-K runs over the flattened (queries x labels) grid with no per-query argmax, matching RTDetrImageProcessor.post_process_object_detection for use_focal_loss=True, so one query clearing the threshold under several classes legitimately emits one detection per class sharing that query's box. detect still prints all of it.

It did have one real consequence, now fixed: the OCR planner would have transcribed such a region once per label. The planner collapses same-box entries to one region, after the category mapping so a box labelled both picture and text is read as text rather than dropped on the un-OCRable label.

Verification

Run on GB10 / CUDA sm_121 against the local docling-layout-heron-mlx-bf16 checkpoint, with PIL-drawn pages of known geometry.

Before, on the 1000x1300 portrait page, all detections shared one box (0.0, 0.0, 551.5, 658.6). After, each drawn element gets its own box on its own content:

section_header  0.706    80.08    60.14   771.48   108.70   <- heading drawn at x 80, y 55-105
section_header  0.798    72.27   152.66   462.89   185.03
text            0.947    58.59   213.28   957.03   426.56
section_header  0.712    81.05   482.42   512.70   512.89
text            0.926    64.45   541.46   943.36   717.92
text            0.808    72.27   825.20   958.98   962.30

A footer drawn at x 80, y 1200 on the same tall page returns page_footer 0.51 (78.13, 1200.34)-(671.88, 1237.16).

Test plan

  • cargo test --profile test-fast --features cuda --lib vision::detection::rt_detr_v2 (30 passed)
  • cargo test --profile test-fast --features cuda --lib vision::falcon_ocr_layout (15 passed)
  • cargo test --profile test-fast --features cuda --bin mlxcel commands:: (158 passed)
  • cargo clippy --profile test-fast --features cuda --lib --bin mlxcel (clean)
  • cargo fmt
  • mlxcel detect reproduced the defect before the change and returns content-aligned geometry after, on 1000x1300, 1300x1000, and 1000x1000 pages
  • mlxcel detect --format json output fed to mlxcel generate --layout-detections: parses, plans into reading-ordered regions with no repeats, and reaches the Falcon-OCR model gate

Note on the last item: this box has no Falcon-OCR checkpoint, so the OCR decode itself was not executed. Everything up to it was: the detector JSON is accepted verbatim, and detect_json_plans_into_reading_ordered_regions_without_repeats pins the planned region list (order, per-element uniqueness, footer reaching the bottom of the page) against literal detect --format json output.

The broad --lib vision:: selector reports 3 failures on this box, confirmed identical on unmodified origin/main, so they are pre-existing and unrelated.

Closes #1089

`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 added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:medium Medium priority area:models Model architectures, weights, loading, metadata status:done Completed and removed status:review Under review labels Aug 13, 2026
@inureyes
inureyes merged commit 261407f into main Aug 13, 2026
7 checks passed
@inureyes
inureyes deleted the fix/issue-1089-detect-tall-page-boxes branch August 19, 2026 10:49
@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#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:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(detect): docling-layout-heron boxes miss page content on tall pages

1 participant