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

Hi Pytorch Team,

I am facing an error as: TypeError: forward() takes 1 positional argument but 2 were given

My Model is:

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'])

net = RetinaFace(cfg=resnet50)

I am using Resnet50 as a backbone here.

But when I am running:

out = net(images)

I am facing an error as:


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 <module>
    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

Can anyone help me to resolve this? Would be a great help from your side.

Thanks,
Darshan

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

Hi @eqy,

Thank you for your reply.

Below is the Forward function of Retinafce:

   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

I am using a Resnet50 backbone.

Type of Images: <class ‘torch.Tensor’>
Shape: torch.Size([24, 3, 840, 840])

Thanks,
Darshan

Something seems strange in the ResNet you are using, as doing something like

resnet50 = torchvision.models.__dict__['resnet50']()
resnet50(torch.randn(24, 3, 840, 840))

should work fine.
Can you check which layer of the ResNet it fails on?

Actually, I am using a Custom(layers changed) resnet50 as a Backbone.

The Problem is arising in this line(in the forward function of retinaface):

    `out = self.body(inputs)`

The standard Resnet 50 (used with Torchvision) works fine. But when I use custom resent50 then I am facing the issue.

I am attaching the Retinaface Architecture with Standard resnet50(which works) and custom resnet50(which throws error) below:

Retinaface Architecture with Standard resnet50(which works): https://drive.google.com/file/d/11296uAtcTFJf8JZ-Q2Zys0PGGDUx_rdp/view?usp=sharing

Retinaface Architecture with custom resnet50(which throws error)https://drive.google.com/file/d/133VFhjsHDbXSemtdmknAIyJOVTCjylRt/view?usp=sharing

I feel the Custom ResNet50 is throwing an error, because self.body is the backbone which is resnet50.

Thanks.
Darshan

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.