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

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.

Source

Thrown at pytorch_segmentation/unet/src/vgg_unet.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. List the model's children with named_children() and restrict return_layers keys to those names
  2. For vgg.features use numeric string indices within range (e.g. '4', '9', '16', '23', '30')
  3. Double-check for typos like extra spaces or wrong casing

Example fix

// before
IntermediateLayerGetter(vgg, return_layers={'conv4': '0', 'conv5': '1'})
// after
IntermediateLayerGetter(vgg.features, return_layers={'16': '0', '23': '1'})
Defensive patterns

Strategy: validation

Validate before calling

child_names = [name for name, _ in vgg.features.named_children()]
return_layers = {'16': '0', '23': '1'}
assert set(return_layers).issubset(child_names), f"valid: {child_names}"

Type guard

def layers_present(model, return_layers: dict) -> bool:
    return set(return_layers).issubset(name for name, _ in model.named_children())

Try / catch

try:
    getter = IntermediateLayerGetter(vgg.features, return_layers)
except ValueError as e:
    print(f"invalid return_layers: {e}"); raise

Prevention

When it happens

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

Common situations: Copy-pasting return_layers from another architecture, typos in keys, or torchvision version differences changing module structure.

Related errors


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