WZMIAOMIAO/deep-learning-for-image-processing · error · ValueError

return_layers are not present in model

Error message

return_layers are not present in model

What it means

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.

Source

Thrown at pytorch_segmentation/lraspp/src/lraspp_model.py:38

    Additionally, it is only able to query submodules that are directly
    assigned to the model. So if `model` is passed, `model.feature1` can
    be returned, but not `model.feature1.layer2`.

    Args:
        model (nn.Module): model on which we will extract the features
        return_layers (Dict[name, new_name]): a dict containing the names
            of the modules for which the activations will be returned as
            the key of the dict, and the value of the dict is the name
            of the returned activation (which the user can specify).
    """
    _version = 2
    __annotations__ = {
        "return_layers": Dict[str, str],
    }

    def __init__(self, model: nn.Module, return_layers: Dict[str, str]) -> None:
        if not set(return_layers).issubset([name for name, _ in model.named_children()]):
            raise ValueError("return_layers are not present in model")
        orig_return_layers = return_layers
        return_layers = {str(k): str(v) for k, v in return_layers.items()}

        # 重新构建backbone,将没有使用到的模块全部删掉
        layers = OrderedDict()
        for name, module in model.named_children():
            layers[name] = module
            if name in return_layers:
                del return_layers[name]
            if not return_layers:
                break

        super(IntermediateLayerGetter, self).__init__(layers)
        self.return_layers = orig_return_layers

    def forward(self, x: Tensor) -> Dict[str, Tensor]:
        out = OrderedDict()
        for name, module in self.items():

View on GitHub (pinned to 1ec3fe6f37)

Solutions

  1. Enumerate `model.named_children()` and pick the intended numeric indices (e.g. '16' for the last conv, '13' for mid features)
  2. Keep return_layers values consistent with the keys your segmentation head expects
  3. Wrap the raw MobileNetV3 backbone, not a container module

Example fix

// before
backbone = IntermediateLayerGetter(backbone, {'layer3': '0', 'layer4': '1'})
// after
backbone = IntermediateLayerGetter(backbone, {'13': '0', '16': '1'})
Defensive patterns

Strategy: validation

Validate before calling

children = [n for n, _ in model.named_children()]
assert set(return_layers).issubset(children), f"valid: {children}"

Type guard

def valid_return_layers(model, return_layers):
    return set(return_layers).issubset(n for n, _ in model.named_children())

Try / catch

try:
    backbone = IntermediateLayerGetter(mobilenet, return_layers)
except ValueError:
    print('children:', [n for n, _ in mobilenet.named_children()])
    raise

Prevention

When it happens

Trigger: `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.

Common situations: 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.

Related errors


AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30). Data as JSON: /api/errors/6af945fb243c9864. Report an issue: GitHub.