{"record":{"id":"4f87a4206fadee02","repo":"facebookresearch/detectron2","slug":"cannot-match-one-checkpoint-key-to-multiple-keys-i","errorCode":null,"errorMessage":"Cannot match one checkpoint key to multiple keys in the model.","messagePattern":"Cannot match one checkpoint key to multiple keys in the model\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"detectron2/checkpoint/c2_model_loading.py","lineNumber":286,"sourceCode":"                )\n            )\n            logger.warning(\n                \"{} will not be loaded. Please double check and see if this is desired.\".format(\n                    key_ckpt\n                )\n            )\n            continue\n\n        assert key_model not in result_state_dict\n        result_state_dict[key_model] = value_ckpt\n        if key_ckpt in matched_keys:  # already added to matched_keys\n            logger.error(\n                \"Ambiguity found for {} in checkpoint!\"\n                \"It matches at least two keys in the model ({} and {}).\".format(\n                    key_ckpt, key_model, matched_keys[key_ckpt]\n                )\n            )\n            raise ValueError(\"Cannot match one checkpoint key to multiple keys in the model.\")\n\n        matched_keys[key_ckpt] = key_model\n\n    # logging:\n    matched_model_keys = sorted(matched_keys.values())\n    if len(matched_model_keys) == 0:\n        logger.warning(\"No weights in checkpoint matched with model.\")\n        return ckpt_state_dict\n    common_prefix = _longest_common_prefix(matched_model_keys)\n    rev_matched_keys = {v: k for k, v in matched_keys.items()}\n    original_keys = {k: original_keys[rev_matched_keys[k]] for k in matched_model_keys}\n\n    model_key_groups = _group_keys_by_module(matched_model_keys, original_keys)\n    table = []\n    memo = set()\n    for key_model in matched_model_keys:\n        if key_model in memo:\n            continue","sourceCodeStart":268,"sourceCodeEnd":304,"githubUrl":"https://github.com/facebookresearch/detectron2/blob/a2f4a8771ab77e8411c26b27f24f9489a28a2453/detectron2/checkpoint/c2_model_loading.py#L268-L304","documentation":"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.","triggerScenarios":"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').","commonSituations":"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.","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"],"exampleFix":"# before\nckpt.load(\"model.pth?matching_heuristics=True\")  # ambiguous suffix matches\n# after\nsd = torch.load(\"model.pth\")['model']\nsd = { (k[7:] if k.startswith('module.') else k): v for k, v in sd.items() }\nmodel.load_state_dict(sd, strict=False)","handlingStrategy":"validation","validationCode":"ckpt_sd = DetectionCheckpointer(path)._load_file(path)\nmodel_sd = model.state_dict()\nambiguous = [k for k in ckpt_sd if sum(mk.endswith(k) or k.endswith(mk.split('.')[-1]) and False for mk in []) ]\n# simpler: simulate suffix matching\nfor k in ckpt_sd:\n    matches = [mk for mk in model_sd if mk.endswith(k)]\n    if len(matches) > 1:\n        print('ambiguous:', k, matches)","typeGuard":null,"tryCatchPattern":"try:\n    ckpt.load(path)\nexcept ValueError as e:\n    if 'multiple keys' in str(e):\n        sd = {k.replace('module.',''): v for k,v in torch.load(path)['model'].items()}\n        model.load_state_dict(sd, strict=False)\n    else:\n        raise","preventionTips":["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"],"tags":["checkpoint","state-dict","model-loading","detectron2"],"backgroundTag":"checkpoint-key-mismatch","analyzedSha":"a2f4a8771ab77e8411c26b27f24f9489a28a2453","analyzedAt":"2026-08-27T12:08:21.260Z","schemaVersion":2},"datasetVersion":"2026-08-27T13:17:12.746Z"}