{"record":{"id":"e3c79f8264c3d577","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"return-layers-are-not-present-in-model","errorCode":null,"errorMessage":"return_layers are not present in model","messagePattern":"return_layers are not present in model","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pytorch_object_detection/faster_rcnn/backbone/feature_pyramid_network.py","lineNumber":34,"sourceCode":"    This means that one should **not** reuse the same nn.Module\n    twice in the forward if you want this to work.\n    Additionally, it is only able to query submodules that are directly\n    assigned to the model. So if `model` is passed, `model.feature1` can\n    be returned, but not `model.feature1.layer2`.\n    Arguments:\n        model (nn.Module): model on which we will extract the features\n        return_layers (Dict[name, new_name]): a dict containing the names\n            of the modules for which the activations will be returned as\n            the key of the dict, and the value of the dict is the name\n            of the returned activation (which the user can specify).\n    \"\"\"\n    __annotations__ = {\n        \"return_layers\": Dict[str, str],\n    }\n\n    def __init__(self, model, return_layers):\n        if not set(return_layers).issubset([name for name, _ in model.named_children()]):\n            raise ValueError(\"return_layers are not present in model\")\n\n        orig_return_layers = return_layers\n        return_layers = {str(k): str(v) for k, v in return_layers.items()}\n        layers = OrderedDict()\n\n        # 遍历模型子模块按顺序存入有序字典\n        # 只保存layer4及其之前的结构，舍去之后不用的结构\n        for name, module in model.named_children():\n            layers[name] = module\n            if name in return_layers:\n                del return_layers[name]\n            if not return_layers:\n                break\n\n        super().__init__(layers)\n        self.return_layers = orig_return_layers\n\n    def forward(self, x):","sourceCodeStart":16,"sourceCodeEnd":52,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_object_detection/faster_rcnn/backbone/feature_pyramid_network.py#L16-L52","documentation":"BackboneWithFPN's constructor validates that every key of return_layers is an actual named child of the model; if any requested layer name is missing it raises ValueError('return_layers are not present in model'). This prevents silently building an FPN hooked to nonexistent intermediate layers.","triggerScenarios":"Calling BackboneWithFPN(resnet, return_layers={'layer5':'0'}) or {'conv1':'0'}-style dicts where a key doesn't match model.named_children(); passing a model whose architecture differs (e.g. torchvision version renamed layers, or wrapping an already-FPN-wrapped backbone so expected children vanish).","commonSituations":"Copy-pasting return_layers from a ResNet-50 example into a different backbone (MobileNet/VGG have different child names); torchvision version changes changing module names; passing layer names instead of child module names (e.g. 'layer1.0.conv1'); applying BackboneWithFPN twice.","solutions":["Print [name for name,_ in model.named_children()] and use exactly those names as return_layers keys.","For ResNet use return_layers = {'layer1':'0','layer2':'1','layer3':'2','layer4':'3'}.","Match your backbone to the example the code was written for, or update return_layers for your architecture.","Ensure you wrap the raw backbone model once, not an already-wrapped backbone.","Check torchvision version for renamed children (e.g. mobilenet_v2 uses 'features', not named stages)."],"exampleFix":"# before\nreturn_layers = {'layer1': '0', 'layer2': '1', 'layer3': '2', 'layer5': '3'}  # layer5 doesn't exist\nbackbone = BackboneWithFPN(resnet50_fpn_backbone, return_layers=return_layers)\n# after\nreturn_layers = {'layer1': '0', 'layer2': '1', 'layer3': '2', 'layer4': '3'}\nbackbone = BackboneWithFPN(resnet50_fpn_backbone, return_layers=return_layers)","handlingStrategy":"validation","validationCode":"children = {name for name, _ in model.named_children()}\nassert set(return_layers).issubset(children), \\\n    f\"unknown layers {set(return_layers) - children}; available: {children}\"","typeGuard":"def layers_exist(model, return_layers: dict) -> bool:\n    children = {name for name, _ in model.named_children()}\n    return set(return_layers).issubset(children)","tryCatchPattern":"try:\n    backbone = BackboneWithFPN(model, return_layers=return_layers)\nexcept ValueError as e:\n    logging.error(\"%s — children: %s\", e, [n for n, _ in model.named_children()])\n    raise SystemExit(1)","preventionTips":["Print model.named_children() before writing return_layers.","Only use top-level child names, not nested submodule paths.","Pin torchvision versions so backbone child names stay stable.","Wrap the raw backbone exactly once with BackboneWithFPN."],"tags":["pytorch","faster-rcnn","fpn","backbone","config"],"backgroundTag":"layer-not-found-in-model","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}