How to rename Pytorch object name?
My Pytorch Model:

EfficientDet(
  (backbone): EfficientNetFeatures(
    (conv_stem): Conv2d(4, 48, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
    (bn1): BatchNorm2d(48, eps=0.001, momentum=0.1, affine=True, track_running_stats=True)
...
...


Is there a way to rename backbone object to some other name?

We can rename an attribute of an instance using the following function.

def rename_attribute(obj, old_name, new_name):
    obj._modules[new_name] = obj._modules.pop(old_name)



Example

class EfficientNetFeatures(nn.Module):
    def __init__(self):
        super(EfficientNetFeatures, self).__init__()
        self.conv_stem = nn.Conv2d(4, 48, kernel_size=(3, 3),
                                   stride=(2, 2), padding=(1, 1), bias=False)
        self.bn1 = nn.BatchNorm2d(48, eps=0.001, momentum=0.1,
                                  affine=True, track_running_stats=True)


class EfficientDet(nn.Module):
    def __init__(self):
        super(EfficientDet, self).__init__()
        self.backbone = EfficientNetFeatures()


model = EfficientDet()
print(model)

rename_attribute(model, 'backbone', 'newname')
print(model)


Outputs:

EfficientDet(
  (backbone): EfficientNetFeatures(
    (conv_stem): Conv2d(4, 48, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
    (bn1): BatchNorm2d(48, eps=0.001, momentum=0.1, affine=True, track_running_stats=True)
  )
)

EfficientDet(
  (newname): EfficientNetFeatures(
    (conv_stem): Conv2d(4, 48, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
    (bn1): BatchNorm2d(48, eps=0.001, momentum=0.1, affine=True, track_running_stats=True)
  )
)

