Skip to content
  1. LuzineDebug
  2. AI & LLMs
  3. RuntimeError: Error(s) in loading state_dict for…
AI & LLMs Intermediate ≈ 20 min to fix

Fix "Error(s) in loading state_dict" (size mismatch, Missing key(s)) in PyTorch

Error message
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']
In short

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.

Be the first to confirm this fix

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

  1. Different hyperparameters: num_classes, hidden_size, vocab_size or number of layers differing between training and loading, typically an ImageNet model with 1000 classes reloaded with 10 classes.
  2. module. or _orig_mod. prefix: the model was saved while wrapped in nn.DataParallel / DistributedDataParallel, or after torch.compile.
  3. Full checkpoint instead of the weights: the file holds {"epoch": …, "model_state_dict": …, "optimizer_state_dict": …}, hence "Unexpected key(s): "epoch", …".
  4. Wrong class or changed code: a layer renamed or added since the save, or the wrong variant (resnet18 instead of resnet50, bert-base instead of bert-large).
  5. 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

  1. 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.

    python
    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))
  2. Full checkpoint: load the right sub-key

    If the unexpected keys are called epoch, model_state_dict or optimizer_state_dict, the file is a checkpoint dictionary: pass only the model weights.

    python
    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"])
  3. Strip the module. or _orig_mod. prefix

    PyTorch provides a function that strips a prefix from every key. For future saves, store the unwrapped model: model.module.state_dict() with DDP.

    python
    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)
  4. 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.

    python
    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"])
  5. 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=True does the same.

    python
    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
    )
  6. Use strict=False knowingly

    strict=False tolerates 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 print missing_keys and unexpected_keys from 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 writes config.json and safetensors files).
  • Always save the unwrapped model: getattr(model, "module", model) for DDP, getattr(model, "_orig_mod", model) after torch.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

More AI & LLMs errors

All AI & LLMs errors →