{"record":{"id":"99d0556b61a7c486","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"return-layers-are-not-present-in-model-99d055","errorCode":null,"errorMessage":"return_layers are not present in model","messagePattern":"return_layers are not present in model","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pytorch_object_detection/retinaNet/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/retinaNet/backbone/feature_pyramid_network.py#L16-L52","documentation":"LastLevelMaxPool-backed FPN wrapper validates that every key in return_layers corresponds to a named child module of the given model via model.named_children(). If any requested layer name doesn't exist on the backbone, it raises ValueError because feature extraction would fail silently otherwise.","triggerScenarios":"Constructing BackboneWithFPN(backbone, return_layers={'layerX': '0', ...}) where 'layerX' is not a direct child name of the backbone (e.g. requesting 'layer1' from a Sequential-wrapped backbone or a name that lives in a nested module).","commonSituations":"Wrapping a backbone wrapped in extra containers (Sequential, custom wrapper) so named_children differ from expected ResNet stage names; copying torchvision return_layers dicts onto a different architecture; typos like 'body.layer1' when the wrapper already exposes stages.","solutions":["Print [name for name, _ in model.named_children()] and use exactly those keys in return_layers","Pass the inner (unwrapped) module to BackboneWithFPN so children match the stage names","Correct typos in return_layers keys"],"exampleFix":"// before\nm = torchvision.models.resnet50()\nbackbone = BackboneWithFPN(nn.Sequential(m), {'layer1':'0','layer2':'1','layer3':'2','layer4':'3'}, returned_layers, True)  # Sequential hides stage names\n// after\nbackbone = BackboneWithFPN(m, {'layer1':'0','layer2':'1','layer3':'2','layer4':'3'}, returned_layers, True)","handlingStrategy":"validation","validationCode":"children = [name for name, _ in backbone.named_children()]\nassert set(return_layers).issubset(children), f'return_layers keys {list(return_layers)} not in {children}'\nbackbone_fpn = BackboneWithFPN(backbone, return_layers, returned_layers, extra_blocks)","typeGuard":"def layers_exist(model, return_layers):\n    children = {name for name, _ in model.named_children()}\n    return set(return_layers).issubset(children)","tryCatchPattern":"try:\n    backbone = BackboneWithFPN(model, return_layers, returned_layers, True)\nexcept ValueError as e:\n    if 'not present in model' in str(e):\n        print([n for n, _ in model.named_children()])  # inspect valid keys\n    raise","preventionTips":["Inspect model.named_children() before building return_layers","Avoid wrapping the backbone in extra containers before FPN","Add a unit test constructing the FPN for each supported backbone"],"tags":["python","fpn","backbone"],"backgroundTag":"invalid-key-name","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}