{"record":{"id":"68b5d1cf0f5f279d","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"return-layers-are-not-present-in-model-68b5d1","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/vgg_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/vgg_unet.py#L20-L56","documentation":"Identical IntermediateLayerGetter check in the VGG variant: every return_layers key must be a direct child of the passed model, otherwise ValueError('return_layers are not present in model') is raised at construction. It prevents silently building a truncated backbone that drops a requested output.","triggerScenarios":"Creating VGG16Backbone with return_layers={'3':'0','7':'1',...} where one index exceeds vgg.features' child count or a name like 'conv5_3' is used instead of numeric child indices.","commonSituations":"Copy-pasting return_layers from another architecture, typos in keys, or torchvision version differences changing module structure.","solutions":["List the model's children with named_children() and restrict return_layers keys to those names","For vgg.features use numeric string indices within range (e.g. '4', '9', '16', '23', '30')","Double-check for typos like extra spaces or wrong casing"],"exampleFix":"// before\nIntermediateLayerGetter(vgg, return_layers={'conv4': '0', 'conv5': '1'})\n// after\nIntermediateLayerGetter(vgg.features, return_layers={'16': '0', '23': '1'})","handlingStrategy":"validation","validationCode":"child_names = [name for name, _ in vgg.features.named_children()]\nreturn_layers = {'16': '0', '23': '1'}\nassert set(return_layers).issubset(child_names), f\"valid: {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(vgg.features, return_layers)\nexcept ValueError as e:\n    print(f\"invalid return_layers: {e}\"); raise","preventionTips":["Use numeric string indices matching vgg.features children","Validate keys against named_children() at startup","Avoid layer aliases like 'conv5_3' — the check only knows child names"],"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"}