Correct way to update a register_buffer in PyTorch
I'm trying to determine the recommended way to update a register buffer which preserves the buffer's attributes. One "hacky" way to do this is shown below:
import torch
import torch.nn as nn
class SomeModule(nn.Module):
def __init__(self):
super().__init__()
self.register_buffer("A", torch.tensor(2.0))
def forward(self, x):
return x * self.A
def update_buffer(self, v):
A = getattr(self, "A")
setattr(self, "A", torch.tensor(v, dtype=A.dtype, device=A.device))
if __name__ == "__main__":
model = SomeModule()
model.to(torch.float64)
print(model(1.0).dtype)
model.update_buffer(3.0)
print(model(1.0).dtype)
When updating many buffers this gets a bit messy. Is there a recommended / better method to accomplish this?