{"record":{"id":"1dca657eceb96702","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"s-is-not-compatible-with-s-specify-weights-1dca65","errorCode":null,"errorMessage":"%s is not compatible with %s. Specify --weights '' or specify a --cfg compatible with %s. See https://github.com/ultralytics/yolov3/issues/657","messagePattern":"(.+?) is not compatible with (.+?)\\. Specify --weights '' or specify a --cfg compatible with (.+?)\\. See https://github\\.com/ultralytics/yolov3/issues/657","errorType":"exception","errorClass":"KeyError","httpStatus":null,"severity":"error","filePath":"pytorch_object_detection/yolov3_spp/train_multi_GPU.py","lineNumber":96,"sourceCode":"\n    # Initialize model\n    model = Darknet(cfg).to(device)\n\n    start_epoch = 0\n    best_map = 0.0\n    # 如果指定了预训练权重，则载入预训练权重\n    if weights.endswith(\".pt\"):\n        ckpt = torch.load(weights, map_location=device)\n\n        # load model\n        try:\n            ckpt[\"model\"] = {k: v for k, v in ckpt[\"model\"].items()\n                             if model.state_dict()[k].numel() == v.numel()}\n            model.load_state_dict(ckpt[\"model\"], strict=False)\n        except KeyError as e:\n            s = \"%s is not compatible with %s. Specify --weights '' or specify a --cfg compatible with %s. \" \\\n                \"See https://github.com/ultralytics/yolov3/issues/657\" % (opt.weights, opt.cfg, opt.weights)\n            raise KeyError(s) from e\n\n        if opt.rank in [-1, 0]:\n            # load results\n            if ckpt.get(\"training_results\") is not None:\n                with open(results_file, \"w\") as file:\n                    file.write(ckpt[\"training_results\"])  # write results.txt\n\n        # epochs\n        start_epoch = ckpt[\"epoch\"] + 1\n        if epochs < start_epoch:\n            print('%s has been trained for %g epochs. Fine-tuning for %g additional epochs.' %\n                  (opt.weights, ckpt['epoch'], epochs))\n            epochs += ckpt['epoch']  # finetune additional epochs\n\n        if opt.amp and \"scaler\" in ckpt:\n            scaler.load_state_dict(ckpt[\"scaler\"])\n\n        del ckpt","sourceCodeStart":78,"sourceCodeEnd":114,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_object_detection/yolov3_spp/train_multi_GPU.py#L78-L114","documentation":"Same guard as train.py: when loading a checkpoint in multi-GPU main(), mismatched checkpoint keys cause model.state_dict()[k] to raise KeyError, re-raised as a KeyError message saying the weights and cfg are incompatible, with a link to yolov3 issue #657.","triggerScenarios":"Running train_multi_GPU.py where --weights checkpoint architecture does not match --cfg (class count, depth/width multiples, or SPP layers differ).","commonSituations":"Distributed fine-tune of a COCO checkpoint with a custom-N-classes cfg; resuming a run whose cfg was edited between runs; using single-GPU weights with a modified multi-GPU cfg.","solutions":["Pass --weights '' to train from scratch with the current cfg","Use a --cfg that matches the checkpoint architecture exactly","Preprocess the checkpoint to drop/resize incompatible layers before loading"],"exampleFix":"// before\npython train_multi_GPU.py --cfg cfg/yolov3-tiny3.cfg --weights weights/yolov3-spp.pt\n// after\npython train_multi_GPU.py --cfg cfg/yolov3-tiny3.cfg --weights ''\n# or match the checkpoint: --cfg cfg/yolov3-spp.cfg --weights weights/yolov3-spp.pt","handlingStrategy":"try-catch","validationCode":"import torch\nckpt = torch.load(opt.weights, map_location='cpu')\nmissing = set(ckpt['model'].keys()) - set(model.state_dict().keys())\nassert not missing, f'weights/cfg mismatch, e.g. {sorted(missing)[:3]}'","typeGuard":null,"tryCatchPattern":"try:\n    model.load_state_dict(ckpt['model'], strict=False)\nexcept KeyError as e:\n    raise SystemExit('weights/cfg mismatch in multi-GPU run: use --weights \\'\\'' or the matching cfg') from e","preventionTips":["Store cfg + hyp + weights together per run and resume only from matching combos","Re-generate checkpoints after any cfg architecture change","Pre-validate checkpoint keys against the model state_dict before DDP launch"],"tags":["python","pytorch","yolo","checkpoint","distributed"],"backgroundTag":"checkpoint-architecture-mismatch","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}