{"record":{"id":"fb7abea12876b3ee","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"return-layers-are-not-present-in-model-fb7abe","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/unet/src/mobilenet_unet.py","lineNumber":38,"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":20,"sourceCodeEnd":56,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_segmentation/unet/src/mobilenet_unet.py#L20-L56","documentation":"IntermediateLayerGetter (copied from torchvision) validates that every key in return_layers corresponds to a direct child module of the model (via named_children()). If any requested layer name is not a top-level child of the given backbone, __init__ raises ValueError. This catches requesting feature maps from layers the wrapped model doesn't expose.","triggerScenarios":"Instantiating MobileNetBackbone/IntermediateLayerGetter with return_layers keys like {'features': '0'} or 'layer4' while passing a torchvision mobilenet_v2 whose children are e.g. features, avgpool, classifier — a key that isn't an exact child name triggers the error.","commonSituations":"Mixing return_layers dicts copied from a ResNet example into a MobileNet model, upgrading torchvision where child module names changed, or passing keys with typos ('feature' vs 'features').","solutions":["Print [name for name, _ in model.named_children()] and use exactly those names as return_layers keys","Use return_layers={'features': '0'} (or similar) matching mobilenet's top-level children","Only request layers that remain after truncation — keys must be direct children"],"exampleFix":"// before\nIntermediateLayerGetter(mobilenet_v2(weights=...).features, return_layers={'14': '0', '18': '1'})\n// after\nbackbone = mobilenet_v2(weights=...).features\nIntermediateLayerGetter(backbone, return_layers={'14': '0', '18': '1'})  # keys are child indices of .features","handlingStrategy":"validation","validationCode":"return_layers = {'14': '0', '18': '1'}\nchild_names = [name for name, _ in backbone.named_children()]\nassert set(return_layers).issubset(child_names), f\"valid children: {child_names}\"","typeGuard":"def layers_present(model, return_layers: dict) -> bool:\n    return set(return_layers).issubset(name for name, _ in model.named_children())","tryCatchPattern":"try:\n    getter = IntermediateLayerGetter(backbone, return_layers)\nexcept ValueError as e:\n    print(f\"check return_layers keys: {e}\"); raise","preventionTips":["Print named_children() of the backbone before writing return_layers","Never copy return_layers dicts between different architectures","Pin torchvision version to keep module structure stable"],"tags":["python","valueerror","backbone","torchvision"],"backgroundTag":"invalid-layer-name","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}