{"record":{"id":"3c0f6c60d1bd6e6d","repo":"WZMIAOMIAO/deep-learning-for-image-processing","slug":"s-is-not-compatible-with-s-specify-weights","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.py","lineNumber":108,"sourceCode":"    pg = [p for p in model.parameters() if p.requires_grad]\n    optimizer = optim.SGD(pg, lr=hyp[\"lr0\"], momentum=hyp[\"momentum\"],\n                          weight_decay=hyp[\"weight_decay\"], nesterov=True)\n\n    scaler = torch.cuda.amp.GradScaler() if opt.amp else None\n\n    start_epoch = 0\n    best_map = 0.0\n    if weights.endswith(\".pt\") or weights.endswith(\".pth\"):\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() 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        # load optimizer\n        if ckpt[\"optimizer\"] is not None:\n            optimizer.load_state_dict(ckpt[\"optimizer\"])\n            if \"best_map\" in ckpt.keys():\n                best_map = ckpt[\"best_map\"]\n\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","sourceCodeStart":90,"sourceCodeEnd":126,"githubUrl":"https://github.com/WZMIAOMIAO/deep-learning-for-image-processing/blob/1ec3fe6f374fc9969973a61f819de25658595afa/pytorch_object_detection/yolov3_spp/train.py#L90-L126","documentation":"When resuming/loading pretrained weights, train() filters checkpoint params by matching numel with the current model and loads with strict=False; if a checkpoint key is absent from the model's state_dict, model.state_dict()[k] raises KeyError, which is re-raised as a clearer KeyError stating that --weights and --cfg are incompatible, linking to yolov3 issue #657.","triggerScenarios":"Running train.py with --weights pointing to a checkpoint whose architecture differs from --cfg (different number of classes, different backbone width/depth, or a cfg edited after the checkpoint was saved).","commonSituations":"Fine-tuning a COCO-pretrained .pt (80 classes) with a custom cfg (N classes) without adjusting; using yolov3.cfg weights with yolov3-spp.cfg; modified hyp/cfg after resuming an old run.","solutions":["Load with --weights '' (train from scratch with the given cfg), or","Make --cfg match the checkpoint's architecture (same layer sizes / classes), or","Strip/convert the incompatible layers from the checkpoint before loading"],"exampleFix":"// before\npython train.py --cfg cfg/yolov3-custom4.cfg --weights weights/yolov3-spp.pt\n// after (option A: scratch)\npython train.py --cfg cfg/yolov3-custom4.cfg --weights ''\n// or (option B: matching cfg)\npython train.py --cfg cfg/yolov3-spp.cfg --weights weights/yolov3-spp.pt","handlingStrategy":"try-catch","validationCode":"import torch\nckpt = torch.load(opt.weights, map_location='cpu')\ncs = set(ckpt['model'].keys()); ms = set(model.state_dict().keys())\nmissing = cs - ms\nassert not missing, f'cfg incompatible with weights, 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: start with --weights \\'\\'' or use the matching cfg') from e","preventionTips":["Keep the .cfg used for the checkpoint alongside the .pt and load them as a pair","Change class count? Retrain from scratch (--weights '') or resize head layers programmatically","Diff state_dict keys of checkpoint vs model before loading when resuming"],"tags":["python","pytorch","yolo","checkpoint","weights"],"backgroundTag":"checkpoint-architecture-mismatch","analyzedSha":"1ec3fe6f374fc9969973a61f819de25658595afa","analyzedAt":"2026-08-30T09:19:11.901Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}