Skip to content

[models] Fix SAR and MASTER accuracy: build a new activation module per layer instead of sharing a default instance - #2232

Merged
felixdittrich92 merged 2 commits into
mindee:mainfrom
Zephyr4772:fix/conv-sequence-shared-relu
Nov 19, 2026
Merged

felixdittrich92 merged 2 commits into
mindee:mainfrom
Zephyr4772:fix/conv-sequence-shared-relu

Conversation

@Zephyr4772

@Zephyr4772 Zephyr4772 commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Problem. Since #2063 (May 2026), conv_sequence_pt has a default argument activation: nn.Module = nn.ReLU(inplace=True). That single ReLU instance is shared by every layer built with the default. The ResNet31 stems unpack conv_sequence_pt(...) twice into one nn.Sequential, so the same module is registered twice at the top level. SAR and MASTER take their features through IntermediateLayerGetter, which rebuilds the backbone from named_children(). That keeps a repeated module only once, so each model loses exactly one ReLU: top-level child "5", after the second stem conv/BN. The ReLUs inside the stages still run, because nn.Sequential.forward iterates repeated modules, so nothing else is affected.

I found this in actual use: running ocr_predictor(reco_arch="master") on docs/source/_static/images/examples/invoice.pdf returns "ACMIE Office Supplits / IN/N/OJUCE" instead of "ACME Office Supplies / INVOICE". git bisect between v1.0.1 and main points to 53c58dc (#2063). The bug is in the v1.1.0 release.

Impact, word accuracy on IIIT5K test (3,000 words, recognition_predictor, case-sensitive):

model main this PR
master 67.8% 76.7%
sar_resnet31 64.1% 76.1%
parseq (unaffected) 76.7% 76.7%

Fix.

  • conv_sequence_pt: activation defaults to None, and each call builds its own nn.ReLU(inplace=True). The docstring says that an explicitly passed activation must be a new instance per call.
  • PositionwiseFeedForward and EncoderBlock (modules/transformer) had the same default-instance pattern, and EncoderBlock passed one activation to all of its layers. They now default to None, and EncoderBlock gives each layer its own copy. Their outputs do not change (activations hold no state), but no backbone shares a module any more: vit_s, vit_b, parseq and vitstr_small had 11 shared modules each and master 2; all now have 0.

Validation.

  • test_classification_architectures: every top-level layer is its own module (len(list(model.named_children())) == len(model._modules)). test_recognition_models: a feature extractor built with IntermediateLayerGetter has no missing layer index. On main these fail for resnet31, magc_resnet31, sar_resnet31 and master (train and eval); with this PR all 39 cases pass. test_conv_sequence also checks that two calls build distinct activation modules.
  • Raw outputs on a fixed input are unchanged by the transformer change for vit_s, vit_b, vip_tiny, vip_base, parseq, vitstr_small, master and viptr_tiny. Earlier, every pretrained detection, recognition, layout, table and formula model was compared on main and with the conv_sequence_pt fix: only sar_resnet31 and master change, and sar_resnet31 then matches fb4bb21, the commit before [Feat] Add Vit-Det as LW-DETR encoder #2063, exactly.
  • Rebased on main (0c5b013). pytest tests/pytorch/test_models_utils_pt.py tests/pytorch/test_models_classification_pt.py tests/pytorch/test_models_recognition_pt.py: 142 passed. tests/common/test_utils_geometry.py (the job that failed before the rebase): 44 passed. ruff check / ruff format clean.

AI assistance: Claude Code found the regression, bisected it, wrote the fix and tests, and ran the checks above.

@felixdittrich92 felixdittrich92 self-assigned this Nov 19, 2026
@felixdittrich92 felixdittrich92 added this to the 1.2.0 milestone Nov 19, 2026
@felixdittrich92 felixdittrich92 added type: bug Something isn't working module: models Related to doctr.models ext: tests Related to tests folder framework: pytorch Related to PyTorch backend topic: text recognition Related to the task of text recognition labels Nov 19, 2026

@felixdittrich92 felixdittrich92 left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for tracking this down! I checked the root cause and the fix locally:

  • On main, the IntermediateLayerGetter in SAR and MASTER drops child "5", the ReLU after the second stem conv/BN. With this PR it's back.
  • The state dict keys don't change, so existing checkpoints load the same way.
  • resnet31 and magc_resnet31 are the only backbones with a repeated top-level module, so no other model's output changes.

The fix itself looks good to me. I'm requesting changes mainly for the tests and the docs.

1. Extend the existing tests instead of adding a new test function

test_intermediate_layer_getter_keeps_every_layer reimplements IntermediateLayerGetter by hand, hardcodes "10" and only covers the two ResNet31 variants. The root cause is simpler than that: a backbone must never register the same module twice at the top level. We can check that for every backbone with one assertion in test_classification_architectures, and then remove the new test function:

# tests/pytorch/test_models_classification_pt.py
def test_classification_architectures(arch_name, input_shape, output_size):
    # Model
    model = classification.__dict__[arch_name](pretrained=True).eval()
    _test_classification(model, input_shape, output_size)
    # SAR, MASTER, ... rebuild their backbone with IntermediateLayerGetter, which iterates named_children() and so keeps
    # a module shared between top-level layers only once: every top-level layer must be its own module
    assert len(list(model.named_children())) == len(model._modules)
    ...

We should also test the models users actually run. All feature extractors built with IntermediateLayerGetter use the layer names "0", "1", …, so a dropped layer shows up as a gap in the numbering:

# tests/pytorch/test_models_recognition_pt.py
from torchvision.models._utils import IntermediateLayerGetter

def test_recognition_models(arch_name, input_shape, train_mode, mock_vocab):
    batch_size = 4
    model = recognition.__dict__[arch_name](vocab=mock_vocab, pretrained=True, input_shape=input_shape)
    model = model.train() if train_mode else model.eval()
    assert isinstance(model, torch.nn.Module)
    # A backbone layer shared with an earlier one is dropped by IntermediateLayerGetter: no layer index may be missing
    if isinstance(model.feat_extractor, IntermediateLayerGetter):
        assert list(model.feat_extractor) == [str(idx) for idx in range(len(model.feat_extractor))]
    ...

On main, these assertions fail for resnet31, magc_resnet31, sar_resnet31 and master (both train and eval mode). With your fix they pass for every model. Your extension of test_conv_sequence is fine as it is.

2. Document that an explicitly passed activation must be a new instance

Callers can still bring the bug back by passing one instance to several calls. Please say so in the docstring:

        activation: the activation layer to be added if act is True. Defaults to a new ``nn.ReLU(inplace=True)``
            per call. When passing one, use a new instance per call: a module shared between layers is kept only
            once by ``named_children`` (e.g. in ``IntermediateLayerGetter``)

3. Nit: wording in the commit message / PR title

"lost activations" is plural, but each model loses exactly one: top-level child "5". The ReLUs inside the stages still run, because nn.Sequential.forward iterates repeated modules. Saying so would make it clearer that the fix can't affect anything else.

4. Optional: the same pattern in modules/transformer/pytorch.py

PositionwiseFeedForward and EncoderBlock also default to a module instance (activation_fct=nn.ReLU()). In addition, EncoderBlock passes one activation to all its layers, so vit_s and vit_b share one nn.GELU across every encoder layer. It doesn't change outputs today, because the shared module isn't a top-level child and activations hold no state. It is the same trap, though, and it also affects forward hooks and quantization fusion. If you'd like to fix it here (otherwise a follow-up issue is fine):

from copy import deepcopy

class PositionwiseFeedForward(nn.Sequential):
    def __init__(
        self, d_model: int, ffd: int, dropout: float = 0.1, activation_fct: Callable[[Any], Any] | None = None
    ) -> None:
        super().__init__(  # type: ignore[call-overload]
            nn.Linear(d_model, ffd),
            nn.ReLU() if activation_fct is None else activation_fct,
            nn.Dropout(p=dropout),
            nn.Linear(ffd, d_model),
            nn.Dropout(p=dropout),
        )

# EncoderBlock.__init__: activation_fct: Callable[[Any], Any] | None = None
        self.position_feed_forward = nn.ModuleList([
            # deepcopy: one activation module per layer instead of one shared by all of them
            PositionwiseFeedForward(d_model, dff, dropout, deepcopy(activation_fct))
            for _ in range(self.num_layers)
        ])

With this change, no classification backbone shares a module anywhere, and the classification and recognition tests still pass.

@felixdittrich92

Copy link
Copy Markdown
Collaborator

@Zephyr4772 Please rebase on main before. Thanks 😃

…ault instance

conv_sequence_pt defaulted to one nn.ReLU instance shared by every layer built
with it. The ResNet31 stems register it twice at the top level, and
IntermediateLayerGetter rebuilds the SAR and MASTER backbones from
named_children(), which keeps a repeated module once: each of these models lost
exactly one ReLU, top-level child 5 after the second stem conv/BN. The ReLUs
inside the stages still ran, since nn.Sequential.forward iterates repeated
modules.

PositionwiseFeedForward and EncoderBlock had the same default-instance pattern,
and EncoderBlock shared one activation across all of its layers. Their outputs
do not change, but no backbone shares a module any more.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Zephyr4772
Zephyr4772 force-pushed the fix/conv-sequence-shared-relu branch from cf94540 to de6963e Compare November 19, 2026 17:16
@Zephyr4772 Zephyr4772 changed the title [models] Fix SAR and MASTER accuracy: build a new ReLU per conv_sequence_pt call [models] Fix SAR and MASTER accuracy: build a new activation module per layer instead of sharing a default instance Nov 19, 2026
… were cancelled)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Zephyr4772

Copy link
Copy Markdown
Contributor Author

On CI: the run on de6963e failed test_read_html and test_document_file in pytest-common with HTTP 429 from https://www.google.com (823 other tests passed), and build (macos-latest, 3.13/3.14) were cancelled before running tests. I pushed an empty commit to rerun them; if the 429 comes back, a rerun of that job should clear it.

@codecov

codecov Bot commented Nov 19, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.24%. Comparing base (0c5b013) to head (7024981).

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2232   +/-   ##
=======================================
  Coverage   98.24%   98.24%           
=======================================
  Files         181      181           
  Lines       12798    12799    +1     
=======================================
+ Hits        12574    12575    +1     
  Misses        224      224           
Flag Coverage Δ
unittests 98.24% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@felixdittrich92 felixdittrich92 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @Zephyr4772 👍🏼 LGTM

@felixdittrich92
felixdittrich92 merged commit 9553cb6 into mindee:main Nov 19, 2026
60 of 61 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ext: tests Related to tests folder framework: pytorch Related to PyTorch backend module: models Related to doctr.models topic: text recognition Related to the task of text recognition type: bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants