How to store nn.Parameter as class attribute?

Normally, setattr allows you to set a class attribute. However, when I’m in a class that extends Module and run:

setattr(self, "attribute_name", Parameter(torch.empty([5])))

the class attribute attribute_name does not get created. I can print the class attributes with print("attribute_name" in self.__dict__) but it’s not there.

Incidentally, setattr(self, "attribute_name", torch.empty([5])) does work.

Hi,

Did you try register_parameter method — PyTorch 1.8.1 documentation?

Thank you, I’m interested in trying that, but I’m not sure I understand the purpose of the register_parameter method.