Repository navigation
fix(detect): read RT-DETRv2 outputs by dtype instead of assuming f32 - #1127
Merged
Merged
Conversation
`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
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
mlxcel detectreturned boxes that matched no page content. The cause is the host readback inpredictor, 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 indexedquery * num_labelsandquery * 4into 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.jsonsetsdo_pad: falseand 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_valuesis cast to f32, but the first conv against a bf16 weight settles the graph back into bf16, sopred_logitsandpred_boxesare bf16 for the shipped checkpoints. bf16 is the high half of an f32, so a 4-byte little-endian parse over that buffer returnsn/2values 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(wasto_f32_vec) casts to f32 before reading raw bytes.predict_pathrejects a readback length mismatch instead of silently consuming a short buffer.decode_detectionsanddenormalize_boxare 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_detectionsstays a pure geometry filter mirroring the reference.docs/supported-models.md: document the pipe, the reading order, and the duplicate-label collapse.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, matchingRTDetrImageProcessor.post_process_object_detectionforuse_focal_loss=True, so one query clearing the threshold under several classes legitimately emits one detection per class sharing that query's box.detectstill 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
pictureandtextis 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-bf16checkpoint, 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: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 fmtmlxcel detectreproduced the defect before the change and returns content-aligned geometry after, on 1000x1300, 1300x1000, and 1000x1000 pagesmlxcel detect --format jsonoutput fed tomlxcel generate --layout-detections: parses, plans into reading-ordered regions with no repeats, and reaches the Falcon-OCR model gateNote 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_repeatspins the planned region list (order, per-element uniqueness, footer reaching the bottom of the page) against literaldetect --format jsonoutput.The broad
--lib vision::selector reports 3 failures on this box, confirmed identical on unmodifiedorigin/main, so they are pre-existing and unrelated.Closes #1089