{"record":{"id":"4e545844b50ccdac","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"return-layers-are-not-present-in-model-4e5458","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/fcn/src/fcn_model.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/fcn/src/fcn_model.py#L20-L56","documentation":"IntermediateLayerGetter (the wrapper that truncates a model to only the modules needed) validates that every key in `return_layers` matches a direct child name of the wrapped model. If any requested layer name is not among `model.named_children()`, it raises this ValueError rather than silently returning wrong features.","triggerScenarios":"`IntermediateLayerGetter(resnet50(), {'layer3': '0', 'layer4': '1'})` when model is not a torchvision-style ResNet (no `layer3`/`layer4` children); using torchvision v2 resnet wrapped differently; requesting 'features.5' style names on a Sequential-less model; passing a MobileNetV3 model with ResNet layer names.","commonSituations":"Swapping backbones (ResNet -> MobileNet/VGG) without updating return_layers keys; torchvision version changes renaming modules (e.g. resnet50 url/weights updates still keep layer names, but EfficientNet uses different ones); typo like 'layer4x'.","solutions":["Print `[name for name, _ in model.named_children()]` and use exactly those names as keys in return_layers","Match keys to the backbone family: ResNet uses 'layer1'..'layer4', MobileNetV3 uses numeric indices like '0'..'16'","Ensure you wrap the bare backbone model, not an outer wrapper that already consumed children"],"exampleFix":"// before\nbackbone = IntermediateLayerGetter(mobilenetv3, {'layer3': '0', 'layer4': '1'})  # ValueError\n// after\nprint([n for n, _ in mobilenetv3.named_children()])  # e.g. ['0',...,'16']\nbackbone = IntermediateLayerGetter(mobilenetv3, {'13': '0', '16': '1'})","handlingStrategy":"validation","validationCode":"children = [name for name, _ in model.named_children()]\nmissing = set(return_layers) - set(children)\nassert not missing, f\"return_layers {missing} not in model children {children}\"","typeGuard":"def layers_exist(model, return_layers):\n    return set(return_layers).issubset(name for name, _ in model.named_children())","tryCatchPattern":"try:\n    backbone = IntermediateLayerGetter(model, return_layers)\nexcept ValueError:\n    print('available children:', [n for n, _ in model.named_children()])\n    raise","preventionTips":["Print named_children() of each new backbone before choosing keys","Keep per-backbone return_layers tables in a dict keyed by backbone name","Never reuse ResNet keys for MobileNet/EfficientNet backbones","Check the returned feature keys match what your head consumes"],"tags":["python","value-error","backbone","feature-extraction"],"backgroundTag":"invalid-layer-name","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}