[JIT] Const ModuleList length

Hello,

I’ve found the issue that cannot understand.

In the TorchScript doc said that we can use ModuleList as long as they are constant. It is possible to iterate over it, but cannot get the length of ModuleList

class SubModule(torch.nn.Module):
    def __init__(self):
        super(SubModule, self).__init__()
        self.weight = nn.Parameter(torch.randn(2))

    def forward(self, input):
        return self.weight + input

class MyModule(torch.nn.Module):
    __constants__ = ['mods']

    def __init__(self, x):
        super(MyModule, self).__init__()
        self.mods = torch.nn.ModuleList([SubModule() for i in range(10)])

    def forward(self, v):
        print(len(self.mods))
        return v


m = torch.jit.script(MyModule(3))
m(torch.rand(3))

Gives an error:

~/anaconda2/envs/pytorch-nightly/lib/python3.7/site-packages/torch/jit/_recursive.py in create_methods_from_stubs(concrete_type, stubs)
    278     rcbs = [m.resolution_callback for m in stubs]
    279     defaults = [get_default_args(m.original_method) for m in stubs]
--> 280     concrete_type._create_methods(defs, rcbs, defaults)
    281 
    282 def create_script_module_for_tracing(nn_module, stubs):

RuntimeError: 
Tried to access nonexistent attribute or method '__len__' of type '__torch__.torch.jit.___torch_mangle_65._ConstModuleList'. Did you forget to initialize an attribute in __init__()?:
at <ipython-input-26-4c61e0830c6c>:17:14
    def forward(self, v):
        print(len(self.mods))
              ~~~ <--- HERE
        return v

I have meet the same problem:( Can anyone give some suggestions?

Just use another variable to store the length.