MCPcopy Create free account
hub / github.com/AIRMEC/HECTOR / load_encoder_resnet

Function load_encoder_resnet

encoders.py:98–156  ·  view source on GitHub ↗
(backbone, checkpoint_file, use_imagenet_weights, device)

Source from the content-addressed store, hash-verified

96
97# Regular resnet encoder.
98def load_encoder_resnet(backbone, checkpoint_file, use_imagenet_weights, device):
99 import torch.nn as nn
100 import torchvision.models as models
101
102 class DecapitatedResnet(nn.Module):
103 def __init__(self, base_encoder, pretrained):
104 super(DecapitatedResnet, self).__init__()
105 self.encoder = base_encoder(pretrained=pretrained)
106
107 def forward(self, x):
108 # Same forward pass function as used in the torchvision 'stock' ResNet code
109 # but with the final FC layer removed.
110 x = self.encoder.conv1(x)
111 x = self.encoder.bn1(x)
112 x = self.encoder.relu(x)
113 x = self.encoder.maxpool(x)
114
115 x = self.encoder.layer1(x)
116 x = self.encoder.layer2(x)
117 x = self.encoder.layer3(x)
118 x = self.encoder.layer4(x)
119
120 x = self.encoder.avgpool(x)
121 x = torch.flatten(x, 1)
122
123 return x
124
125 model = DecapitatedResnet(models.__dict__[backbone], use_imagenet_weights)
126
127 if use_imagenet_weights:
128 if checkpoint_file is not None:
129 raise Exception(
130 "Either provide a weights checkpoint or the --imagenet flag, not both."
131 )
132 print(f"Created encoder with Imagenet weights")
133 else:
134 checkpoint = torch.load(checkpoint_file, map_location="cpu")
135 state_dict = checkpoint["state_dict"]
136 for k in list(state_dict.keys()):
137 # retain only encoder_q up to before the embedding layer
138 if k.startswith("module.encoder_q") and not k.startswith(
139 "module.encoder_q.fc"
140 ):
141 # remove prefix from key names
142 state_dict[k[len("module.encoder_q.") :]] = state_dict[k]
143 # delete renamed or unused k
144 del state_dict[k]
145
146 # Verify that the checkpoint did not contain data for the final FC layer
147 msg = model.encoder.load_state_dict(state_dict, strict=False)
148 assert set(msg.missing_keys) == {"fc.weight", "fc.bias"}
149 print(f"Loaded checkpoint {checkpoint_file}")
150
151 model = model.to(device)
152 if torch.cuda.device_count() > 1:
153 model = torch.nn.DataParallel(model)
154 model.eval()
155

Callers

nothing calls this directly

Calls 1

DecapitatedResnetClass · 0.85

Tested by

no test coverage detected