AttributeError: 'AvgPool2d' object has no attribute 'divisor_override'

vyaslkv: <hr>
<p>AttributeError                            Traceback (most recent call last)<br>
 in <br>
45<br>
46 start = datetime.datetime.now()<br>
—&gt; 47 inp, out, lab, pred, paths = predict_test_paths(model, dataloaders=dataloaders)<br>
48 end = datetime.datetime.now()<br>
49</p>
<p> in predict_test_paths(model, dataloaders, device_type)<br>
126                 labels = labels.to(device)<br>
127<br>
–&gt; 128                 outputs = model(inputs)<br>
129                 _, preds = torch.max(outputs, 1)<br>
130</p>
<p>~/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py in <strong>call</strong>(self, *input, **kwargs)<br>
530             result = self._slow_forward(*input, **kwargs)<br>
531         else:<br>
–&gt; 532             result = self.forward(*input, **kwargs)<br>
533         for hook in self._forward_hooks.values():<br>
534             hook_result = hook(self, input, result)</p>
<p>~/anaconda3/lib/python3.7/site-packages/torch/nn/parallel/data_parallel.py in forward(self, *inputs, **kwargs)<br>
138     def forward(self, *inputs, **kwargs):<br>
139         if not self.device_ids:<br>
–&gt; 140             return self.module(*inputs, **kwargs)<br>
141<br>
142         for t in chain(self.module.parameters(), self.module.buffers()):</p>
<p>~/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py in <strong>call</strong>(self, *input, **kwargs)<br>
530             result = self._slow_forward(*input, **kwargs)<br>
531         else:<br>
–&gt; 532             result = self.forward(*input, **kwargs)<br>
533         for hook in self._forward_hooks.values():<br>
534             hook_result = hook(self, input, result)</p>
<p> in forward(self, x)<br>
44<br>
45     def forward(self, x):<br>
—&gt; 46         x = self.basemodel(x)<br>
47         x = F.relu(self.dropout1(self.feedforward1(x)))<br>
48         x = F.relu(self.dropout2(self.feedforward2(x)))</p>
<p>~/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py in <strong>call</strong>(self, *input, **kwargs)<br>
530             result = self._slow_forward(*input, **kwargs)<br>
531         else:<br>
–&gt; 532             result = self.forward(*input, **kwargs)<br>
533         for hook in self._forward_hooks.values():<br>
534             hook_result = hook(self, input, result)</p>
<p>~/anaconda3/lib/python3.7/site-packages/torchvision/models/resnet.py in forward(self, x)<br>
214<br>
215     def forward(self, x):<br>
–&gt; 216         return self._forward_impl(x)<br>
217<br>
218</p>
<p>~/anaconda3/lib/python3.7/site-packages/torchvision/models/resnet.py in _forward_impl(self, x)<br>
207         x = self.layer4(x)<br>
208<br>
–&gt; 209         x = self.avgpool(x)<br>
210         x = torch.flatten(x, 1)<br>
211         x = self.fc(x)</p>
<p>~/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py in <strong>call</strong>(self, *input, **kwargs)<br>
530             result = self._slow_forward(*input, **kwargs)<br>
531         else:<br>
–&gt; 532             result = self.forward(*input, **kwargs)<br>
533         for hook in self._forward_hooks.values():<br>
534             hook_result = hook(self, input, result)</p>
<p>~/anaconda3/lib/python3.7/site-packages/torch/nn/modules/pooling.py in forward(self, input)<br>
552     def forward(self, input):<br>
553         return F.avg_pool2d(input, self.kernel_size, self.stride,<br>
–&gt; 554                             self.padding, self.ceil_mode, self.count_include_pad, self.divisor_override)<br>
555<br>
556</p>
<p>~/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py in <strong>getattr</strong>(self, name)<br>
574                 return modules[name]<br>
575         raise AttributeError("’{}’ object has no attribute ‘{}’".format(<br>
–&gt; 576             type(self).<strong>name</strong>, name))<br>
577<br>
578     def <strong>setattr</strong>(self, name, value):</p>
<p>AttributeError: ‘AvgPool2d’ object has no attribute ‘divisor_override’</p>
<pre><code class="lang-auto">v = '/home/lalit/notebooks/Lalit/organic_non_organic/resnet50False30dec_organic_non_organic50.pth'
torch.cuda.empty_cache()

# use_cuda = torch.cuda.is_available()
# DEVICE = torch.device('cuda' if use_cuda else 'cpu') 
# var = torch.load(v)# 'cpu' in this case
# cpu_model = var
# cpu_model.load_state_dict(torch.load(v, map_location=DEVICE))

# var=cpu_model
var = torch.load(v, map_location=torch.device('cpu'))
model = var['model']
# model.avgpool = nn.AvgPool2d(kernel_size=7, stride=1, padding=0)

model = nn.DataParallel(model.module)
model.avgpool = nn.AvgPool2d(kernel_size=7, stride=1, padding=0)
data_dir= fixed_path 

MyImageFolder(data_dir)
batch_size = 32
shuffle = False
num_workers = 4

data_transforms = {'test': transforms.Compose([transforms.Resize((224, 224)),
                                              transforms.ToTensor(),
                                              transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])}

#replace MyImageFolder with datasets.ImageFolder to ignore image paths
image_datasets = {x: MyImageFolder(data_dir, data_transforms[x])
                 for x in ['test']}

dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], sampler= None,
                                             batch_size=batch_size, shuffle=shuffle, num_workers=num_workers)
              for x in ['test']}

dataset_sizes = {x: len(image_datasets[x])
               for x in ['test']}

class_names = ['non_organic','organic']

device = torch.device("cuda:2" if torch.cuda.is_available() else "cpu")

start = datetime.datetime.now()
inp, out, lab, pred, paths = predict_test_paths(model, dataloaders=dataloaders)
end = datetime.datetime.now()



supcs = [p.split('/')[-1].split('.')[0] for p in paths]
finaldf = pd.DataFrame({'path':paths, 'supc':supcs, 'flag_organic':pred},
            columns=['supc', 'path', 'flag_organic'])


noncompdf= finaldf[finaldf['flag_organic'] == 0][['supc','flag_organic']]
finaldf = finaldf[['supc','flag_organic']]
</code></pre>

ptrblck: <p><code>divisor_override</code> was added ~7months ago. Are you using an older version of PyTorch to load the model?<br>
Also, we recommend to store the <code>state_dict</code> of a model instead of the complete model as described <a href="https://pytorch.org/docs/stable/notes/serialization.html">here</a>.</p>