Access a registered buffer directly by name

I’ve registered a couple of buffers using model.register_buffer(...) method. The model here is an nn.Module object with defined architecture and forward pass.

Question is, how do I directly access a buffer known its name? Iterating over named_buffers is not efficient for my use case, and methods like module.get_buffer() shown here return ... object has no attribute get_buffer.

Example to reproduce:

import torch, torch.nn as nn
fc = nn.Linear(512, 10)
fc.register_buffer('buffer', None)

print(fc._buffers['buffer']) # This works, but doesn't look like I should, because its a private entity
print(fc.get_buffer('buffer')) # Doesn't work

# How do I access 'buffer' without iterator?

Edit: Just got it resolved. getattr(fc, 'buffer') or fc.buffer gives the expected behaviour.

1 Like


After you fc.register_buffer('buffer', None), you can access it at the attribute with that name: fc.buffer.