openpoints 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. openpoints/__init__.py +3 -0
  2. openpoints/cpp/__init__.py +6 -0
  3. openpoints/cpp/chamfer_dist/__init__.py +110 -0
  4. openpoints/cpp/chamfer_dist/setup.py +19 -0
  5. openpoints/cpp/chamfer_dist/test.py +34 -0
  6. openpoints/cpp/emd/__init__.py +3 -0
  7. openpoints/cpp/emd/emd.py +88 -0
  8. openpoints/cpp/emd/setup.py +27 -0
  9. openpoints/cpp/emd/test_emd_loss.py +45 -0
  10. openpoints/cpp/pointnet2_batch/__init__.py +24 -0
  11. openpoints/cpp/pointnet2_batch/setup.py +23 -0
  12. openpoints/cpp/pointops/__init__.py +0 -0
  13. openpoints/cpp/pointops/functions/__init__.py +0 -0
  14. openpoints/cpp/pointops/functions/pointops.py +314 -0
  15. openpoints/cpp/pointops/setup.py +37 -0
  16. openpoints/cpp/pointops/src/__init__.py +0 -0
  17. openpoints/dataset/__init__.py +10 -0
  18. openpoints/dataset/atom3d/__init__.py +1 -0
  19. openpoints/dataset/atom3d/psr.py +38 -0
  20. openpoints/dataset/build.py +98 -0
  21. openpoints/dataset/data_util.py +192 -0
  22. openpoints/dataset/datalist.py +67 -0
  23. openpoints/dataset/dataset_base.py +96 -0
  24. openpoints/dataset/graph_dataset/__init__.py +3 -0
  25. openpoints/dataset/graph_dataset/graph_dataset.py +93 -0
  26. openpoints/dataset/graph_dataset/stack_with_pad.py +91 -0
  27. openpoints/dataset/graph_dataset/structural_dataset.py +73 -0
  28. openpoints/dataset/graph_dataset/svd_encodings_dataset.py +110 -0
  29. openpoints/dataset/grid_sample.py +21 -0
  30. openpoints/dataset/matterport3d/__init__.py +1 -0
  31. openpoints/dataset/matterport3d/category_mapping.tsv +1660 -0
  32. openpoints/dataset/matterport3d/matterport3d.py +210 -0
  33. openpoints/dataset/matterport3d/matterport3d_dataprocessing.py +105 -0
  34. openpoints/dataset/modelnet/__init__.py +3 -0
  35. openpoints/dataset/modelnet/modelnet40_normal_resampled_loader.py +124 -0
  36. openpoints/dataset/modelnet/modelnet40_ply_2048_loader.py +160 -0
  37. openpoints/dataset/molhiv/__init__.py +1 -0
  38. openpoints/dataset/molhiv/data.py +59 -0
  39. openpoints/dataset/molpcba/__init__.py +1 -0
  40. openpoints/dataset/molpcba/data.py +59 -0
  41. openpoints/dataset/parsers/__init__.py +1 -0
  42. openpoints/dataset/parsers/class_map.py +19 -0
  43. openpoints/dataset/parsers/constants.py +1 -0
  44. openpoints/dataset/parsers/parser.py +17 -0
  45. openpoints/dataset/parsers/parser_factory.py +29 -0
  46. openpoints/dataset/parsers/parser_image_folder.py +69 -0
  47. openpoints/dataset/parsers/parser_image_in_tar.py +222 -0
  48. openpoints/dataset/parsers/parser_image_tar.py +72 -0
  49. openpoints/dataset/parsers/parser_tfds.py +297 -0
  50. openpoints/dataset/pcqm4m/__init__.py +1 -0
  51. openpoints/dataset/pcqm4m/data.py +62 -0
  52. openpoints/dataset/pcqm4mv2/__init__.py +1 -0
  53. openpoints/dataset/pcqm4mv2/data.py +87 -0
  54. openpoints/dataset/s3dis/__init__.py +2 -0
  55. openpoints/dataset/s3dis/s3dis.py +156 -0
  56. openpoints/dataset/s3dis/s3dis_block.py +96 -0
  57. openpoints/dataset/s3dis/s3dis_sphere.py +349 -0
  58. openpoints/dataset/scannetv2/__init__.py +1 -0
  59. openpoints/dataset/scannetv2/scannet.py +176 -0
  60. openpoints/dataset/scanobjectnn/__init__.py +3 -0
  61. openpoints/dataset/scanobjectnn/scanobjectnn.py +110 -0
  62. openpoints/dataset/semantic_kitti/__init__.py +1 -0
  63. openpoints/dataset/semantic_kitti/helper_tool.py +286 -0
  64. openpoints/dataset/semantic_kitti/label_mapping.yaml +211 -0
  65. openpoints/dataset/semantic_kitti/semantickitti.py +229 -0
  66. openpoints/dataset/semantic_kitti/utils/meta/anno_paths.txt +272 -0
  67. openpoints/dataset/semantic_kitti/utils/meta/class_names.txt +13 -0
  68. openpoints/dataset/semantic_kitti/utils/semantic-kitti.yaml +211 -0
  69. openpoints/dataset/shapenet/__init__.py +1 -0
  70. openpoints/dataset/shapenet/shapenet55.py +76 -0
  71. openpoints/dataset/shapenet/shapenetpart.py +121 -0
  72. openpoints/dataset/shapenetpart/__init__.py +1 -0
  73. openpoints/dataset/shapenetpart/shapenet55.py +75 -0
  74. openpoints/dataset/shapenetpart/shapenetpart.py +388 -0
  75. openpoints/dataset/vis2d.py +17 -0
  76. openpoints/dataset/vis3d.py +153 -0
  77. openpoints/loss/__init__.py +3 -0
  78. openpoints/loss/build.py +281 -0
  79. openpoints/loss/cross_entropy.py +38 -0
  80. openpoints/loss/distill_loss.py +76 -0
  81. openpoints/models/__init__.py +10 -0
  82. openpoints/models/backbone/Stratified_transformer.py +558 -0
  83. openpoints/models/backbone/__init__.py +11 -0
  84. openpoints/models/backbone/baafnet.py +527 -0
  85. openpoints/models/backbone/ball_dgcnn.py +123 -0
  86. openpoints/models/backbone/curvenet.py +793 -0
  87. openpoints/models/backbone/debug_invvit.py +114 -0
  88. openpoints/models/backbone/deepgcn.py +143 -0
  89. openpoints/models/backbone/dgcnn.py +119 -0
  90. openpoints/models/backbone/graphvit3d.py +134 -0
  91. openpoints/models/backbone/grouppointnet.py +100 -0
  92. openpoints/models/backbone/pct.py +163 -0
  93. openpoints/models/backbone/pointmlp.py +417 -0
  94. openpoints/models/backbone/pointnet.py +199 -0
  95. openpoints/models/backbone/pointnetv2.py +511 -0
  96. openpoints/models/backbone/pointnext.py +663 -0
  97. openpoints/models/backbone/pointnextPyG.py +555 -0
  98. openpoints/models/backbone/pointtransformer.py +293 -0
  99. openpoints/models/backbone/pointvector.py +853 -0
  100. openpoints/models/backbone/pointvit.py +392 -0
  101. openpoints/models/backbone/pointvit_inv.py +942 -0
  102. openpoints/models/backbone/pointvit_inv_old.py +784 -0
  103. openpoints/models/backbone/randlenet.py +318 -0
  104. openpoints/models/backbone/resnet.py +342 -0
  105. openpoints/models/backbone/simpleview.py +153 -0
  106. openpoints/models/backbone/simpleview_util.py +292 -0
  107. openpoints/models/build.py +13 -0
  108. openpoints/models/classification/__init__.py +5 -0
  109. openpoints/models/classification/cls_base.py +136 -0
  110. openpoints/models/classification/point_bert.py +154 -0
  111. openpoints/models/layers/__init__.py +14 -0
  112. openpoints/models/layers/activation.py +57 -0
  113. openpoints/models/layers/attention.py +103 -0
  114. openpoints/models/layers/conv.py +167 -0
  115. openpoints/models/layers/drop.py +164 -0
  116. openpoints/models/layers/graph_conv.py +122 -0
  117. openpoints/models/layers/group.py +415 -0
  118. openpoints/models/layers/group_embed.py +286 -0
  119. openpoints/models/layers/helpers.py +43 -0
  120. openpoints/models/layers/kmeans.py +119 -0
  121. openpoints/models/layers/knn.py +110 -0
  122. openpoints/models/layers/local_aggregation.py +286 -0
  123. openpoints/models/layers/mlp.py +129 -0
  124. openpoints/models/layers/norm.py +106 -0
  125. openpoints/models/layers/padding.py +56 -0
  126. openpoints/models/layers/patch_embed.py +37 -0
  127. openpoints/models/layers/registry.py +168 -0
  128. openpoints/models/layers/subsample.py +185 -0
  129. openpoints/models/layers/upsampling.py +106 -0
  130. openpoints/models/layers/weight_init.py +89 -0
  131. openpoints/models/reconstruction/__init__.py +8 -0
  132. openpoints/models/reconstruction/base_recontruct.py +216 -0
  133. openpoints/models/reconstruction/maskedpoint.py +116 -0
  134. openpoints/models/reconstruction/maskedpointgroup.py +168 -0
  135. openpoints/models/reconstruction/maskedpointvit.py +253 -0
  136. openpoints/models/reconstruction/nodeshuffle.py +11 -0
  137. openpoints/models/registry.py +149 -0
  138. openpoints/models/segmentation/__init__.py +6 -0
  139. openpoints/models/segmentation/base_seg.py +278 -0
  140. openpoints/models/segmentation/vit_seg.py +126 -0
  141. openpoints/optim/__init__.py +15 -0
  142. openpoints/optim/adabelief.py +201 -0
  143. openpoints/optim/adafactor.py +167 -0
  144. openpoints/optim/adahessian.py +156 -0
  145. openpoints/optim/adamp.py +105 -0
  146. openpoints/optim/adamw.py +122 -0
  147. openpoints/optim/lamb.py +192 -0
  148. openpoints/optim/lars.py +135 -0
  149. openpoints/optim/lookahead.py +61 -0
  150. openpoints/optim/madgrad.py +184 -0
  151. openpoints/optim/nadam.py +92 -0
  152. openpoints/optim/nvnovograd.py +120 -0
  153. openpoints/optim/optim_factory.py +306 -0
  154. openpoints/optim/radam.py +89 -0
  155. openpoints/optim/rmsprop_tf.py +139 -0
  156. openpoints/optim/sgdp.py +70 -0
  157. openpoints/scheduler/__init__.py +8 -0
  158. openpoints/scheduler/cosine_lr.py +124 -0
  159. openpoints/scheduler/multistep_lr.py +65 -0
  160. openpoints/scheduler/plateau_lr.py +113 -0
  161. openpoints/scheduler/poly_lr.py +116 -0
  162. openpoints/scheduler/scheduler.py +110 -0
  163. openpoints/scheduler/scheduler_factory.py +118 -0
  164. openpoints/scheduler/step_lr.py +65 -0
  165. openpoints/scheduler/tanh_lr.py +117 -0
  166. openpoints/transforms/__init__.py +7 -0
  167. openpoints/transforms/point_transform_cpu.py +332 -0
  168. openpoints/transforms/point_transformer_gpu.py +764 -0
  169. openpoints/transforms/transforms_factory.py +60 -0
  170. openpoints/utils/__init__.py +8 -0
  171. openpoints/utils/ckpt_util.py +438 -0
  172. openpoints/utils/config.py +113 -0
  173. openpoints/utils/dist_utils.py +54 -0
  174. openpoints/utils/logger.py +170 -0
  175. openpoints/utils/metrics.py +311 -0
  176. openpoints/utils/random.py +16 -0
  177. openpoints/utils/registry.py +294 -0
  178. openpoints/utils/str2bool.py +11 -0
  179. openpoints/utils/wandb.py +88 -0
  180. openpoints-0.1.0.dist-info/METADATA +150 -0
  181. openpoints-0.1.0.dist-info/RECORD +184 -0
  182. openpoints-0.1.0.dist-info/WHEEL +5 -0
  183. openpoints-0.1.0.dist-info/licenses/LICENSE +21 -0
  184. openpoints-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,318 @@
1
+ import time
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ from ..build import MODELS
6
+
7
+ try:
8
+ from torch_points import knn
9
+ except (ModuleNotFoundError, ImportError):
10
+ from torch_points_kernels import knn
11
+
12
+ class SharedMLP(nn.Module):
13
+ def __init__(
14
+ self,
15
+ in_channels,
16
+ out_channels,
17
+ kernel_size=1,
18
+ stride=1,
19
+ transpose=False,
20
+ padding_mode='zeros',
21
+ bn=False,
22
+ activation_fn=None
23
+ ):
24
+ super(SharedMLP, self).__init__()
25
+
26
+ conv_fn = nn.ConvTranspose2d if transpose else nn.Conv2d
27
+
28
+ self.conv = conv_fn(
29
+ in_channels,
30
+ out_channels,
31
+ kernel_size,
32
+ stride=stride,
33
+ padding_mode=padding_mode
34
+ )
35
+ self.batch_norm = nn.BatchNorm2d(out_channels, eps=1e-6, momentum=0.99) if bn else None
36
+ self.activation_fn = activation_fn
37
+
38
+ def forward(self, input):
39
+ r"""
40
+ Forward pass of the network
41
+
42
+ Parameters
43
+ ----------
44
+ input: torch.Tensor, shape (B, d_in, N, K)
45
+
46
+ Returns
47
+ -------
48
+ torch.Tensor, shape (B, d_out, N, K)
49
+ """
50
+ x = self.conv(input)
51
+ if self.batch_norm:
52
+ x = self.batch_norm(x)
53
+ if self.activation_fn:
54
+ x = self.activation_fn(x)
55
+ return x
56
+
57
+
58
+ class LocalSpatialEncoding(nn.Module):
59
+ def __init__(self, d, num_neighbors, device):
60
+ super(LocalSpatialEncoding, self).__init__()
61
+
62
+ self.num_neighbors = num_neighbors
63
+ self.mlp = SharedMLP(10, d, bn=True, activation_fn=nn.ReLU())
64
+
65
+ self.device = device
66
+
67
+ def forward(self, coords, features, knn_output):
68
+ r"""
69
+ Forward pass
70
+
71
+ Parameters
72
+ ----------
73
+ coords: torch.Tensor, shape (B, N, 3)
74
+ coordinates of the point cloud
75
+ features: torch.Tensor, shape (B, d, N, 1)
76
+ features of the point cloud
77
+ neighbors: tuple
78
+
79
+ Returns
80
+ -------
81
+ torch.Tensor, shape (B, 2*d, N, K)
82
+ """
83
+ # finding neighboring points
84
+ idx, dist = knn_output
85
+ B, N, K = idx.size()
86
+ # idx(B, N, K), coords(B, N, 3)
87
+ # neighbors[b, i, n, k] = coords[b, idx[b, n, k], i] = extended_coords[b, i, extended_idx[b, i, n, k], k]
88
+ extended_idx = idx.unsqueeze(1).expand(B, 3, N, K)
89
+ extended_coords = coords.transpose(-2,-1).unsqueeze(-1).expand(B, 3, N, K)
90
+ neighbors = torch.gather(extended_coords, 2, extended_idx) # shape (B, 3, N, K)
91
+ # if USE_CUDA:
92
+ # neighbors = neighbors.cuda()
93
+
94
+ # relative point position encoding
95
+ concat = torch.cat((
96
+ extended_coords,
97
+ neighbors,
98
+ extended_coords - neighbors,
99
+ dist.unsqueeze(-3)
100
+ ), dim=-3).to(self.device)
101
+ return torch.cat((
102
+ self.mlp(concat),
103
+ features.expand(B, -1, N, K)
104
+ ), dim=-3)
105
+
106
+
107
+
108
+ class AttentivePooling(nn.Module):
109
+ def __init__(self, in_channels, out_channels):
110
+ super(AttentivePooling, self).__init__()
111
+
112
+ self.score_fn = nn.Sequential(
113
+ nn.Linear(in_channels, in_channels, bias=False),
114
+ nn.Softmax(dim=-2)
115
+ )
116
+ self.mlp = SharedMLP(in_channels, out_channels, bn=True, activation_fn=nn.ReLU())
117
+
118
+ def forward(self, x):
119
+ r"""
120
+ Forward pass
121
+
122
+ Parameters
123
+ ----------
124
+ x: torch.Tensor, shape (B, d_in, N, K)
125
+
126
+ Returns
127
+ -------
128
+ torch.Tensor, shape (B, d_out, N, 1)
129
+ """
130
+ # computing attention scores
131
+ scores = self.score_fn(x.permute(0,2,3,1)).permute(0,3,1,2)
132
+
133
+ # sum over the neighbors
134
+ features = torch.sum(scores * x, dim=-1, keepdim=True) # shape (B, d_in, N, 1)
135
+
136
+ return self.mlp(features)
137
+
138
+
139
+
140
+ class LocalFeatureAggregation(nn.Module):
141
+ def __init__(self, d_in, d_out, num_neighbors, device):
142
+ super(LocalFeatureAggregation, self).__init__()
143
+
144
+ self.num_neighbors = num_neighbors
145
+
146
+ self.mlp1 = SharedMLP(d_in, d_out//2, activation_fn=nn.LeakyReLU(0.2))
147
+ self.mlp2 = SharedMLP(d_out, 2*d_out)
148
+ self.shortcut = SharedMLP(d_in, 2*d_out, bn=True)
149
+
150
+ self.lse1 = LocalSpatialEncoding(d_out//2, num_neighbors, device)
151
+ self.lse2 = LocalSpatialEncoding(d_out//2, num_neighbors, device)
152
+
153
+ self.pool1 = AttentivePooling(d_out, d_out//2)
154
+ self.pool2 = AttentivePooling(d_out, d_out)
155
+
156
+ self.lrelu = nn.LeakyReLU()
157
+
158
+ def forward(self, coords, features):
159
+ r"""
160
+ Forward pass
161
+
162
+ Parameters
163
+ ----------
164
+ coords: torch.Tensor, shape (B, N, 3)
165
+ coordinates of the point cloud
166
+ features: torch.Tensor, shape (B, d_in, N, 1)
167
+ features of the point cloud
168
+
169
+ Returns
170
+ -------
171
+ torch.Tensor, shape (B, 2*d_out, N, 1)
172
+ """
173
+ knn_output = knn(coords.cpu().contiguous(), coords.cpu().contiguous(), self.num_neighbors)
174
+
175
+ x = self.mlp1(features)
176
+
177
+ x = self.lse1(coords, x, knn_output)
178
+ x = self.pool1(x)
179
+
180
+ x = self.lse2(coords, x, knn_output)
181
+ x = self.pool2(x)
182
+
183
+ return self.lrelu(self.mlp2(x) + self.shortcut(features))
184
+
185
+
186
+ @MODELS.register_module()
187
+ class RandLANet(nn.Module):
188
+ def __init__(self, d_in, num_classes, num_neighbors=16, decimation=4, device=torch.device('cuda'), **kwargs):
189
+ super(RandLANet, self).__init__()
190
+ self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
191
+ self.num_neighbors = num_neighbors
192
+ self.decimation = decimation
193
+
194
+ self.fc_start = nn.Linear(d_in, 8)
195
+ self.bn_start = nn.Sequential(
196
+ nn.BatchNorm2d(8, eps=1e-6, momentum=0.99),
197
+ nn.LeakyReLU(0.2)
198
+ )
199
+
200
+ # encoding layers
201
+ self.encoder = nn.ModuleList([
202
+ LocalFeatureAggregation(8, 16, num_neighbors, device),
203
+ LocalFeatureAggregation(32, 64, num_neighbors, device),
204
+ LocalFeatureAggregation(128, 128, num_neighbors, device),
205
+ LocalFeatureAggregation(256, 256, num_neighbors, device)
206
+ ])
207
+
208
+ self.mlp = SharedMLP(512, 512, activation_fn=nn.ReLU())
209
+
210
+ # decoding layers
211
+ decoder_kwargs = dict(
212
+ transpose=True,
213
+ bn=True,
214
+ activation_fn=nn.ReLU()
215
+ )
216
+ self.decoder = nn.ModuleList([
217
+ SharedMLP(1024, 256, **decoder_kwargs),
218
+ SharedMLP(512, 128, **decoder_kwargs),
219
+ SharedMLP(256, 32, **decoder_kwargs),
220
+ SharedMLP(64, 8, **decoder_kwargs)
221
+ ])
222
+
223
+ # final semantic prediction
224
+ self.fc_end = nn.Sequential(
225
+ SharedMLP(8, 64, bn=True, activation_fn=nn.ReLU()),
226
+ SharedMLP(64, 32, bn=True, activation_fn=nn.ReLU()),
227
+ nn.Dropout(),
228
+ SharedMLP(32, num_classes)
229
+ )
230
+ self.device = device
231
+
232
+ self = self.to(device)
233
+
234
+ def forward(self, input):
235
+ r"""
236
+ Forward pass
237
+
238
+ Parameters
239
+ ----------
240
+ input: torch.Tensor, shape (B, N, d_in)
241
+ input points
242
+
243
+ Returns
244
+ -------
245
+ torch.Tensor, shape (B, num_classes, N)
246
+ segmentation scores for each point
247
+ """
248
+ N = input.size(1)
249
+ d = self.decimation
250
+
251
+ coords = input[...,:3].clone().cpu()
252
+ x = self.fc_start(input).transpose(-2,-1).unsqueeze(-1)
253
+ x = self.bn_start(x) # shape (B, d, N, 1)
254
+
255
+ decimation_ratio = 1
256
+
257
+ # <<<<<<<<<< ENCODER
258
+ x_stack = []
259
+
260
+ permutation = torch.randperm(N)
261
+ coords = coords[:,permutation]
262
+ x = x[:,:,permutation]
263
+
264
+ for lfa in self.encoder:
265
+ # at iteration i, x.shape = (B, N//(d**i), d_in)
266
+ x = lfa(coords[:,:N//decimation_ratio], x)
267
+ x_stack.append(x.clone())
268
+ decimation_ratio *= d
269
+ x = x[:,:,:N//decimation_ratio]
270
+
271
+
272
+ # # >>>>>>>>>> ENCODER
273
+
274
+ x = self.mlp(x)
275
+
276
+ # <<<<<<<<<< DECODER
277
+ for mlp in self.decoder:
278
+ neighbors, _ = knn(
279
+ coords[:,:N//decimation_ratio].cpu().contiguous(), # original set
280
+ coords[:,:d*N//decimation_ratio].cpu().contiguous(), # upsampled set
281
+ 1
282
+ ) # shape (B, N, 1)
283
+ neighbors = neighbors.to(self.device)
284
+
285
+ extended_neighbors = neighbors.unsqueeze(1).expand(-1, x.size(1), -1, 1)
286
+
287
+ x_neighbors = torch.gather(x, -2, extended_neighbors)
288
+
289
+ x = torch.cat((x_neighbors, x_stack.pop()), dim=1)
290
+
291
+ x = mlp(x)
292
+
293
+ decimation_ratio //= d
294
+
295
+ # >>>>>>>>>> DECODER
296
+ # inverse permutation
297
+ x = x[:,:,torch.argsort(permutation)]
298
+
299
+ scores = self.fc_end(x)
300
+
301
+ return scores.squeeze(-1)
302
+
303
+
304
+ if __name__ == '__main__':
305
+ import time
306
+ device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
307
+
308
+ d_in = 7
309
+ cloud = 1000*torch.randn(1, 2**16, d_in).to(device)
310
+ model = RandLANet(d_in, 6, 16, 4, device)
311
+ # model.load_state_dict(torch.load('checkpoints/checkpoint_100.pth'))
312
+ model.eval()
313
+
314
+ t0 = time.time()
315
+ pred = model(cloud)
316
+ t1 = time.time()
317
+ # print(pred)
318
+ print(t1-t0)
@@ -0,0 +1,342 @@
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch.hub import load_state_dict_from_url
4
+
5
+
6
+ __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
7
+ 'resnet152', 'resnext50_32x4d', 'resnext101_32x8d',
8
+ 'wide_resnet50_2', 'wide_resnet101_2']
9
+
10
+
11
+ model_urls = {
12
+ 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
13
+ 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
14
+ 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
15
+ 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
16
+ 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
17
+ 'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',
18
+ 'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',
19
+ 'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth',
20
+ 'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth',
21
+ }
22
+
23
+
24
+ def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
25
+ """3x3 convolution with padding"""
26
+ return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
27
+ padding=dilation, groups=groups, bias=False, dilation=dilation)
28
+
29
+
30
+ def conv1x1(in_planes, out_planes, stride=1):
31
+ """1x1 convolution"""
32
+ return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
33
+
34
+
35
+ class BasicBlock(nn.Module):
36
+ expansion = 1
37
+
38
+ def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
39
+ base_width=64, dilation=1, norm_layer=None):
40
+ super(BasicBlock, self).__init__()
41
+ if norm_layer is None:
42
+ norm_layer = nn.BatchNorm2d
43
+ if groups != 1 or base_width != 64:
44
+ raise ValueError('BasicBlock only supports groups=1 and base_width=64')
45
+ if dilation > 1:
46
+ raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
47
+ # Both self.conv1 and self.downsample layers downsample the input when stride != 1
48
+ self.conv1 = conv3x3(inplanes, planes, stride)
49
+ self.bn1 = norm_layer(planes)
50
+ self.relu = nn.ReLU(inplace=True)
51
+ self.conv2 = conv3x3(planes, planes)
52
+ self.bn2 = norm_layer(planes)
53
+ self.downsample = downsample
54
+ self.stride = stride
55
+
56
+ def forward(self, x):
57
+ identity = x
58
+
59
+ out = self.conv1(x)
60
+ out = self.bn1(out)
61
+ out = self.relu(out)
62
+
63
+ out = self.conv2(out)
64
+ out = self.bn2(out)
65
+
66
+ if self.downsample is not None:
67
+ identity = self.downsample(x)
68
+
69
+ out += identity
70
+ out = self.relu(out)
71
+
72
+ return out
73
+
74
+
75
+ class Bottleneck(nn.Module):
76
+ # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2)
77
+ # while original implementation places the stride at the first 1x1 convolution(self.conv1)
78
+ # according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385.
79
+ # This variant is also known as ResNet V1.5 and improves accuracy according to
80
+ # https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch.
81
+
82
+ expansion = 4
83
+
84
+ def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
85
+ base_width=64, dilation=1, norm_layer=None):
86
+ super(Bottleneck, self).__init__()
87
+ if norm_layer is None:
88
+ norm_layer = nn.BatchNorm2d
89
+ width = int(planes * (base_width / 64.)) * groups
90
+ # Both self.conv2 and self.downsample layers downsample the input when stride != 1
91
+ self.conv1 = conv1x1(inplanes, width)
92
+ self.bn1 = norm_layer(width)
93
+ self.conv2 = conv3x3(width, width, stride, groups, dilation)
94
+ self.bn2 = norm_layer(width)
95
+ self.conv3 = conv1x1(width, planes * self.expansion)
96
+ self.bn3 = norm_layer(planes * self.expansion)
97
+ self.relu = nn.ReLU(inplace=True)
98
+ self.downsample = downsample
99
+ self.stride = stride
100
+
101
+ def forward(self, x):
102
+ identity = x
103
+
104
+ out = self.conv1(x)
105
+ out = self.bn1(out)
106
+ out = self.relu(out)
107
+
108
+ out = self.conv2(out)
109
+ out = self.bn2(out)
110
+ out = self.relu(out)
111
+
112
+ out = self.conv3(out)
113
+ out = self.bn3(out)
114
+
115
+ if self.downsample is not None:
116
+ identity = self.downsample(x)
117
+
118
+ out += identity
119
+ out = self.relu(out)
120
+
121
+ return out
122
+
123
+
124
+ class ResNet(nn.Module):
125
+
126
+ def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,
127
+ groups=1, width_per_group=64, replace_stride_with_dilation=None,
128
+ norm_layer=None, feature_size=64):
129
+ super(ResNet, self).__init__()
130
+ if norm_layer is None:
131
+ norm_layer = nn.BatchNorm2d
132
+ self._norm_layer = norm_layer
133
+
134
+ self.inplanes = feature_size
135
+ self.dilation = 1
136
+ if replace_stride_with_dilation is None:
137
+ # each element in the tuple indicates if we should replace
138
+ # the 2x2 stride with a dilated convolution instead
139
+ replace_stride_with_dilation = [False, False, False]
140
+ if len(replace_stride_with_dilation) != 3:
141
+ raise ValueError("replace_stride_with_dilation should be None "
142
+ "or a 3-element tuple, got {}".format(replace_stride_with_dilation))
143
+ self.groups = groups
144
+ self.base_width = width_per_group
145
+ self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,
146
+ bias=False)
147
+ self.bn1 = norm_layer(self.inplanes)
148
+ self.relu = nn.ReLU(inplace=True)
149
+ self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
150
+ self.layer1 = self._make_layer(block, feature_size, layers[0])
151
+ self.layer2 = self._make_layer(block, feature_size * 2, layers[1], stride=2,
152
+ dilate=replace_stride_with_dilation[0])
153
+ self.layer3 = self._make_layer(block, feature_size * 4, layers[2], stride=2,
154
+ dilate=replace_stride_with_dilation[1])
155
+ self.layer4 = self._make_layer(block, feature_size * 8, layers[3], stride=2,
156
+ dilate=replace_stride_with_dilation[2])
157
+ self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
158
+ self.fc = nn.Linear(feature_size * 8 * block.expansion, num_classes)
159
+
160
+ for m in self.modules():
161
+ if isinstance(m, nn.Conv2d):
162
+ nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
163
+ elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
164
+ nn.init.constant_(m.weight, 1)
165
+ nn.init.constant_(m.bias, 0)
166
+
167
+ # Zero-initialize the last BN in each residual branch,
168
+ # so that the residual branch starts with zeros, and each residual block behaves like an identity.
169
+ # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
170
+ if zero_init_residual:
171
+ for m in self.modules():
172
+ if isinstance(m, Bottleneck):
173
+ nn.init.constant_(m.bn3.weight, 0)
174
+ elif isinstance(m, BasicBlock):
175
+ nn.init.constant_(m.bn2.weight, 0)
176
+
177
+ def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
178
+ norm_layer = self._norm_layer
179
+ downsample = None
180
+ previous_dilation = self.dilation
181
+ if dilate:
182
+ self.dilation *= stride
183
+ stride = 1
184
+ if stride != 1 or self.inplanes != planes * block.expansion:
185
+ downsample = nn.Sequential(
186
+ conv1x1(self.inplanes, planes * block.expansion, stride),
187
+ norm_layer(planes * block.expansion),
188
+ )
189
+
190
+ layers = []
191
+ layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
192
+ self.base_width, previous_dilation, norm_layer))
193
+ self.inplanes = planes * block.expansion
194
+ for _ in range(1, blocks):
195
+ layers.append(block(self.inplanes, planes, groups=self.groups,
196
+ base_width=self.base_width, dilation=self.dilation,
197
+ norm_layer=norm_layer))
198
+
199
+ return nn.Sequential(*layers)
200
+
201
+ def _forward_impl(self, x):
202
+ # See note [TorchScript super()]
203
+ x = self.conv1(x)
204
+ x = self.bn1(x)
205
+ x = self.relu(x)
206
+ x = self.maxpool(x)
207
+
208
+ x = self.layer1(x)
209
+ x = self.layer2(x)
210
+ x = self.layer3(x)
211
+ x = self.layer4(x)
212
+
213
+ x = self.avgpool(x)
214
+ x = torch.flatten(x, 1)
215
+ x = self.fc(x)
216
+
217
+ return x
218
+
219
+ def forward(self, x):
220
+ return self._forward_impl(x)
221
+
222
+
223
+ def _resnet(arch, block, layers, pretrained, progress, **kwargs):
224
+ model = ResNet(block, layers, **kwargs)
225
+ if pretrained:
226
+ state_dict = load_state_dict_from_url(model_urls[arch],
227
+ progress=progress)
228
+ model.load_state_dict(state_dict)
229
+ return model
230
+
231
+
232
+ def resnet18(pretrained=False, progress=True, **kwargs):
233
+ r"""ResNet-18 model from
234
+ `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
235
+ Args:
236
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
237
+ progress (bool): If True, displays a progress bar of the download to stderr
238
+ """
239
+ return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress,
240
+ **kwargs)
241
+
242
+
243
+ def resnet34(pretrained=False, progress=True, **kwargs):
244
+ r"""ResNet-34 model from
245
+ `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
246
+ Args:
247
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
248
+ progress (bool): If True, displays a progress bar of the download to stderr
249
+ """
250
+ return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress,
251
+ **kwargs)
252
+
253
+
254
+ def resnet50(pretrained=False, progress=True, **kwargs):
255
+ r"""ResNet-50 model from
256
+ `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
257
+ Args:
258
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
259
+ progress (bool): If True, displays a progress bar of the download to stderr
260
+ """
261
+ return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress,
262
+ **kwargs)
263
+
264
+
265
+ def resnet101(pretrained=False, progress=True, **kwargs):
266
+ r"""ResNet-101 model from
267
+ `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
268
+ Args:
269
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
270
+ progress (bool): If True, displays a progress bar of the download to stderr
271
+ """
272
+ return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress,
273
+ **kwargs)
274
+
275
+
276
+ def resnet152(pretrained=False, progress=True, **kwargs):
277
+ r"""ResNet-152 model from
278
+ `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
279
+ Args:
280
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
281
+ progress (bool): If True, displays a progress bar of the download to stderr
282
+ """
283
+ return _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained, progress,
284
+ **kwargs)
285
+
286
+
287
+ def resnext50_32x4d(pretrained=False, progress=True, **kwargs):
288
+ r"""ResNeXt-50 32x4d model from
289
+ `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
290
+ Args:
291
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
292
+ progress (bool): If True, displays a progress bar of the download to stderr
293
+ """
294
+ kwargs['groups'] = 32
295
+ kwargs['width_per_group'] = 4
296
+ return _resnet('resnext50_32x4d', Bottleneck, [3, 4, 6, 3],
297
+ pretrained, progress, **kwargs)
298
+
299
+
300
+ def resnext101_32x8d(pretrained=False, progress=True, **kwargs):
301
+ r"""ResNeXt-101 32x8d model from
302
+ `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
303
+ Args:
304
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
305
+ progress (bool): If True, displays a progress bar of the download to stderr
306
+ """
307
+ kwargs['groups'] = 32
308
+ kwargs['width_per_group'] = 8
309
+ return _resnet('resnext101_32x8d', Bottleneck, [3, 4, 23, 3],
310
+ pretrained, progress, **kwargs)
311
+
312
+
313
+ def wide_resnet50_2(pretrained=False, progress=True, **kwargs):
314
+ r"""Wide ResNet-50-2 model from
315
+ `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_
316
+ The model is the same as ResNet except for the bottleneck number of channels
317
+ which is twice larger in every block. The number of channels in outer 1x1
318
+ convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048
319
+ channels, and in Wide ResNet-50-2 has 2048-1024-2048.
320
+ Args:
321
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
322
+ progress (bool): If True, displays a progress bar of the download to stderr
323
+ """
324
+ kwargs['width_per_group'] = 64 * 2
325
+ return _resnet('wide_resnet50_2', Bottleneck, [3, 4, 6, 3],
326
+ pretrained, progress, **kwargs)
327
+
328
+
329
+ def wide_resnet101_2(pretrained=False, progress=True, **kwargs):
330
+ r"""Wide ResNet-101-2 model from
331
+ `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_
332
+ The model is the same as ResNet except for the bottleneck number of channels
333
+ which is twice larger in every block. The number of channels in outer 1x1
334
+ convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048
335
+ channels, and in Wide ResNet-50-2 has 2048-1024-2048.
336
+ Args:
337
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
338
+ progress (bool): If True, displays a progress bar of the download to stderr
339
+ """
340
+ kwargs['width_per_group'] = 64 * 2
341
+ return _resnet('wide_resnet101_2', Bottleneck, [3, 4, 23, 3],
342
+ pretrained, progress, **kwargs)