Repository navigation
[models] Resolve ambiguous overlaps of split word crops by reading the region of each pair - #2231
Conversation
felixdittrich92
left a comment
There was a problem hiding this comment.
Thanks a lot for this: the analysis is thorough, the stand-in "spelling" recognizer is a great test tool, and the core idea (only an extra reading can count a repeated stretch) is right. I benchmarked it at scale, and I'd like to propose a change of approach that came out clearly better. I pushed a prototype you can test directly (details at the end).
Benchmark
All 7 pretrained recognizers, 24,326 crops wider than 8:1:
- real: every such crop of SROIE (13,623 lines), FUNSD (194), CORD (9);
- synthetic (30 fonts, 16–64 px, noise / JPEG / blur / spacing): 3,000 IDs with runs or patterns, 1,500 without, 800 separator rows, 1,500 amounts / dates / phone numbers / IBANs, 2,500 long words, 1,200 URLs.
Findings on this PR:
- The whole reading is often too squeezed to trust. The predictor keeps the aspect ratio, so a 20:1 crop reaches the model as a 128×6 px strip. On a real receipt, parseq turned a row of 24
*(right onmain) into 20–21, from a whole reading'insssesemmunussommuna'(conf 0.68). It shares no char with any candidate, so the edit distance just picks the shortest allowed one. Clean readings can also be confidently wrong:GSTID:000220499968is read whole asGSTID:0000220499968(conf 1.00). - Real data: across 7 archs, +12/−11 on SROIE (parseq +2/−7).
- Synthetic: many breaks for the transformer decoders (parseq −64, vitstr −44, master −85).
Proposed approach: per-pair region reading + geometry
- Find the pairs of neighbouring parts whose readings overlap exactly at several lengths (and where
merge_stringspicked one of them). - Read the region those two parts cover (≈ 9:1, far less squeezed than the whole crop), all pairs in one extra batch.
- Score each exact overlap length
nby two independent signals: the edit distance of its merge to the region reading, plus the mean distance (in chars) between the overlapping chars' positions in the two parts when each part's chars are spread evenly over its width. The part offsets are known exactly from the split. - Use the best length only if its merge is ≤ 2 edits from the region reading and its score beats
merge_strings' length by > 0.25. Otherwise keepmerge_strings.
Fixed / broken vs main, measured with the actual predictor:
| arch | this PR | proposed |
|---|---|---|
| parseq | +188 / −64 | +211 / −27 |
| crnn_vgg16_bn | +49 / −0 | +208 / −11 |
| crnn_mobilenet_v3_large | +22 / −0 | +178 / −10 |
| vitstr_small | +111 / −44 | +162 / −25 |
| sar_resnet31 | +45 / −4 | +136 / −29 |
| master | +91 / −85 | +94 / −38 |
| viptr_tiny | +43 / −1 | +211 / −14 |
| total | +549 / −198 | +1,200 / −154 |
| real (SROIE) | +12 / −11 | +20 / −1 (≥ 0 for every arch) |
- Validated: tuned on half of the synthetic crops, same result on the other half (+596/−73 vs +587/−79).
- Real documents: on 149 pages, parseq changes no word (the
*regression is gone), and crnn changes 1 (an edge-cut*row). - Cost: +5–12 % recognition time on split crops; end-to-end within noise.
- Simpler: no whole-crop reading, so no confidence floor and no ±1-length window. No
lengthen_onlyand no model imports in the predictor (it is arch-agnostic and works for CTC models without special-casing). No candidate search with a cap. Themax_lengthguard reduces to one comparison.
Things I tried that did not beat it, to save you iterations:
- changing the expected overlap (
- 2→- 1.5/- 1): −12 to −33 per arch; - lengthen-only everywhere: keeps parseq's real-data breaks, which are over-counts;
- geometry alone (no extra read): +943/−91 in total, a decent fallback;
- requiring the whole and the region readings to agree: safe, but fewer fixes at double the cost;
- giving the geometry less weight than the reading: 2–3× more breaks, because real readings are often one char off.
The one trade-off is that with a perfect reader (your stand-in) it fixes 330 of 529 misjoins rather than all of them, since geometry deliberately holds back a reading that disagrees with it. Your stand-in tests would need to reflect that. On real models this is what keeps the breaks down.
Prototype to test
Branch: https://github.com/felixdittrich92/doctr/tree/proto-split-merge-geo
Diff against main: main...felixdittrich92:doctr:proto-split-merge-geo
git fetch https://github.com/felixdittrich92/doctr.git proto-split-merge-geo
git checkout FETCH_HEADIt is one commit on top of main (~150 lines in 3 files):
doctr/models/recognition/utils.py:exact_overlaps, and an optionaloverlapsargument onmerge_multi_stringsto impose known overlap lengths;doctr/models/recognition/predictor/_utils.py:ambiguous_overlaps(finds the pairs and cuts their regions),resolve_overlap(the scoring above), andremap_predspassing the overlaps through;doctr/models/recognition/predictor/pytorch.py: the forward pass moved into_read, plusRecognitionPredictor(..., resolve_ambiguous_overlaps=True). Set it toFalseto getmain's behaviour exactly.
It passes ruff and the existing recognition tests, but has no new tests yet. It would be great if you could run it on your ID benchmark and the OnnxTR setup.
Requested changes
- Switch to the per-pair region reading + geometry scoring (feel free to take the prototype as a base), or show that it does worse on your data.
- Keep the predictor architecture-agnostic: no
CTCPostProcessor/SARPostProcessor/VIPTRPostProcessorimports. - Port your tests to it: the
merge/remapunit tests, plus the stand-in recognizer tests with expectations adjusted for the geometry term (for example, a reading that is off from the geometry by more than its edit-distance gain keepsmerge_strings' length). Also update the description and the "Very wide crops" docs section.
|
Please rebase your branch first on main before you apply any further changes :) |
ca4ef89 to
1485688
Compare
|
Thanks a lot for the thorough review and the prototype, the numbers are convincing.
One observation from the stand-in: when a part's edge cuts a character in half, the evenly spread positions are about half a character off. For example, on a 210 × 24 crop of I haven't run it in the OnnxTR setup yet. |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #2231 +/- ##
=======================================
Coverage 98.24% 98.25%
=======================================
Files 181 181
Lines 12799 12863 +64
=======================================
+ Hits 12575 12639 +64
Misses 224 224
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Across a repeated stretch, a run ("0000001") or a pattern ("EME" in
"ENDORSEMENT"), the readings of two neighbouring parts of a split crop
can match exactly at several overlap lengths. merge_strings then keeps
the length nearest to the one the overlap ratio predicts, which is
sometimes a character off, so the stretch gains or loses part of
itself even when both parts are read right.
- exact_overlaps lists the lengths at which two readings match.
- ambiguous_overlaps finds the pairs of parts that match at several
lengths, one of them the one merge_strings picks, and cuts the region
of the crop the two parts cover (at most 9:1). _split_starts is
factored out of _split_horizontally so the regions line up with the
parts.
- RecognitionPredictor reads all those regions in one extra batch. Its
forward pass moved into _read so that they take the same path.
- resolve_overlap scores each exact length by the edit distance of its
merge to the region reading, plus how far apart the overlapping chars
sit when the chars of each part are spread evenly over its width.
A length replaces merge_strings' one only if its merge is at most 2
edits from the region reading and it scores better by more than
0.25. A region reading of max_length - 2 chars or more may have been
cut short by the model and does not decide.
- merge_multi_strings and remap_preds take the resolved lengths through
a new overlaps argument, applied only while they are still exact
overlaps of the merge so far; every other pair is merged by
merge_strings as before.
- resolve_ambiguous_overlaps=False, an argument and attribute of
RecognitionPredictor, keeps the previous behaviour.
- exact_overlaps, and merge_multi_strings imposing known overlap lengths: an imposed length that is not an exact overlap of the merge so far falls back to merge_strings, and imposing merge_strings' own exact lengths merges as it does. - remap_preds applies the overlaps of each crop to that crop only. - ambiguous_overlaps finds the pairs whose readings overlap exactly at several lengths where merge_strings picks one, and cuts the region both parts cover, with the right ratio and offset for the last pair. - resolve_overlap: the region reading and the char positions agreeing, a reading matching merge_strings' length or more than 2 edits off, a tie between the two signals, and the margin. - RecognitionPredictor, with a stand-in recognizer that reads crops whose columns spell their chars exactly: a run split across parts is resolved with one extra batch; across ten strings at every split size, nothing merge_strings merges right is broken, and misjoins drop or vanish; a region reading cut short by the model's max_length keeps merge_strings' overlap; nothing is resolved with the switch off or for crops that are not split. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The user guide says how the parts of a split crop are merged, when a region is read once more, and how to switch that off. The cut-short guard's comment says why max_length - 2 suits every recognition model. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1485688 to
9819442
Compare
felixdittrich92
left a comment
There was a problem hiding this comment.
Thanks! The implementation looks good to me. The tests (+295 lines) can be cut down a lot without losing anything.
I tried a shorter version: +121 lines, run time 2.8 s → 0.05 s, same coverage of the added code (82/82 statements, 32/32 branches). I injected the faults from your mutation list plus a few more, one at a time: the current tests catch 19 of 21, the shorter ones all 21. The two that get through:
exact_overlapsdropping its longest length: no case has a part read entirely inside a run (("000X", "X0000") → [1, 2, 3]).- the cut-short guard one char stricter than
max_length - 2: only one side of the boundary is tested.
Requested changes:
- Replace the spelling stand-in (
_spelled,_ColumnsPreProcessor,_SpellingModel,_spelling_predictor,_split_sizesand the 5 tests using them) with a scripted mock and one parametrized test. The unit tests already pin regions, offsets, ratios and scores exactly. - Drop
test_merge_multi_strings_imposing_its_own_overlapsand the duplicate cases oftest_exact_overlaps/test_merge_multi_strings_overlaps. - Fold
test_resolve_overlap_marginintotest_resolve_overlap. - Keep comments and docstrings in the tests to the minimum.
tests/pytorch/test_models_recognition_pt.py:
class _ScriptedRecoModel(torch.nn.Module):
"""Reads the crops as the next `readings`: the parts with a confidence of 0.9, the regions of 0.1"""
def __init__(self, readings: list[str], max_length: int | None) -> None:
super().__init__()
self.dummy = torch.nn.Parameter(torch.zeros(1))
self.readings = iter(readings)
self.batch_sizes: list[int] = []
if max_length is not None:
self.max_length = max_length
def forward(self, x: torch.Tensor, return_preds: bool = False, **kwargs):
self.batch_sizes.append(x.shape[0])
conf = 0.9 if len(self.batch_sizes) == 1 else 0.1
return {"preds": [(next(self.readings), conf) for _ in range(x.shape[0])]}
# The parts of a 154 x 14 crop of "WARMUP-0000001": merge_strings adds a zero to the run
_PARTS = ["WARMUP-0", "MUP-00000", "-0000001"]
@pytest.mark.parametrize(
"width, readings, resolve, max_length, text, batch_sizes",
[
(154, [*_PARTS, "MUP-0000001"], True, 32, "WARMUP-0000001", [3, 1]),
(154, [*_PARTS, "MUP-0000001"], True, None, "WARMUP-0000001", [3, 1]),
# A region reading of `max_length - 2` chars or more may be cut short
(154, [*_PARTS, "MUP-0000001"], True, 13, "WARMUP-00000001", [3, 1]),
(154, [*_PARTS, "MUP-0000001"], True, 14, "WARMUP-0000001", [3, 1]),
(154, [*_PARTS, "MUP-00000001"], True, 32, "WARMUP-00000001", [3, 1]),
(154, _PARTS, False, 32, "WARMUP-00000001", [3]),
(154, ["WARMUP-1", "MUP-1234", "-1234567"], True, 32, "WARMUP-1234567", [3]),
(98, ["WARMUP-0000001"], True, 32, "WARMUP-0000001", [1]),
],
)
def test_recognition_predictor_resolve_ambiguous_overlaps(width, readings, resolve, max_length, text, batch_sizes):
model = _ScriptedRecoModel(readings, max_length)
predictor = RecognitionPredictor(
PreProcessor(output_size=(32, 128), batch_size=32, preserve_aspect_ratio=True),
model,
resolve_ambiguous_overlaps=resolve,
)
assert predictor([np.zeros((14, width, 3), dtype=np.uint8)]) == [(text, 0.9)]
assert model.batch_sizes == batch_sizestests/common/test_models_recognition_utils.py:
@pytest.mark.parametrize(
"a, b, lengths",
[
("WARMUP-0000", "-0000001", [1, 2, 3]),
("PARTICIP", "TICIPANTS", [1, 3]),
("000X", "X0000", [1, 2, 3]),
("hellowo", "loworld", [2]),
("a", "b", []),
],
)
def test_exact_overlaps(a, b, lengths):
assert exact_overlaps(a, b) == lengths
@pytest.mark.parametrize(
"overlaps, merged",
[
(None, "WARMUP-00000001"),
({1: 3}, "WARMUP-0000001"),
# Not an exact overlap of the merge so far: aligned by merge_strings
({1: 5}, "WARMUP-00000001"),
],
)
def test_merge_multi_strings_overlaps(overlaps, merged):
assert merge_multi_strings(["WARMUP", "MUP-0000", "-0000001"], 0.5, 0.519, overlaps) == mergedtests/common/test_models_recognition_predictor.py:
def test_remap_preds_overlaps():
preds = [("WARMUP", 0.9), ("MUP-0000", 0.8), ("-0000001", 0.7)] * 2
assert remap_preds(preds, [(0, 3, 0.519), (3, 6, 0.519)], 0.5, overlaps={(0, 1): 3}) == [
("WARMUP-0000001", 0.7),
("WARMUP-00000001", 0.7),
]
def test_ambiguous_overlaps():
crops = [np.zeros((32, 128, 3), dtype=np.uint8), np.arange(10 * 200 * 3, dtype=np.int64).reshape(10, 200, 3)]
# The second crop is split into 6 parts of 60 columns starting at 0, 30, 60, 90, 120 and 140
_, crop_map, _ = split_crops(crops, 8, 6, 0.5)
texts = ["single", "XY-0000", "-000000", "00001AB", "1ABCDEF", "GH00000", "0000000"]
pairs = ambiguous_overlaps([(text, 0.9) for text in texts], crop_map, crops, 6, 0.5)
assert [(key, a, b, ratio, offset) for key, _, a, b, ratio, offset in pairs] == [
((1, 0), "XY-0000", "-000000", 0.5, 0.5),
((1, 1), "-000000", "00001AB", 0.5, 0.5),
((1, 4), "GH00000", "0000000", pytest.approx(40 / 60), pytest.approx(20 / 60)),
]
for (_, region, *_), (start, end) in zip(pairs, [(0, 90), (30, 120), (120, 200)]):
np.testing.assert_array_equal(region, crops[1][:, start:end])
# merge_strings picks no exact overlap / the parts do not match the split
assert ambiguous_overlaps([("aaab", 0.9), ("baabbbbb", 0.9)], [(0, 2, 0.2)], [crops[1][:, :90]], 6, 0.5) == []
assert ambiguous_overlaps([(text, 0.9) for text in texts[:3]], [0, (1, 3, 0.5)], crops, 6, 0.5) == []
@pytest.mark.parametrize(
"a, b, overlap_ratio, offset, region_text, kwargs, length",
[
# The region reading and the char positions agree on 4, merge_strings picks 3 (score gap 1.28)
("MUP-00000", "-0000001", 2 / 3, 1 / 3, "MUP-0000001", {}, 4),
("MUP-00000", "-0000001", 2 / 3, 1 / 3, "MUP-0000001", {"margin": 1.3}, None),
("MUP-00000", "-0000001", 2 / 3, 1 / 3, "MUP-00000001", {}, None),
("MUP-00000", "-0000001", 2 / 3, 1 / 3, "XYZ", {}, None),
# The region reading points at 5, the char positions at merge_strings' 4: a tie keeps it
("U-000000000", "00000008911", 78 / 144, 66 / 144, "U-0000000008911", {"margin": 0}, None),
("hellowo", "loworld", 0.5, 0.5, "helloworld", {}, None),
("aaab", "baabbbbb", 0.2, 0.5, "aaabbbbb", {}, None),
],
)
def test_resolve_overlap(a, b, overlap_ratio, offset, region_text, kwargs, length):
assert resolve_overlap(a, b, overlap_ratio, offset, region_text, **kwargs) == lengthThe spelling stand-in and its sweep over split sizes give way to a scripted model and one parametrized predictor test, since the unit tests pin the regions, offsets, ratios and scores exactly. The random-input merge test and the duplicate cases are dropped, and the margin cases join test_resolve_overlap. The cases now also cover a part read entirely inside a run in exact_overlaps, the cut-short guard on both sides of max_length - 2, and the 2-edit limit on both sides. Co-Authored-By: felix <felixdittrich92@gmail.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Thanks, done in b7aea90 with your shorter suite, credited to you as co-author. One change: in I reran my fault list against it, extended with your two and a few boundary faults: 25 of 26 caught, against 20 of 25 for the old tests. The one left compares the margin with It's a separate commit on top so you can see the change. Happy to squash it into the test commit if you prefer. |
felixdittrich92
left a comment
There was a problem hiding this comment.
Thanks @pbstriker38 👍
Fixes #2229 (cross-linked as felixdittrich92/OnnxTR#129). Follow-up to #2153.
Rebuilt on the per-pair approach proposed in review: the branch is rebased on main, starts from your prototype commit
(same code, with a message describing the change), and adds tests, docs and a comment on top. Thanks for the prototype
and the benchmark!
The bug
RecognitionPredictorsplits word crops wider thancritical_ar(8:1) into overlapping parts, reads each part, andjoins the readings with
merge_strings. Across a repeated stretch, a run of one character (0000001) or a repeatingpattern (
EMEinENDORSEMENT,ICIinPARTICIPANTS), the overlap matches exactly at several lengths, andmerge_stringskeeps the one closest tolen(b) * overlap_ratio - 2. That estimate is sometimes a character off, sothe stretch gains or loses part of itself, even when every part is read right:
The fix
ambiguous_overlapsfinds the pairs of neighbouring parts whose readings overlap exactly at several lengths(
exact_overlaps), wheremerge_stringspicked one of them, and cuts the region the two parts cover (about 9:1).RecognitionPredictorreads all those regions in one extra batch.resolve_overlapscores each exact length by the edit distance of its merge to the region reading, plus how farapart the overlapping characters sit in the two parts when each part's characters are spread evenly over its width.
The best length replaces
merge_strings' one only if its merge is at most 2 edits from the region reading and itsscore is better by more than 0.25.
merge_multi_strings/remap_predstake the resolved lengths through a newoverlapsargument; every other pairis aligned by
merge_stringsas before.A region reading at least
model.max_length - 2characters long may have been cut short by the decoder and doesn'tdecide. The models are trained on words of up to
max_length - 2(PARSeq, MASTER, ViTSTR),max_length - 1(SAR) ormax_lengthcharacters (CRNN, VIPTR, whose CTC targets have no<eos>), so that is exact or more cautious for each.This replaces the first version of this PR, which re-read the whole crop and chose among merges of the whole crop.
Squeezed to the model input, a crop that wide read too unreliably (see the review); the region of a pair is far less
squeezed, and the character positions catch what its reading gets wrong.
API
RecognitionPredictor(..., resolve_ambiguous_overlaps=True), also an attribute;Falsegivesmain's behaviourexactly.
exact_overlaps(recognition/utils.py),ambiguous_overlapsandresolve_overlap(
recognition/predictor/_utils.py); an optionaloverlapsargument onmerge_multi_stringsandremap_preds.RecognitionPredictor._predictmoved into_read, so the regions go through the same path.Evidence
Rendered IDs and words, all 7 pretrained recognizers
Synthetic IDs (letters, digits,
-and/) and long words rendered with Pillow in 5 fonts (DejaVu Sans/Serif,Liberation Sans/Mono, Noto Sans Mono), crops 30–56 px high, a third of them blurred, all wider than 8:1. Exact-match
counts on
main→ this PR, with the first version of this PR for comparison:accommodation,MISSISSIPPI,www.committee.net, …) or on words with a periodic stretch (44:PARTICIPANTS,ENDORSEMENTS, …), forany arch. 4–11 of the 174 IDs and about a fifth of the double-letter words get a region read.
Private documents
On 578 pages of private scanned and born-digital business forms (665 crops wider than 8:1),
crnn_vgg16_bnandparseqread 47–48 regions, in 45–46 crops, and change no word. These documents hold few runs, so this only shows the change is safethere.
Stand-in recognizer (every part and region read exactly)
Ten strings, seven with a run or repeating pattern, at every size the predictor splits for heights 10–47 px and
characters 0.4–0.8 of the height wide: 213 of 2,130 crops misjoin on
main, 61 with this PR, and none is broken. The61 are the trade-off you described. For example, the 2 parts of a 210 × 24 crop of
U-0000000008911each cut a zero inhalf: the exact region reading points at an overlap of 5, the evenly spread positions at 4,
merge_stringspicked 4,and the tie keeps it. A character cut in half at a part's edge shifts the evenly spread positions by about half a
character; refining the position term for that might be a follow-up.
Tests
tests/common/test_models_recognition_utils.py:exact_overlaps, including a part read entirely inside a run, andmerge_multi_stringswith an imposed overlap, which falls back tomerge_stringswhen it is no longer an exactoverlap of the merge so far.
tests/common/test_models_recognition_predictor.py:remap_predswithoverlaps, applied to their own crop only;ambiguous_overlapson a crop split into 6 parts: the pairs, their regions, ratios (the last pair's included) andoffsets; nothing for a pair where
merge_stringspicks no exact length, or for a crop whose parts don't match itssplit;
resolve_overlap: the two signals agreeing, and the margin; a reading that matchesmerge_strings' length; the2-edit limit from both sides; the tie above, which keeps
merge_strings' length even with no margin; one exactlength only.
tests/pytorch/test_models_recognition_pt.py: one parametrized test ofRecognitionPredictorwith a scriptedrecognizer. A run split across parts is resolved with one extra batch of 1 region, and the confidence stays the
parts'. A region reading of
max_length - 2characters keepsmerge_strings' length and one ofmax_length - 3decides, and a model without
max_lengthis trusted. Nothing is read again withresolve_ambiguous_overlaps=False,without an ambiguous pair, or for a crop that is not split.
They run in 0.02 s and cover the added code fully (82/82 statements, 32/32 branches). Of 26 faults injected one at a
time, 25 are caught: among them never resolving, dropping the position term, the offset, the 2-edit limit or the margin,
moving the edit limit or the cut-short guard by one either way, breaking ties away from
merge_strings' length, a wrongregion, offset or last-pair ratio, missing a dropped part, applying one crop's overlaps to every crop, imposing a length
without checking it or off by one,
exact_overlapsdropping its longest length, changing the confidence when aregion is read, and ignoring the switch. The one left compares the margin with
>=, which differs only when thescore gap equals the margin exactly.
make styleandmake quality(ruff + mypy) are clean; the recognition test files pass.🤖 Generated with Claude Code