Fix "Error(s) in loading state_dict" (size mismatch, Missing key(s)) in PyTorch
RuntimeError: Error(s) in loading state_dict for ResNet: size mismatch for fc.weight: copying a param with shape torch.Size([1000, 512]) from checkpoint, the shape in current model is torch.Size([10, 512]).
- RuntimeError: Error(s) in loading state_dict for Net: Missing key(s) in state_dict: "conv1.weight", "conv1.bias". Unexpected key(s) in state_dict: "module.conv1.weight", "module.conv1.bias".
- Unexpected key(s) in state_dict: "epoch", "model_state_dict", "optimizer_state_dict".
- size mismatch for classifier.weight: copying a param with shape torch.Size([2, 768]) from checkpoint, the shape in current model is torch.Size([5, 768]). You may consider adding `ignore_mismatched_sizes=True` in the model `from_pretrained` method.
- Some weights of BertForSequenceClassification were not initialized from the model checkpoint at bert-base-uncased and are newly initialized: ['classifier.bias', 'classifier.weight']
The checkpoint does not match the model architecture: layers of different sizes (1000 classes versus 10), keys prefixed with module. (DataParallel, DDP) or _orig_mod. (torch.compile), or a file holding the whole checkpoint (model_state_dict, optimizer_state_dict) instead of just the weights. Compare keys and shapes, then rebuild the model with the same hyperparameters, strip the prefix or load selectively.
What this error means
model.load_state_dict(sd) matches every tensor in the dictionary, by name (layer1.0.conv1.weight), to a model parameter. With strict=True (the default), both key sets must be identical: a model key absent from the file gives "Missing key(s)", an extra key gives "Unexpected key(s)". Independently, every tensor must have exactly the same shape as the parameter: otherwise "size mismatch", even with strict=False. PyTorch groups all these problems into a single RuntimeError "Error(s) in loading state_dict for <Class>". The weights are not corrupted: the structure differs between the code that saved and the code that loads.
Common causes
- Different hyperparameters:
num_classes,hidden_size,vocab_sizeor number of layers differing between training and loading, typically an ImageNet model with 1000 classes reloaded with 10 classes. module.or_orig_mod.prefix: the model was saved while wrapped innn.DataParallel/DistributedDataParallel, or aftertorch.compile.- Full checkpoint instead of the weights: the file holds
{"epoch": …, "model_state_dict": …, "optimizer_state_dict": …}, hence "Unexpected key(s): "epoch", …". - Wrong class or changed code: a layer renamed or added since the save, or the wrong variant (
resnet18instead ofresnet50,bert-baseinstead ofbert-large). - New classification head: a pretrained model reloaded with a different number of labels (
from_pretrained(..., num_labels=5)), hence a "size mismatch for classifier".
Step-by-step fix
-
Compare keys and shapes
Load the file on CPU and compare it with the model
state_dict(): missing keys, extra keys and different shapes show up in a few lines.import torch ckpt = torch.load("model.pt", map_location="cpu", weights_only=True) state = ckpt.get("model_state_dict", ckpt) own = model.state_dict() print("missing:", sorted(set(own) - set(state))[:10]) print("unexpected:", sorted(set(state) - set(own))[:10]) for key, tensor in state.items(): if key in own and tensor.shape != own[key].shape: print("shape:", key, tuple(tensor.shape), "->", tuple(own[key].shape)) -
Full checkpoint: load the right sub-key
If the unexpected keys are called
epoch,model_state_dictoroptimizer_state_dict, the file is a checkpoint dictionary: pass only the model weights.checkpoint = torch.load("checkpoint.pt", map_location="cpu", weights_only=True) model.load_state_dict(checkpoint["model_state_dict"]) optimizer.load_state_dict(checkpoint["optimizer_state_dict"]) -
Strip the
module.or_orig_mod.prefixPyTorch provides a function that strips a prefix from every key. For future saves, store the unwrapped model:
model.module.state_dict()with DDP.from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present state = torch.load("model.pt", map_location="cpu", weights_only=True) consume_prefix_in_state_dict_if_present(state, "module.") consume_prefix_in_state_dict_if_present(state, "_orig_mod.") model.load_state_dict(state) -
Rebuild the model with the same hyperparameters
For a "size mismatch", instantiate the model exactly as during training. The safest way is to save the configuration together with the weights.
config = {"num_classes": 10, "hidden": 256} torch.save({"config": config, "model_state_dict": model.state_dict()}, "model.pt") ckpt = torch.load("model.pt", map_location="cpu", weights_only=True) model = Net(**ckpt["config"]) model.load_state_dict(ckpt["model_state_dict"]) -
Fine-tuning: replace the head or skip incompatible layers
To change the number of classes, load the pretrained weights first, then replace the last layer. For a checkpoint, filter out tensors whose shape differs. With Hugging Face Transformers,
ignore_mismatched_sizes=Truedoes the same.import torch import torchvision model = torchvision.models.resnet18(weights="IMAGENET1K_V1") model.fc = torch.nn.Linear(model.fc.in_features, 10) # new head, 10 classes # Or keep only the tensors whose shape matches own = model.state_dict() filtered = {k: v for k, v in state.items() if k in own and v.shape == own[k].shape} result = model.load_state_dict(filtered, strict=False) print("left randomly initialized:", result.missing_keys) # Hugging Face Transformers from transformers import AutoModelForSequenceClassification clf = AutoModelForSequenceClassification.from_pretrained( "bert-base-uncased", num_labels=5, ignore_mismatched_sizes=True ) -
Use
strict=Falseknowinglystrict=Falsetolerates missing or extra keys, but not "size mismatch". It can also hide a real problem: a model with half of its layers left random. Always printmissing_keysandunexpected_keysfrom the result.
Did this fix work for you?
Confirm it in one click: it will rise for the next developers stuck on the same error.
Keep it from coming back
- Save the configuration together with the weights (or use
save_pretrained(), which writesconfig.jsonand safetensors files). - Always save the unwrapped model:
getattr(model, "module", model)for DDP,getattr(model, "_orig_mod", model)aftertorch.compile. - Add a test that reloads the checkpoint right after training, using the production code.
Frequently asked questions
Does strict=False fix a "size mismatch"?
No. strict=False only covers missing or extra keys. For a different shape, you need the same model, or to filter out incompatible tensors before loading.
Where does the module. prefix in the keys come from?
nn.DataParallel and DistributedDataParallel wrap the model in a module attribute, so saving the wrapper prefixes every key with module..
Is it safe to load a .pt downloaded from the Internet?
torch.load relies on pickle, which can run code. Keep weights_only=True (the default since PyTorch 2.6) and prefer the safetensors format for shared weights.
Useful tools for this error
Text diff
Compare two versions line by line: additions, deletions, invisible whitespace.
Error finder
Paste an error message or a log: the tool recognises the error and opens the right fix.
Stack trace formatter
Formats a stack trace (JS, Python, PHP, Java, .NET, Go), separates your code from libraries and points to the line to open first.
More AI & LLMs errors
- Fix error 429 "Rate limit reached" on OpenAI, Claude and Gemini APIs
- Fix "maximum context length" and "prompt is too long" (context_length_exceeded)
- Fix "CUDA out of memory" in PyTorch
- Fix error 401 "Incorrect API key provided" / "invalid x-api-key"
- Fix "Torch not compiled with CUDA enabled" and torch.cuda.is_available() returning False
- Fix "could not connect to ollama" and connection refused on port 11434
- Fix "JSONDecodeError: Expecting value" when parsing an LLM response
- Fix "You are trying to access a gated repo" (401) on Hugging Face