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
BackboneWithFPN's constructor validates that every key of return_layers is an actual named child of the model; if any requested layer name is missing it raises ValueError('return_layers are not present in model'). This prevents silently building an FPN hooked to nonexistent intermediate layers.
Source
Thrown at pytorch_object_detection/faster_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
- Print [name for name,_ in model.named_children()] and use exactly those names as return_layers keys.
- For ResNet use return_layers = {'layer1':'0','layer2':'1','layer3':'2','layer4':'3'}.
- Match your backbone to the example the code was written for, or update return_layers for your architecture.
- Ensure you wrap the raw backbone model once, not an already-wrapped backbone.
- Check torchvision version for renamed children (e.g. mobilenet_v2 uses 'features', not named stages).
Example fix
# before
return_layers = {'layer1': '0', 'layer2': '1', 'layer3': '2', 'layer5': '3'} # layer5 doesn't exist
backbone = BackboneWithFPN(resnet50_fpn_backbone, return_layers=return_layers)
# after
return_layers = {'layer1': '0', 'layer2': '1', 'layer3': '2', 'layer4': '3'}
backbone = BackboneWithFPN(resnet50_fpn_backbone, return_layers=return_layers) Defensive patterns
Strategy: validation
Validate before calling
children = {name for name, _ in model.named_children()}
assert set(return_layers).issubset(children), \
f"unknown layers {set(return_layers) - children}; available: {children}" Type guard
def layers_exist(model, return_layers: dict) -> bool:
children = {name for name, _ in model.named_children()}
return set(return_layers).issubset(children) Try / catch
try:
backbone = BackboneWithFPN(model, return_layers=return_layers)
except ValueError as e:
logging.error("%s — children: %s", e, [n for n, _ in model.named_children()])
raise SystemExit(1) Prevention
- Print model.named_children() before writing return_layers.
- Only use top-level child names, not nested submodule paths.
- Pin torchvision versions so backbone child names stay stable.
- Wrap the raw backbone exactly once with BackboneWithFPN.
When it happens
Trigger: Calling BackboneWithFPN(resnet, return_layers={'layer5':'0'}) or {'conv1':'0'}-style dicts where a key doesn't match model.named_children(); passing a model whose architecture differs (e.g. torchvision version renamed layers, or wrapping an already-FPN-wrapped backbone so expected children vanish).
Common situations: Copy-pasting return_layers from a ResNet-50 example into a different backbone (MobileNet/VGG have different child names); torchvision version changes changing module names; passing layer names instead of child module names (e.g. 'layer1.0.conv1'); applying BackboneWithFPN twice.
Related errors
- backbone should contain an attribute out_channelsspecifying
- illegal stride value.
- The inverted_residual_setting should not be empty.
- The inverted_residual_setting should be List[InvertedResidua
- expected stages_repeats as list of 3 positive ints
AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30).
Data as JSON: /api/errors/e3c79f8264c3d577.
Report an issue: GitHub.