Error(s) in loading state_dict for ResNet

thoihen: <pre><code class="lang-auto">Hi,
Could someone help me with this issue as I am unable to get this right.

Created a model like so
model = torchvision.models.resnet50(pretrained=True)

Inside for loop of each epoch , I have saved the state_dict like so

state = {'epoch': epoch + 1, 'state_dict': model.state_dict(),
             'optimizer': optimizer.state_dict() }
 torch.save(state, FILE_NAME)

After, a crash, I decided to load the model but unable to get a handle on how to load the model.
I did this:
model = torchvision.models.resnet50(pretrained=True)
checkpoint = torch.load(filename)
start_epoch = checkpoint['epoch']
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])

The Error I am getting is below:

RuntimeError: Error(s) in loading state_dict for ResNet:
	size mismatch for fc.weight: copying a param with shape torch.Size([18425, 2048]) from checkpoint, the shape in current model is torch.Size([1000, 2048]).
	size mismatch for fc.bias: copying a param with shape torch.Size([18425]) from checkpoint, the shape in current model is torch.Size([1000]).
</code></pre>

MariosOreo: <p>Did you modify the resnet50 from torchvision?</p>
<p>According to your error, the output of the last fc layer is 18452 dim, the output dim in original resnet50 is 1000. I think you should check the shape of the weight of fc layer and find where the mismatch error occurs.</p>
<p>P.S. please format your code with two ```</p>

thoihen: <p>Didn’t modify Resnet. Thanks I will see the shape.</p>

iArunava: <p>First of all, welcome to the PyTorch Community!!<br>
Coming to your question,</p>
<p>I am pretty sure, when you were training it for the first time you somehow tweaked the <code>resnet50</code> that comes with <code>torchvision</code>.</p>
<p>From what it seems, you have changed the final layer with (most probaby for transfer learning purposes)</p>
<pre><code class="lang-auto">fc.weight = nn.Linear(2048, 18425)
</code></pre>
<p>Probably you have not intended to do this. as I think you have calculated the <code>18425</code> and there was some bug in the code that resulted in <code>18425</code>.</p>
<p>As for now, if you need to load this ckpt anyway, just load which ever parts are okay and manually take out the weights of <code>fc.weight</code> in the ckpt and take out a slice.</p>
<pre><code class="lang-auto">fc.weight[:, nc]
</code></pre>
<p>where nc is the number of classes you want. Store all these weights in a <code>new_dict</code> and then</p>
<pre><code class="lang-auto">sd = model.state_dict()
sd.update(new_dict)
model.load_state_dict(sd)
</code></pre>
<p>Make sure <code>new_dict</code> and <code>sd</code> have the same keys.</p>

thoihen: <pre><code class="lang-auto"></code></pre>
<p>I will try the above thanks .<br>
Looks like the same error was solved using this method</p>
<pre><code class="lang-auto">model = resnet18(pretrained=True, num_classes=4)  # where num_classes will be different 
model.load_state_dict(checkpoint)  # load
</code></pre>
<pre><code class="lang-auto">
</code></pre>

alex.veuthey: <p>In general, if you have a different number of output classes than the original network, the pretrained model is not going to work as you expect. You either have fewer classes, but they don’t mean the same thing as the original, or you have more classes, and the additional weights are simply going to be automatically generated (if you specified an initialization or use the default initialization).</p>
<p>This is why fine-tuning is often required. See <a href="https://pytorch.org/tutorials/beginner/finetuning_torchvision_models_tutorial.html" rel="nofollow noopener">this official tutorial</a> for detailed explanations.</p>

thoihen: <pre><code class="lang-auto">Thanks Alex , yes it doesn't work. So,this time around I saved the model state_dict and also the full model.

As I started training again, I had to stop in the middle because of power cut. I just wanted to resume training.
This time around, the load_state_dict still had problems with the size but loading the full model I was able to resume training with the current loss.

Here it is, when I started the GAP score was 0.0000
1. epoch 1
total batches: 5024
1 [0/5024]      time 237.078 (237.078)  loss 9.9302 (9.9302)    GAP 0.0000 (0.0000)

After resuming, loading the full model , the GAP score is below.
2. epoch 1
total batches: 5024
1 [0/5024]      time 68.160 (68.160)    loss 5.0118 (5.0118)    GAP 0.0345 (0.0345)
</code></pre>
<pre><code class="lang-auto">So, the solution to loading state_dict when using pretrained model is to avoid copying fc.weights and fc.bias

avoid = ['fc.weight', 'fc.bias']
for key  in pytorch_state_dict.keys():
        if key in avoid or key not in state_dict.keys(): # 
            # print('not in', key)
            continue
        if pytorch_state_dict[key].size() != state_dict[key].size():
            # print('size not the same', key)
            continue
        state_dict[key] = pytorch_state_dict[key]
</code></pre>
<p><code>Thanks to Arunava Chakraborty also for his advice</code></p>