Skip to content
Advertisement

Initiaized class member in pytorch module

When declaring a model in pytorch, having a model class member variable declared and initialized mysteriously prevents it from being populated in the constructor. Is this expected? If so, why?

Testing code below, with example models with a component member variable. The initialization value of the component (e.g. None, a number or a Tensor) does not change the behaviour.

JavaScript
JavaScript

Advertisement

Answer

This happens because nn.Module overwrites __getattr__, and it would only work as you expect if component was not in Lin2.__dict__ (nor in Lin2().__dict__). Since component is a class attribute, it is in Lin2.__dict__ and will be returned as it should.

When you write self.x = nn.Linear(...) or any other nn.Module (or even nn.Buffer or nn.Parameter), x is actually registered in a dictionary called _modules (or _buffers, etc.) In this way, when you ask for self.component, if component is already in the __dict__ of the class or the instance, Python will not call the custom nn.Module‘s __getattr__().

You can check the source-code of __getattr__ from nn.Module here. A similar discussion was done here. There was also a discussion about changing from __getattr__ to __getattribute__ in PyTorch, but as of now, this is a wontfix issue.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement