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 (the wrapper that truncates a model to only the modules needed) validates that every key in `return_layers` matches a direct child name of the wrapped model. If any requested layer name is not among `model.named_children()`, it raises this ValueError rather than silently returning wrong features.
Source
Thrown at pytorch_segmentation/fcn/src/fcn_model.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 keys in return_layers
- Match keys to the backbone family: ResNet uses 'layer1'..'layer4', MobileNetV3 uses numeric indices like '0'..'16'
- Ensure you wrap the bare backbone model, not an outer wrapper that already consumed children
Example fix
// before
backbone = IntermediateLayerGetter(mobilenetv3, {'layer3': '0', 'layer4': '1'}) # ValueError
// after
print([n for n, _ in mobilenetv3.named_children()]) # e.g. ['0',...,'16']
backbone = IntermediateLayerGetter(mobilenetv3, {'13': '0', '16': '1'}) Defensive patterns
Strategy: validation
Validate before calling
children = [name for name, _ in model.named_children()]
missing = set(return_layers) - set(children)
assert not missing, f"return_layers {missing} not in model children {children}" Type guard
def layers_exist(model, return_layers):
return set(return_layers).issubset(name for name, _ in model.named_children()) Try / catch
try:
backbone = IntermediateLayerGetter(model, return_layers)
except ValueError:
print('available children:', [n for n, _ in model.named_children()])
raise Prevention
- Print named_children() of each new backbone before choosing keys
- Keep per-backbone return_layers tables in a dict keyed by backbone name
- Never reuse ResNet keys for MobileNet/EfficientNet backbones
- Check the returned feature keys match what your head consumes
When it happens
Trigger: `IntermediateLayerGetter(resnet50(), {'layer3': '0', 'layer4': '1'})` when model is not a torchvision-style ResNet (no `layer3`/`layer4` children); using torchvision v2 resnet wrapped differently; requesting 'features.5' style names on a Sequential-less model; passing a MobileNetV3 model with ResNet layer names.
Common situations: Swapping backbones (ResNet -> MobileNet/VGG) without updating return_layers keys; torchvision version changes renaming modules (e.g. resnet50 url/weights updates still keep layer names, but EfficientNet uses different ones); typo like 'layer4x'.
Related errors
- return_layers are not present in model
- return_layers are not present in model
- illegal stride value.
- The inverted_residual_setting should not be empty.
- return_layers are not present in model
AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30).
Data as JSON: /api/errors/4e545844b50ccdac.
Report an issue: GitHub.