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

LastLevelMaxPool-backed FPN wrapper validates that every key in return_layers corresponds to a named child module of the given model via model.named_children(). If any requested layer name doesn't exist on the backbone, it raises ValueError because feature extraction would fail silently otherwise.

Source

Thrown at pytorch_object_detection/retinaNet/backbone/feature_pyramid_network.py:34

    This means that one should **not** reuse the same nn.Module
    twice in the forward if you want this to work.
    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`.
    Arguments:
        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).
    """
    __annotations__ = {
        "return_layers": Dict[str, str],
    }

    def __init__(self, model, return_layers):
        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()}
        layers = OrderedDict()

        # 遍历模型子模块按顺序存入有序字典
        # 只保存layer4及其之前的结构,舍去之后不用的结构
        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().__init__(layers)
        self.return_layers = orig_return_layers

    def forward(self, x):

View on GitHub (pinned to 1ec3fe6f37)

Solutions

  1. Print [name for name, _ in model.named_children()] and use exactly those keys in return_layers
  2. Pass the inner (unwrapped) module to BackboneWithFPN so children match the stage names
  3. Correct typos in return_layers keys

Example fix

// before
m = torchvision.models.resnet50()
backbone = BackboneWithFPN(nn.Sequential(m), {'layer1':'0','layer2':'1','layer3':'2','layer4':'3'}, returned_layers, True)  # Sequential hides stage names
// after
backbone = BackboneWithFPN(m, {'layer1':'0','layer2':'1','layer3':'2','layer4':'3'}, returned_layers, True)
Defensive patterns

Strategy: validation

Validate before calling

children = [name for name, _ in backbone.named_children()]
assert set(return_layers).issubset(children), f'return_layers keys {list(return_layers)} not in {children}'
backbone_fpn = BackboneWithFPN(backbone, return_layers, returned_layers, extra_blocks)

Type guard

def layers_exist(model, return_layers):
    children = {name for name, _ in model.named_children()}
    return set(return_layers).issubset(children)

Try / catch

try:
    backbone = BackboneWithFPN(model, return_layers, returned_layers, True)
except ValueError as e:
    if 'not present in model' in str(e):
        print([n for n, _ in model.named_children()])  # inspect valid keys
    raise

Prevention

When it happens

Trigger: Constructing BackboneWithFPN(backbone, return_layers={'layerX': '0', ...}) where 'layerX' is not a direct child name of the backbone (e.g. requesting 'layer1' from a Sequential-wrapped backbone or a name that lives in a nested module).

Common situations: Wrapping a backbone wrapped in extra containers (Sequential, custom wrapper) so named_children differ from expected ResNet stage names; copying torchvision return_layers dicts onto a different architecture; typos like 'body.layer1' when the wrapper already exposes stages.

Related errors


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