MCPcopy Create free account
hub / github.com/CHENGY12/PLOT / ModifiedResNet

Class ModifiedResNet

plot-pp/clip/model.py:96–153  ·  view source on GitHub ↗

A ResNet class that is similar to torchvision's but contains the following changes: - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool. - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride

Source from the content-addressed store, hash-verified

94
95
96class ModifiedResNet(nn.Module):
97 """
98 A ResNet class that is similar to torchvision's but contains the following changes:
99 - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
100 - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
101 - The final pooling layer is a QKV attention instead of an average pool
102 """
103
104 def __init__(self, layers, output_dim, heads, input_resolution=224, width=64):
105 super().__init__()
106 self.output_dim = output_dim
107 self.input_resolution = input_resolution
108
109 # the 3-layer stem
110 self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
111 self.bn1 = nn.BatchNorm2d(width // 2)
112 self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
113 self.bn2 = nn.BatchNorm2d(width // 2)
114 self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
115 self.bn3 = nn.BatchNorm2d(width)
116 self.avgpool = nn.AvgPool2d(2)
117 self.relu = nn.ReLU(inplace=True)
118
119 # residual layers
120 self._inplanes = width # this is a *mutable* variable used during construction
121 self.layer1 = self._make_layer(width, layers[0])
122 self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
123 self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
124 self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
125
126 embed_dim = width * 32 # the ResNet feature dimension
127 self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)
128
129 def _make_layer(self, planes, blocks, stride=1):
130 layers = [Bottleneck(self._inplanes, planes, stride)]
131
132 self._inplanes = planes * Bottleneck.expansion
133 for _ in range(1, blocks):
134 layers.append(Bottleneck(self._inplanes, planes))
135
136 return nn.Sequential(*layers)
137
138 def forward(self, x):
139 def stem(x):
140 for conv, bn in [(self.conv1, self.bn1), (self.conv2, self.bn2), (self.conv3, self.bn3)]:
141 x = self.relu(bn(conv(x)))
142 x = self.avgpool(x)
143 return x
144
145 x = x.type(self.conv1.weight.dtype)
146 x = stem(x)
147 x = self.layer1(x)
148 x = self.layer2(x)
149 x = self.layer3(x)
150 x = self.layer4(x)
151 x = self.attnpool(x)
152
153 return x

Callers 1

__init__Method · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected