{"record":{"id":"16883d2a432244f0","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"return-layers-are-not-present-in-model-16883d","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_segmentation/deeplab_v3/src/deeplabv3_model.py","lineNumber":39,"sourceCode":"    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\n    Args:\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    _version = 2\n    __annotations__ = {\n        \"return_layers\": Dict[str, str],\n    }\n\n    def __init__(self, model: nn.Module, return_layers: Dict[str, str]) -> None:\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        orig_return_layers = return_layers\n        return_layers = {str(k): str(v) for k, v in return_layers.items()}\n\n        # 重新构建backbone，将没有使用到的模块全部删掉\n        layers = OrderedDict()\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(IntermediateLayerGetter, self).__init__(layers)\n        self.return_layers = orig_return_layers\n\n    def forward(self, x: Tensor) -> Dict[str, Tensor]:\n        out = OrderedDict()\n        for name, module in self.items():","sourceCodeStart":21,"sourceCodeEnd":57,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_segmentation/deeplab_v3/src/deeplabv3_model.py#L21-L57","documentation":"IntermediateLayerGetter wraps a backbone and extracts intermediate feature maps whose names are given in return_layers. In __init__ it verifies that every requested layer key exists among model.named_children(); otherwise it raises ValueError, since there is no submodule by that name to return.","triggerScenarios":"Constructing IntermediateLayerGetter(model, return_layers) with a dict key that does not match any direct child module name of the model, e.g. {'layer4': '0'} on a model whose blocks are named differently.","commonSituations":"Swapping backbones (resnet vs mobilenet) without updating return_layers keys; typo like 'layer3' vs 'layers.3'; expecting nested module paths when only top-level children are matched.","solutions":["Print [name for name, _ in model.named_children()] and make return_layers keys exactly match one of those names.","Use the return_layers dict appropriate for the chosen backbone (e.g. {'layer4': '0'} for ResNet-50, matching mobilenet's block names otherwise).","If you need deeper/nested feature maps, restructure the model or wrap the sub-block rather than naming a nested path."],"exampleFix":"// before\nreturn_layers = {'features.6': '0'}\nbackbone = IntermediateLayerGetter(mobilenet, return_layers)\n// after\nreturn_layers = {'features': '0'}\nbackbone = IntermediateLayerGetter(mobilenet, return_layers)","handlingStrategy":"validation","validationCode":"children = {name for name, _ in model.named_children()}\nmissing = set(return_layers) - children\nassert not missing, f\"layers not in model: {missing}; have: {children}\"","typeGuard":"def layers_exist(model, return_layers: dict) -> bool:\n    names = {n for n, _ in model.named_children()}\n    return set(return_layers).issubset(names)","tryCatchPattern":"try:\n    backbone = IntermediateLayerGetter(model, return_layers)\nexcept ValueError as e:\n    logging.error(f\"{e}; available: {[n for n, _ in model.named_children()]}\"); raise","preventionTips":["Print model.named_children() when switching backbones","Keep a per-backbone return_layers mapping table","Remember only top-level children are matched, not nested paths"],"tags":["value-error","backbone","feature-extraction","configuration"],"backgroundTag":"layer-name-not-in-model","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}