WZMIAOMIAO/deep-learning-for-image-processing · error · KeyError
%s is not compatible with %s. Specify --weights '' or specif
Error message
%s is not compatible with %s. Specify --weights '' or specify a --cfg compatible with %s. See https://github.com/ultralytics/yolov3/issues/657
What it means
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.
Source
Thrown at pytorch_object_detection/yolov3_spp/train.py:108
pg = [p for p in model.parameters() if p.requires_grad]
optimizer = optim.SGD(pg, lr=hyp["lr0"], momentum=hyp["momentum"],
weight_decay=hyp["weight_decay"], nesterov=True)
scaler = torch.cuda.amp.GradScaler() if opt.amp else None
start_epoch = 0
best_map = 0.0
if weights.endswith(".pt") or weights.endswith(".pth"):
ckpt = torch.load(weights, map_location=device)
# load model
try:
ckpt["model"] = {k: v for k, v in ckpt["model"].items() if model.state_dict()[k].numel() == v.numel()}
model.load_state_dict(ckpt["model"], strict=False)
except KeyError as e:
s = "%s is not compatible with %s. Specify --weights '' or specify a --cfg compatible with %s. " \
"See https://github.com/ultralytics/yolov3/issues/657" % (opt.weights, opt.cfg, opt.weights)
raise KeyError(s) from e
# load optimizer
if ckpt["optimizer"] is not None:
optimizer.load_state_dict(ckpt["optimizer"])
if "best_map" in ckpt.keys():
best_map = ckpt["best_map"]
# load results
if ckpt.get("training_results") is not None:
with open(results_file, "w") as file:
file.write(ckpt["training_results"]) # write results.txt
# epochs
start_epoch = ckpt["epoch"] + 1
if epochs < start_epoch:
print('%s has been trained for %g epochs. Fine-tuning for %g additional epochs.' %
(opt.weights, ckpt['epoch'], epochs))
epochs += ckpt['epoch'] # finetune additional epochsView on GitHub (pinned to 1ec3fe6f37)
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
Example fix
// before python train.py --cfg cfg/yolov3-custom4.cfg --weights weights/yolov3-spp.pt // after (option A: scratch) python train.py --cfg cfg/yolov3-custom4.cfg --weights '' // or (option B: matching cfg) python train.py --cfg cfg/yolov3-spp.cfg --weights weights/yolov3-spp.pt
Defensive patterns
Strategy: try-catch
Validate before calling
import torch
ckpt = torch.load(opt.weights, map_location='cpu')
cs = set(ckpt['model'].keys()); ms = set(model.state_dict().keys())
missing = cs - ms
assert not missing, f'cfg incompatible with weights, e.g. {sorted(missing)[:3]}' Try / catch
try:
model.load_state_dict(ckpt['model'], strict=False)
except KeyError as e:
raise SystemExit('weights/cfg mismatch: start with --weights \'\'' or use the matching cfg') from e Prevention
- 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
When it happens
Trigger: 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).
Common situations: 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.
Related errors
- %s is not compatible with %s. Specify --weights '' or specif
- conv2d filter size must be int type.
- not found weights file: {}
- not found weights file: {}
- expected stages_repeats as list of 3 positive ints
AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30).
Data as JSON: /api/errors/3c0f6c60d1bd6e6d.
Report an issue: GitHub.