{"record":{"id":"6af945fb243c9864","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"return-layers-are-not-present-in-model-6af945","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/lraspp/src/lraspp_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/lraspp/src/lraspp_model.py#L20-L56","documentation":"The LRASPP project uses the same IntermediateLayerGetter wrapper: every key of `return_layers` must be a direct child name of the wrapped model, otherwise this ValueError is raised. For MobileNetV3 backbones children are numeric-string names ('0'..'16'), so ResNet-style keys ('layer3'/'layer4') will not match.","triggerScenarios":"`IntermediateLayerGetter(mobilenet_v3_large(...), {'layer3':'0','layer4':'1'})` — keys not in named_children; typos like '14 ' with whitespace; wrapping an already-truncated model so child names shifted; wrapping a model inside another module.","commonSituations":"Porting the FCN ResNet training script to LRASPP without changing return_layers; upgrading torchvision and building a custom backbone whose module order changed; constructing LRASPP head with wrong feature dict keys downstream.","solutions":["Enumerate `model.named_children()` and pick the intended numeric indices (e.g. '16' for the last conv, '13' for mid features)","Keep return_layers values consistent with the keys your segmentation head expects","Wrap the raw MobileNetV3 backbone, not a container module"],"exampleFix":"// before\nbackbone = IntermediateLayerGetter(backbone, {'layer3': '0', 'layer4': '1'})\n// after\nbackbone = IntermediateLayerGetter(backbone, {'13': '0', '16': '1'})","handlingStrategy":"validation","validationCode":"children = [n for n, _ in model.named_children()]\nassert set(return_layers).issubset(children), f\"valid: {children}\"","typeGuard":"def valid_return_layers(model, return_layers):\n    return set(return_layers).issubset(n for n, _ in model.named_children())","tryCatchPattern":"try:\n    backbone = IntermediateLayerGetter(mobilenet, return_layers)\nexcept ValueError:\n    print('children:', [n for n, _ in mobilenet.named_children()])\n    raise","preventionTips":["For MobileNetV3 use numeric-string keys like '13'/'16'","Auto-derive keys: children = list(dict(model.named_children())) and pick by index","Keep LRASPP and FCN return_layers configs separate","Re-check keys after any torchvision upgrade"],"tags":["python","value-error","backbone","lraspp","feature-extraction"],"backgroundTag":"invalid-layer-name","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}