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
IntermediateLayerGetter (copied from torchvision) validates that every key in return_layers corresponds to a direct child module of the model (via named_children()). If any requested layer name is not a top-level child of the given backbone, __init__ raises ValueError. This catches requesting feature maps from layers the wrapped model doesn't expose.
Source
Thrown at pytorch_segmentation/unet/src/mobilenet_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
- Print [name for name, _ in model.named_children()] and use exactly those names as return_layers keys
- Use return_layers={'features': '0'} (or similar) matching mobilenet's top-level children
- Only request layers that remain after truncation — keys must be direct children
Example fix
// before
IntermediateLayerGetter(mobilenet_v2(weights=...).features, return_layers={'14': '0', '18': '1'})
// after
backbone = mobilenet_v2(weights=...).features
IntermediateLayerGetter(backbone, return_layers={'14': '0', '18': '1'}) # keys are child indices of .features Defensive patterns
Strategy: validation
Validate before calling
return_layers = {'14': '0', '18': '1'}
child_names = [name for name, _ in backbone.named_children()]
assert set(return_layers).issubset(child_names), f"valid children: {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(backbone, return_layers)
except ValueError as e:
print(f"check return_layers keys: {e}"); raise Prevention
- Print named_children() of the backbone before writing return_layers
- Never copy return_layers dicts between different architectures
- Pin torchvision version to keep module structure stable
When it happens
Trigger: Instantiating MobileNetBackbone/IntermediateLayerGetter with return_layers keys like {'features': '0'} or 'layer4' while passing a torchvision mobilenet_v2 whose children are e.g. features, avgpool, classifier — a key that isn't an exact child name triggers the error.
Common situations: Mixing return_layers dicts copied from a ResNet example into a MobileNet model, upgrading torchvision where child module names changed, or passing keys with typos ('feature' vs 'features').
Related errors
- return_layers are not present in model
- expected stages_repeats as list of 3 positive ints
- expected stages_out_channels as list of 5 positive ints
- image: {} isn't RGB mode.
- dataset have {} classes, but input {}
AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30).
Data as JSON: /api/errors/fb7abea12876b3ee.
Report an issue: GitHub.