Repository navigation
[models] Fix SAR and MASTER accuracy: build a new activation module per layer instead of sharing a default instance - #2232
Conversation
There was a problem hiding this comment.
Thanks for tracking this down! I checked the root cause and the fix locally:
- On
main, theIntermediateLayerGetterin 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.
resnet31andmagc_resnet31are 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.
|
@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>
cf94540 to
de6963e
Compare
… were cancelled) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
On CI: the run on de6963e failed |
Codecov Report✅ All modified and coverable lines are covered by tests. 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
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:
|
felixdittrich92
left a comment
There was a problem hiding this comment.
Thanks @Zephyr4772 👍🏼 LGTM
Problem. Since #2063 (May 2026),
conv_sequence_pthas a default argumentactivation: nn.Module = nn.ReLU(inplace=True). That singleReLUinstance is shared by every layer built with the default. The ResNet31 stems unpackconv_sequence_pt(...)twice into onenn.Sequential, so the same module is registered twice at the top level. SAR and MASTER take their features throughIntermediateLayerGetter, which rebuilds the backbone fromnamed_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, becausenn.Sequential.forwarditerates repeated modules, so nothing else is affected.I found this in actual use: running
ocr_predictor(reco_arch="master")ondocs/source/_static/images/examples/invoice.pdfreturns "ACMIE Office Supplits / IN/N/OJUCE" instead of "ACME Office Supplies / INVOICE".git bisectbetween 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):mastersar_resnet31parseq(unaffected)Fix.
conv_sequence_pt:activationdefaults toNone, and each call builds its ownnn.ReLU(inplace=True). The docstring says that an explicitly passed activation must be a new instance per call.PositionwiseFeedForwardandEncoderBlock(modules/transformer) had the same default-instance pattern, andEncoderBlockpassed one activation to all of its layers. They now default toNone, andEncoderBlockgives 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,parseqandvitstr_smallhad 11 shared modules each andmaster2; 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 withIntermediateLayerGetterhas no missing layer index. Onmainthese fail forresnet31,magc_resnet31,sar_resnet31andmaster(train and eval); with this PR all 39 cases pass.test_conv_sequencealso checks that two calls build distinct activation modules.vit_s,vit_b,vip_tiny,vip_base,parseq,vitstr_small,masterandviptr_tiny. Earlier, every pretrained detection, recognition, layout, table and formula model was compared on main and with theconv_sequence_ptfix: onlysar_resnet31andmasterchange, andsar_resnet31then matches fb4bb21, the commit before [Feat] Add Vit-Det as LW-DETR encoder #2063, exactly.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 formatclean.AI assistance: Claude Code found the regression, bisected it, wrote the fix and tests, and ran the checks above.