Error: TypeError: forward() takes 1 positional argument but 2 were given

Darshan: <p>Hi Pytorch Team,</p>
<p>I am facing an error as: <strong>TypeError: forward() takes 1 positional argument but 2 were given</strong></p>
<p>My Model is:</p>
<pre><code class="lang-auto">class RetinaFace(nn.Module):
    def __init__(self, cfg = None, phase = 'train'):
        """
        :param cfg:  Network related settings.
        :param phase: train or test.
        """
        super(RetinaFace,self).__init__()
        hvd.init()
        self.phase = phase
        backbone = None
        if cfg['name'] == 'mobilenet0.25':
            backbone = MobileNetV1()
            if cfg['pretrain']:
                checkpoint = torch.load("./weights/mobilenetV1X0.25_pretrain.tar", map_location=torch.device('cpu'))
                from collections import OrderedDict
                new_state_dict = OrderedDict()
                for k, v in checkpoint['state_dict'].items():
                    name = k[7:]  # remove module.
                    new_state_dict[name] = v
                # load params
                backbone.load_state_dict(new_state_dict)
        elif cfg['name'] == 'Resnet50':
            net = OFAResNets(
        n_classes=1000, bn_param=(0.1, 1e-05),
        dropout_rate=0.1,
        depth_list=[0,1,2], expand_ratio_list=[0.2, 0.25, 0.35], width_mult_list=[0.65, 0.8, 1.0]
    )
            model_path = 'ofa_resnet50_d=0+1+2_e=0.2+0.25+0.35_w=0.65+0.8+1.0'

            init = torch.load(model_path, map_location='cpu')['state_dict']
            net.load_state_dict(init)
            newmodel = torch.nn.Sequential(*(list(net.children())[:-1]))
            newmodel = torch.nn.Sequential(*(list(newmodel.children())[:-1]))

        self.body = newmodel
        in_channels_stage2 = cfg['in_channel']
        in_channels_list = [
            in_channels_stage2 * 2,
            in_channels_stage2 * 4,
            in_channels_stage2 * 8,
        ]
        out_channels = cfg['out_channel']
        self.fpn = FPN(in_channels_list,out_channels)
        self.ssh1 = SSH(out_channels, out_channels)
        self.ssh2 = SSH(out_channels, out_channels)
        self.ssh3 = SSH(out_channels, out_channels)

        self.ClassHead = self._make_class_head(fpn_num=3, inchannels=cfg['out_channel'])
        self.BboxHead = self._make_bbox_head(fpn_num=3, inchannels=cfg['out_channel'])
        self.LandmarkHead = self._make_landmark_head(fpn_num=3, inchannels=cfg['out_channel'])
</code></pre>
<p>net = RetinaFace(cfg=resnet50)</p>
<p>I am using Resnet50 as a backbone here.</p>
<p>But when I am running:</p>
<p><code>        out = net(images)</code></p>
<p>I am facing an error as:</p>
<pre><code class="lang-auto">
Traceback (most recent call last):
  File "/snap/pycharm-community/238/plugins/python-ce/helpers/pydev/pydevd.py", line 1483, in _exec
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/snap/pycharm-community/238/plugins/python-ce/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/home/darshan/Pytorch_Retinaface/train.py", line 160, in &lt;module&gt;
    train()
  File "/home/darshan/Pytorch_Retinaface/train.py", line 126, in train
    out = net(images)
  File "/home/darshan/.local/lib/python3.6/site-packages/torch/nn/modules/module.py", line 727, in _call_impl
    result = self.forward(*input, **kwargs)
  File "/home/darshan/.local/lib/python3.6/site-packages/torch/nn/parallel/data_parallel.py", line 159, in forward
    return self.module(*inputs[0], **kwargs[0])
  File "/home/darshan/.local/lib/python3.6/site-packages/torch/nn/modules/module.py", line 727, in _call_impl
    result = self.forward(*input, **kwargs)
  File "/home/darshan/Pytorch_Retinaface/models/retinaface.py", line 126, in forward
    out = self.body(inputs)
  File "/home/darshan/.local/lib/python3.6/site-packages/torch/nn/modules/module.py", line 727, in _call_impl
    result = self.forward(*input, **kwargs)
  File "/home/darshan/.local/lib/python3.6/site-packages/torch/nn/modules/container.py", line 117, in forward
    input = module(input)
  File "/home/darshan/.local/lib/python3.6/site-packages/torch/nn/modules/module.py", line 727, in _call_impl
    result = self.forward(*input, **kwargs)
TypeError: forward() takes 1 positional argument but 2 were given
</code></pre>
<p>Can anyone help me to resolve this? Would be a great help from your side.</p>
<p>Thanks,<br>
Darshan</p>

eqy: <p>It looks like the default <code>forward</code> function in <code>nn.Module</code> is being used instead of an override which seems strange. What is the <code>forward</code> function in your model and what is the type of <code>images</code> here? Is it just a single tensor?</p>

Darshan: <p>Hi <a class="mention" href="/u/eqy">@eqy</a>,</p>
<p>Thank you for your reply.</p>
<p>Below is the Forward function of Retinafce:</p>
<pre><code class="lang-auto">   def forward(self,inputs):
        out = self.body(inputs)

        # FPN
        fpn = self.fpn(out)

        # SSH
        feature1 = self.ssh1(fpn[0])
        feature2 = self.ssh2(fpn[1])
        feature3 = self.ssh3(fpn[2])
        features = [feature1, feature2, feature3]

        bbox_regressions = torch.cat([self.BboxHead[i](feature) for i, feature in enumerate(features)], dim=1)
        classifications = torch.cat([self.ClassHead[i](feature) for i, feature in enumerate(features)],dim=1)
        ldm_regressions = torch.cat([self.LandmarkHead[i](feature) for i, feature in enumerate(features)], dim=1)

        if self.phase == 'train':
            output = (bbox_regressions, classifications, ldm_regressions)
        else:
            output = (bbox_regressions, F.softmax(classifications, dim=-1), ldm_regressions)
        return output
</code></pre>
<p>I am using a Resnet50 backbone.</p>
<p>Type of Images: &lt;class ‘torch.Tensor’&gt;<br>
Shape: torch.Size([24, 3, 840, 840])</p>
<p>Thanks,<br>
Darshan</p>

eqy: <p>Something seems strange in the ResNet you are using, as doing something like</p>
<pre><code class="lang-auto">resnet50 = torchvision.models.__dict__['resnet50']()
resnet50(torch.randn(24, 3, 840, 840))
</code></pre>
<p>should work fine.<br>
Can you check which layer of the ResNet it fails on?</p>

Darshan: <p>Actually, I am using a Custom(layers changed) resnet50 as a Backbone.</p>
<p>The Problem is arising in this line(in the forward function of retinaface):</p>
<pre><code>    `out = self.body(inputs)`
</code></pre>
<p>The standard Resnet 50 (used with Torchvision) works fine. But when I use custom resent50 then I am facing the issue.</p>
<p>I am attaching the Retinaface Architecture with Standard resnet50(which works) and custom resnet50(which throws error) below:</p>
<p>Retinaface Architecture with Standard resnet50(which works): <a href="https://drive.google.com/file/d/11296uAtcTFJf8JZ-Q2Zys0PGGDUx_rdp/view?usp=sharing" rel="noopener nofollow ugc">https://drive.google.com/file/d/11296uAtcTFJf8JZ-Q2Zys0PGGDUx_rdp/view?usp=sharing</a></p>
<p>Retinaface Architecture with custom resnet50(which throws error)<a href="https://drive.google.com/file/d/133VFhjsHDbXSemtdmknAIyJOVTCjylRt/view?usp=sharing" rel="noopener nofollow ugc">https://drive.google.com/file/d/133VFhjsHDbXSemtdmknAIyJOVTCjylRt/view?usp=sharing</a></p>
<p>I feel the Custom ResNet50 is throwing an error, because self.body is the backbone which is resnet50.</p>
<p>Thanks.<br>
Darshan</p>

eqy: <p>Yes, I agree that the error is likely in the custom ResNet so it would be useful if you could check which layer or operation the failure is coming from.</p>