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

FeaturePyramidNetwork's __init__ validates that every key of return_layers names an actual child module of the provided model (checked via model.named_children()). If any requested layer name does not correspond to a direct child, the backbone cannot extract the requested feature maps, so it raises this ValueError immediately.

Source

Thrown at pytorch_object_detection/mask_rcnn/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 correct return_layers keys to exactly match those child names
  2. Only reference top-level children; if the desired tensor comes from a deeper module, wrap that module or expose it as a direct child
  3. Verify you are passing the intended backbone model instance (not a wrapper without those children)

Example fix

// before
fpn = FeaturePyramidNetwork(backbone, return_layers={'layer1x': '0', 'layer2': '1'})
// after
print([n for n, _ in backbone.named_children()])  # e.g. ['conv1','bn1','relu','maxpool','layer1','layer2','layer3','layer4']
fpn = FeaturePyramidNetwork(backbone, return_layers={'layer1': '0', 'layer2': '1'})
Defensive patterns

Strategy: validation

Validate before calling

child_names = [name for name, _ in model.named_children()]
missing = set(return_layers) - set(child_names)
if missing:
    raise ValueError(f"return_layers keys not children of model: {missing}; available: {child_names}")

Type guard

def has_children(model, names):
    children = {n for n, _ in model.named_children()}
    return isinstance(names, dict) and set(names).issubset(children)

Try / catch

try:
    fpn = FeaturePyramidNetwork(model, return_layers)
except ValueError as e:
    if 'return_layers are not present' in str(e):
        print('valid children:', [n for n, _ in model.named_children()])
    raise

Prevention

When it happens

Trigger: Calling FeaturePyramidNetwork(model, return_layers={...}) where at least one dict key is not the name of a direct child of model — e.g. a misspelled layer name, a nested (grandchild) module name, or layer names copied from a different backbone architecture.

Common situations: Adapting FPN code from torchvision or tutorials to a custom backbone whose child names differ; typos like 'layer1' vs 'layers.1'; passing names of sub-submodules (e.g. 'layer1.0.conv1') instead of direct children.

Related errors


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