{"record":{"id":"8ce374cd90f03af2","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"return-layers-are-not-present-in-model-8ce374","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/mask_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/mask_rcnn/backbone/feature_pyramid_network.py#L16-L52","documentation":"FeaturePyramidNetwork's __init__ validates that every key of return_layers names an actual child module of the provided model (checked via model.named_children()). If any requested layer name does not correspond to a direct child, the backbone cannot extract the requested feature maps, so it raises this ValueError immediately.","triggerScenarios":"Calling FeaturePyramidNetwork(model, return_layers={...}) where at least one dict key is not the name of a direct child of model — e.g. a misspelled layer name, a nested (grandchild) module name, or layer names copied from a different backbone architecture.","commonSituations":"Adapting FPN code from torchvision or tutorials to a custom backbone whose child names differ; typos like 'layer1' vs 'layers.1'; passing names of sub-submodules (e.g. 'layer1.0.conv1') instead of direct children.","solutions":["Print [name for name, _ in model.named_children()] and correct return_layers keys to exactly match those child names","Only reference top-level children; if the desired tensor comes from a deeper module, wrap that module or expose it as a direct child","Verify you are passing the intended backbone model instance (not a wrapper without those children)"],"exampleFix":"// before\nfpn = FeaturePyramidNetwork(backbone, return_layers={'layer1x': '0', 'layer2': '1'})\n// after\nprint([n for n, _ in backbone.named_children()])  # e.g. ['conv1','bn1','relu','maxpool','layer1','layer2','layer3','layer4']\nfpn = FeaturePyramidNetwork(backbone, return_layers={'layer1': '0', 'layer2': '1'})","handlingStrategy":"validation","validationCode":"child_names = [name for name, _ in model.named_children()]\nmissing = set(return_layers) - set(child_names)\nif missing:\n    raise ValueError(f\"return_layers keys not children of model: {missing}; available: {child_names}\")","typeGuard":"def has_children(model, names):\n    children = {n for n, _ in model.named_children()}\n    return isinstance(names, dict) and set(names).issubset(children)","tryCatchPattern":"try:\n    fpn = FeaturePyramidNetwork(model, return_layers)\nexcept ValueError as e:\n    if 'return_layers are not present' in str(e):\n        print('valid children:', [n for n, _ in model.named_children()])\n    raise","preventionTips":["Always derive return_layers keys from model.named_children(), never hardcode from memory","Write a unit test constructing the FPN for every backbone you ship"],"tags":["pytorch","validation","config"],"backgroundTag":"invalid-layer-name","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}