Adding a sequential module to existing nn.Module class using function

Hello! I am creating a nn.Module class. In that I need to add a sequential module. The module is build from an external function.

import torch
import torch.nn as nn
from typing import List, Optional, Tuple

from torch.nn import modules

def build_shared_mlp(mlp_spec: List[int], bn: bool = True):
    layers = []
    for i in range(1, len(mlp_spec)):
        layers.append(nn.Conv2d(mlp_spec[i - 1], mlp_spec[i], kernel_size=1, bias=not bn))
        if bn:
            layers.append(nn.BatchNorm2d(mlp_spec[i]))
        layers.append(nn.ReLU(True))

    return nn.Sequential(*layers)

class temp(nn.Module):
    def __init__(self):
        super(temp).__init__()
        self.build_model()

    def build_model(self):
        self.net = build_shared_mlp([3,4,5],True)
        
net = temp()

But this gives me error saying

AttributeError: cannot assign module before Module.__init__() call

How can I have the module inserted using a function?

This is because you don’t initialize correctly the main class (nn.Module) that temp inherits.
Change super(temp).__init__() to super(temp, self).__init__() or super().__init__(), and the problem will be solved.

Thank you so much. My kite extension auto-inserted the init block, I didn’t double check.