facebookresearch/detectron2 · error · ValueError
Cannot match one checkpoint key to multiple keys in the mode
Error message
Cannot match one checkpoint key to multiple keys in the model.
What it means
During checkpoint loading with matching heuristics, each checkpoint key must match at most one model key. The suffix-matching algorithm found one checkpoint key that maps to two or more different keys in the model state dict, making the assignment ambiguous. Detectron2 refuses to guess and aborts the load.
Source
Thrown at detectron2/checkpoint/c2_model_loading.py:286
)
)
logger.warning(
"{} will not be loaded. Please double check and see if this is desired.".format(
key_ckpt
)
)
continue
assert key_model not in result_state_dict
result_state_dict[key_model] = value_ckpt
if key_ckpt in matched_keys: # already added to matched_keys
logger.error(
"Ambiguity found for {} in checkpoint!"
"It matches at least two keys in the model ({} and {}).".format(
key_ckpt, key_model, matched_keys[key_ckpt]
)
)
raise ValueError("Cannot match one checkpoint key to multiple keys in the model.")
matched_keys[key_ckpt] = key_model
# logging:
matched_model_keys = sorted(matched_keys.values())
if len(matched_model_keys) == 0:
logger.warning("No weights in checkpoint matched with model.")
return ckpt_state_dict
common_prefix = _longest_common_prefix(matched_model_keys)
rev_matched_keys = {v: k for k, v in matched_keys.items()}
original_keys = {k: original_keys[rev_matched_keys[k]] for k in matched_model_keys}
model_key_groups = _group_keys_by_module(matched_model_keys, original_keys)
table = []
memo = set()
for key_model in matched_model_keys:
if key_model in memo:
continueView on GitHub (pinned to a2f4a8771a)
Solutions
- Rename the ambiguous model parameter names so each checkpoint key matches exactly one (or zero) model keys
- Load without matching_heuristics and instead remap the checkpoint keys explicitly via a custom checkpointer hook or c2 name conversion
- Strip spurious prefixes (e.g. 'module.') from either the checkpoint or model state dict before loading
Example fix
# before
ckpt.load("model.pth?matching_heuristics=True") # ambiguous suffix matches
# after
sd = torch.load("model.pth")['model']
sd = { (k[7:] if k.startswith('module.') else k): v for k, v in sd.items() }
model.load_state_dict(sd, strict=False) Defensive patterns
Strategy: validation
Validate before calling
ckpt_sd = DetectionCheckpointer(path)._load_file(path)
model_sd = model.state_dict()
ambiguous = [k for k in ckpt_sd if sum(mk.endswith(k) or k.endswith(mk.split('.')[-1]) and False for mk in []) ]
# simpler: simulate suffix matching
for k in ckpt_sd:
matches = [mk for mk in model_sd if mk.endswith(k)]
if len(matches) > 1:
print('ambiguous:', k, matches) Try / catch
try:
ckpt.load(path)
except ValueError as e:
if 'multiple keys' in str(e):
sd = {k.replace('module.',''): v for k,v in torch.load(path)['model'].items()}
model.load_state_dict(sd, strict=False)
else:
raise Prevention
- Keep model parameter naming unique in suffixes
- Avoid loading foreign checkpoints with matching_heuristics when the model has nested duplicate module names
- Log the matched_keys report after loading to catch near-ambiguities
When it happens
Trigger: Calling DetectionCheckpointer.load(path, model=...) where the URL query has matching_heuristics=True (or model weights are loaded with heuristics) and the model contains two parameters whose names share the same suffix that the checkpoint key matches (e.g. both 'conv1.weight' and 'backbone.conv1.weight' match a checkpoint 'conv1.weight').
Common situations: Loading a Caffe2-converted or torchvision backbone checkpoint into a model with wrapped/nested modules (e.g. DDP 'module.' prefix, custom backbones) so duplicate suffixes appear; renaming modules so old checkpoint keys now match multiple parameters.
Related errors
- File {path} not found on main worker.
- Unsupported query remaining: f{queries}, orginal filename: {
- Class with @configurable must have a 'from_config' classmeth
- {name} must take 'cfg' as the first argument!
- target of LazyCall must be a callable or defines a callable!
AI-assisted analysis of facebookresearch/detectron2@a2f4a8771a (2026-08-27).
Data as JSON: /api/errors/4f87a4206fadee02.
Report an issue: GitHub.