graft-pytorch 0.1.7__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.
graft/models/resnet.py ADDED
@@ -0,0 +1,564 @@
1
+ '''ResNet in PyTorch.
2
+ Reference
3
+ Deep Residual Learning for Image Recognition
4
+ https://arxiv.org/abs/1512.03385
5
+ '''
6
+ from typing import Any, Callable, List, Optional, Type, Union, TypeVar, Dict
7
+ import torch
8
+ import torch.nn as nn
9
+ from torch import Tensor
10
+
11
+
12
+ __all__ = [
13
+ "ResNet",
14
+ "ResNet18",
15
+ "ResNet34",
16
+ "ResNet50",
17
+ "ResNet101",
18
+ "ResNet152",
19
+ "ResNext50_32x4d",
20
+ "ResNext101_32x8d",
21
+ "ResNext101_64x4d",
22
+ "wide_resnet50_2",
23
+ "wide_resnet101_2",
24
+ ]
25
+
26
+
27
+ V = TypeVar("V")
28
+ def _ovewrite_value_param(param: str, actual: Optional[V], expected: V) -> V:
29
+ if actual is not None:
30
+ if actual != expected:
31
+ raise ValueError(f"The parameter '{param}' expected value {expected} but got {actual} instead.")
32
+ return expected
33
+
34
+
35
+ def _ovewrite_named_param(kwargs: Dict[str, Any], param: str, new_value: V) -> None:
36
+ if param in kwargs:
37
+ if kwargs[param] != new_value:
38
+ raise ValueError(f"The parameter '{param}' expected value {new_value} but got {kwargs[param]} instead.")
39
+ else:
40
+ kwargs[param] = new_value
41
+
42
+
43
+ def conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, dilation: int = 1) -> nn.Conv2d:
44
+ """3x3 convolution with padding"""
45
+ return nn.Conv2d(
46
+ in_planes,
47
+ out_planes,
48
+ kernel_size=3,
49
+ stride=stride,
50
+ padding=dilation,
51
+ groups=groups,
52
+ bias=False,
53
+ dilation=dilation,
54
+ )
55
+
56
+
57
+ def conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:
58
+ """1x1 convolution"""
59
+ return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
60
+
61
+
62
+ class BasicBlock(nn.Module):
63
+ expansion: int = 1
64
+
65
+ def __init__(
66
+ self,
67
+ inplanes: int,
68
+ planes: int,
69
+ stride: int = 1,
70
+ downsample: Optional[nn.Module] = None,
71
+ groups: int = 1,
72
+ base_width: int = 64,
73
+ dilation: int = 1,
74
+ norm_layer: Optional[Callable[..., nn.Module]] = None,
75
+ ) -> None:
76
+ super().__init__()
77
+ if norm_layer is None:
78
+ norm_layer = nn.BatchNorm2d
79
+ if groups != 1 or base_width != 64:
80
+ raise ValueError("BasicBlock only supports groups=1 and base_width=64")
81
+ if dilation > 1:
82
+ raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
83
+ # Both self.conv1 and self.downsample layers downsample the input when stride != 1
84
+ self.conv1 = conv3x3(inplanes, planes, stride)
85
+ self.bn1 = norm_layer(planes)
86
+ self.relu = nn.ReLU(inplace=True)
87
+ self.conv2 = conv3x3(planes, planes)
88
+ self.bn2 = norm_layer(planes)
89
+ self.downsample = downsample
90
+ self.stride = stride
91
+
92
+ def forward(self, x: Tensor) -> Tensor:
93
+ identity = x
94
+
95
+ out = self.conv1(x)
96
+ out = self.bn1(out)
97
+ out = self.relu(out)
98
+
99
+ out = self.conv2(out)
100
+ out = self.bn2(out)
101
+
102
+ if self.downsample is not None:
103
+ identity = self.downsample(x)
104
+
105
+ out += identity
106
+ out = self.relu(out)
107
+
108
+ return out
109
+
110
+
111
+ class Bottleneck(nn.Module):
112
+ # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2)
113
+ # while original implementation places the stride at the first 1x1 convolution(self.conv1)
114
+ # according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385.
115
+ # This variant is also known as ResNet V1.5 and improves accuracy according to
116
+ # https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch.
117
+
118
+ expansion: int = 4
119
+
120
+ def __init__(
121
+ self,
122
+ inplanes: int,
123
+ planes: int,
124
+ stride: int = 1,
125
+ downsample: Optional[nn.Module] = None,
126
+ groups: int = 1,
127
+ base_width: int = 64,
128
+ dilation: int = 1,
129
+ norm_layer: Optional[Callable[..., nn.Module]] = None,
130
+ ) -> None:
131
+ super().__init__()
132
+ if norm_layer is None:
133
+ norm_layer = nn.BatchNorm2d
134
+ width = int(planes * (base_width / 64.0)) * groups
135
+ # Both self.conv2 and self.downsample layers downsample the input when stride != 1
136
+ self.conv1 = conv1x1(inplanes, width)
137
+ self.bn1 = norm_layer(width)
138
+ self.conv2 = conv3x3(width, width, stride, groups, dilation)
139
+ self.bn2 = norm_layer(width)
140
+ self.conv3 = conv1x1(width, planes * self.expansion)
141
+ self.bn3 = norm_layer(planes * self.expansion)
142
+ self.relu = nn.ReLU(inplace=True)
143
+ self.downsample = downsample
144
+ self.stride = stride
145
+
146
+ def forward(self, x: Tensor) -> Tensor:
147
+ identity = x
148
+
149
+ out = self.conv1(x)
150
+ out = self.bn1(out)
151
+ out = self.relu(out)
152
+
153
+ out = self.conv2(out)
154
+ out = self.bn2(out)
155
+ out = self.relu(out)
156
+
157
+ out = self.conv3(out)
158
+ out = self.bn3(out)
159
+
160
+ if self.downsample is not None:
161
+ identity = self.downsample(x)
162
+
163
+ out += identity
164
+ out = self.relu(out)
165
+
166
+ return out
167
+
168
+
169
+ class ResNet(nn.Module):
170
+ def __init__(
171
+ self,
172
+ block: Type[Union[BasicBlock, Bottleneck]],
173
+ layers: List[int],
174
+ num_classes: int = 1000,
175
+ zero_init_residual: bool = False,
176
+ groups: int = 1,
177
+ width_per_group: int = 64,
178
+ replace_stride_with_dilation: Optional[List[bool]] = None,
179
+ norm_layer: Optional[Callable[..., nn.Module]] = None,
180
+ ) -> None:
181
+ super().__init__()
182
+ # _log_api_usage_once(self)
183
+ if norm_layer is None:
184
+ norm_layer = nn.BatchNorm2d
185
+ self._norm_layer = norm_layer
186
+
187
+ self.inplanes = 64
188
+ self.dilation = 1
189
+ if replace_stride_with_dilation is None:
190
+ # each element in the tuple indicates if we should replace
191
+ # the 2x2 stride with a dilated convolution instead
192
+ replace_stride_with_dilation = [False, False, False]
193
+ if len(replace_stride_with_dilation) != 3:
194
+ raise ValueError(
195
+ "replace_stride_with_dilation should be None "
196
+ f"or a 3-element tuple, got {replace_stride_with_dilation}"
197
+ )
198
+ self.groups = groups
199
+ self.base_width = width_per_group
200
+ self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False)
201
+ self.bn1 = norm_layer(self.inplanes)
202
+ self.relu = nn.ReLU(inplace=True)
203
+ self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
204
+ self.layer1 = self._make_layer(block, 64, layers[0])
205
+ self.layer2 = self._make_layer(block, 128, layers[1], stride=2, dilate=replace_stride_with_dilation[0])
206
+ self.layer3 = self._make_layer(block, 256, layers[2], stride=2, dilate=replace_stride_with_dilation[1])
207
+ self.layer4 = self._make_layer(block, 512, layers[3], stride=2, dilate=replace_stride_with_dilation[2])
208
+ self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
209
+ self.fc = nn.Linear(512 * block.expansion, num_classes)
210
+ self.embDim = 512 * block.expansion
211
+ for m in self.modules():
212
+ if isinstance(m, nn.Conv2d):
213
+ nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
214
+ elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
215
+ nn.init.constant_(m.weight, 1)
216
+ nn.init.constant_(m.bias, 0)
217
+
218
+ # Zero-initialize the last BN in each residual branch,
219
+ # so that the residual branch starts with zeros, and each residual block behaves like an identity.
220
+ # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
221
+ if zero_init_residual:
222
+ for m in self.modules():
223
+ if isinstance(m, Bottleneck) and m.bn3.weight is not None:
224
+ nn.init.constant_(m.bn3.weight, 0) # type: ignore[arg-type]
225
+ elif isinstance(m, BasicBlock) and m.bn2.weight is not None:
226
+ nn.init.constant_(m.bn2.weight, 0) # type: ignore[arg-type]
227
+
228
+ def _make_layer(
229
+ self,
230
+ block: Type[Union[BasicBlock, Bottleneck]],
231
+ planes: int,
232
+ blocks: int,
233
+ stride: int = 1,
234
+ dilate: bool = False,
235
+ ) -> nn.Sequential:
236
+ norm_layer = self._norm_layer
237
+ downsample = None
238
+ previous_dilation = self.dilation
239
+ if dilate:
240
+ self.dilation *= stride
241
+ stride = 1
242
+ if stride != 1 or self.inplanes != planes * block.expansion:
243
+ downsample = nn.Sequential(
244
+ conv1x1(self.inplanes, planes * block.expansion, stride),
245
+ norm_layer(planes * block.expansion),
246
+ )
247
+
248
+ layers = []
249
+ layers.append(
250
+ block(
251
+ self.inplanes, planes, stride, downsample, self.groups, self.base_width, previous_dilation, norm_layer
252
+ )
253
+ )
254
+ self.inplanes = planes * block.expansion
255
+ for _ in range(1, blocks):
256
+ layers.append(
257
+ block(
258
+ self.inplanes,
259
+ planes,
260
+ groups=self.groups,
261
+ base_width=self.base_width,
262
+ dilation=self.dilation,
263
+ norm_layer=norm_layer,
264
+ )
265
+ )
266
+
267
+ return nn.Sequential(*layers)
268
+
269
+ def _forward_impl(self, x: Tensor, last=False, freeze=False) -> Tensor:
270
+ # See note [TorchScript super()]
271
+ if freeze:
272
+ with torch.no_grad():
273
+ self.eval()
274
+ x = self.conv1(x)
275
+ x = self.bn1(x)
276
+ x = self.relu(x)
277
+ x = self.maxpool(x)
278
+ x = self.layer1(x)
279
+ x = self.layer2(x)
280
+ x = self.layer3(x)
281
+ x = self.layer4(x)
282
+ x = self.avgpool(x)
283
+ features = torch.flatten(x, 1)
284
+ self.train()
285
+ else:
286
+ x = self.conv1(x)
287
+ x = self.bn1(x)
288
+ x = self.relu(x)
289
+ x = self.maxpool(x)
290
+ x = self.layer1(x)
291
+ x = self.layer2(x)
292
+ x = self.layer3(x)
293
+ x = self.layer4(x)
294
+ x = self.avgpool(x)
295
+ features = torch.flatten(x, 1)
296
+
297
+ out = self.fc(features)
298
+ if last:
299
+ return out, features
300
+ else:
301
+ return out
302
+
303
+ def forward(self, x: Tensor, last=False, freeze=False) -> Tensor:
304
+ return self._forward_impl(x, last, freeze)
305
+
306
+ def get_embedding_dim(self):
307
+ return self.embDim
308
+
309
+ def get_grads(self) -> torch.Tensor:
310
+ """
311
+ Returns all the gradients concatenated in a single tensor.
312
+ :return: gradients tensor (??)
313
+ """
314
+ grads = []
315
+ for pp in list(self.parameters()):
316
+ if pp.requires_grad: # only using the parameter that require the gradient
317
+ grads.append(pp.grad.view(-1))
318
+ return torch.cat(grads)
319
+
320
+
321
+ def _resnet(
322
+ block: Type[Union[BasicBlock, Bottleneck]],
323
+ layers: List[int],
324
+ **kwargs: Any,
325
+ ) -> ResNet:
326
+ model = ResNet(block, layers, **kwargs)
327
+ return model
328
+
329
+
330
+
331
+ def ResNet18(num_classes: int, **kwargs: Any) -> ResNet:
332
+ """ResNet-18 from `Deep Residual Learning for Image Recognition <https://arxiv.org/pdf/1512.03385.pdf>`__.
333
+ Args:
334
+ weights (:class:`~torchvision.models.ResNet18_Weights`, optional): The
335
+ pretrained weights to use. See
336
+ :class:`~torchvision.models.ResNet18_Weights` below for
337
+ more details, and possible values. By default, no pre-trained
338
+ weights are used.
339
+ progress (bool, optional): If True, displays a progress bar of the
340
+ download to stderr. Default is True.
341
+ **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet``
342
+ base class. Please refer to the `source code
343
+ <https://github.com/pytorch/vision/blob/main/torchvision/models/resnet.py>`_
344
+ for more details about this class.
345
+ .. autoclass:: torchvision.models.ResNet18_Weights
346
+ :members:
347
+ """
348
+ return _resnet(BasicBlock, [2, 2, 2, 2], num_classes=num_classes, **kwargs)
349
+
350
+ def ResNet34(num_classes: int, **kwargs: Any) -> ResNet:
351
+ """ResNet-34 from `Deep Residual Learning for Image Recognition <https://arxiv.org/pdf/1512.03385.pdf>`__.
352
+ Args:
353
+ weights (:class:`~torchvision.models.ResNet34_Weights`, optional): The
354
+ pretrained weights to use. See
355
+ :class:`~torchvision.models.ResNet34_Weights` below for
356
+ more details, and possible values. By default, no pre-trained
357
+ weights are used.
358
+ progress (bool, optional): If True, displays a progress bar of the
359
+ download to stderr. Default is True.
360
+ **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet``
361
+ base class. Please refer to the `source code
362
+ <https://github.com/pytorch/vision/blob/main/torchvision/models/resnet.py>`_
363
+ for more details about this class.
364
+ .. autoclass:: torchvision.models.ResNet34_Weights
365
+ :members:
366
+ """
367
+ return _resnet(BasicBlock, [3, 4, 6, 3], num_classes=num_classes, **kwargs)
368
+
369
+
370
+ def ResNet50(num_classes: int, **kwargs: Any) -> ResNet:
371
+ """ResNet-50 from `Deep Residual Learning for Image Recognition <https://arxiv.org/pdf/1512.03385.pdf>`__.
372
+ .. note::
373
+ The bottleneck of TorchVision places the stride for downsampling to the second 3x3
374
+ convolution while the original paper places it to the first 1x1 convolution.
375
+ This variant improves the accuracy and is known as `ResNet V1.5
376
+ <https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch>`_.
377
+ Args:
378
+ weights (:class:`~torchvision.models.ResNet50_Weights`, optional): The
379
+ pretrained weights to use. See
380
+ :class:`~torchvision.models.ResNet50_Weights` below for
381
+ more details, and possible values. By default, no pre-trained
382
+ weights are used.
383
+ progress (bool, optional): If True, displays a progress bar of the
384
+ download to stderr. Default is True.
385
+ **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet``
386
+ base class. Please refer to the `source code
387
+ <https://github.com/pytorch/vision/blob/main/torchvision/models/resnet.py>`_
388
+ for more details about this class.
389
+ .. autoclass:: torchvision.models.ResNet50_Weights
390
+ :members:
391
+ """
392
+ return _resnet(Bottleneck, [3, 4, 6, 3], num_classes=num_classes, **kwargs)
393
+
394
+
395
+
396
+ def ResNet101(num_classes: int, **kwargs: Any) -> ResNet:
397
+ """ResNet-101 from `Deep Residual Learning for Image Recognition <https://arxiv.org/pdf/1512.03385.pdf>`__.
398
+ .. note::
399
+ The bottleneck of TorchVision places the stride for downsampling to the second 3x3
400
+ convolution while the original paper places it to the first 1x1 convolution.
401
+ This variant improves the accuracy and is known as `ResNet V1.5
402
+ <https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch>`_.
403
+ Args:
404
+ weights (:class:`~torchvision.models.ResNet101_Weights`, optional): The
405
+ pretrained weights to use. See
406
+ :class:`~torchvision.models.ResNet101_Weights` below for
407
+ more details, and possible values. By default, no pre-trained
408
+ weights are used.
409
+ progress (bool, optional): If True, displays a progress bar of the
410
+ download to stderr. Default is True.
411
+ **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet``
412
+ base class. Please refer to the `source code
413
+ <https://github.com/pytorch/vision/blob/main/torchvision/models/resnet.py>`_
414
+ for more details about this class.
415
+ .. autoclass:: torchvision.models.ResNet101_Weights
416
+ :members:
417
+ """
418
+ return _resnet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes, **kwargs)
419
+
420
+
421
+ def ResNet152(num_classes: int, **kwargs: Any) -> ResNet:
422
+ """ResNet-152 from `Deep Residual Learning for Image Recognition <https://arxiv.org/pdf/1512.03385.pdf>`__.
423
+ .. note::
424
+ The bottleneck of TorchVision places the stride for downsampling to the second 3x3
425
+ convolution while the original paper places it to the first 1x1 convolution.
426
+ This variant improves the accuracy and is known as `ResNet V1.5
427
+ <https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch>`_.
428
+ Args:
429
+ weights (:class:`~torchvision.models.ResNet152_Weights`, optional): The
430
+ pretrained weights to use. See
431
+ :class:`~torchvision.models.ResNet152_Weights` below for
432
+ more details, and possible values. By default, no pre-trained
433
+ weights are used.
434
+ progress (bool, optional): If True, displays a progress bar of the
435
+ download to stderr. Default is True.
436
+ **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet``
437
+ base class. Please refer to the `source code
438
+ <https://github.com/pytorch/vision/blob/main/torchvision/models/resnet.py>`_
439
+ for more details about this class.
440
+ .. autoclass:: torchvision.models.ResNet152_Weights
441
+ :members:
442
+ """
443
+ return _resnet(Bottleneck, [3, 8, 36, 3], num_classes=num_classes, **kwargs)
444
+
445
+
446
+ def ResNext50_32x4d(num_classes: int, **kwargs: Any) -> ResNet:
447
+ """ResNeXt-50 32x4d model from
448
+ `Aggregated Residual Transformation for Deep Neural Networks <https://arxiv.org/abs/1611.05431>`_.
449
+ Args:
450
+ weights (:class:`~torchvision.models.ResNeXt50_32X4D_Weights`, optional): The
451
+ pretrained weights to use. See
452
+ :class:`~torchvision.models.ResNext50_32X4D_Weights` below for
453
+ more details, and possible values. By default, no pre-trained
454
+ weights are used.
455
+ progress (bool, optional): If True, displays a progress bar of the
456
+ download to stderr. Default is True.
457
+ **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet``
458
+ base class. Please refer to the `source code
459
+ <https://github.com/pytorch/vision/blob/main/torchvision/models/resnet.py>`_
460
+ for more details about this class.
461
+ .. autoclass:: torchvision.models.ResNeXt50_32X4D_Weights
462
+ :members:
463
+ """
464
+ _ovewrite_named_param(kwargs, "groups", 32)
465
+ _ovewrite_named_param(kwargs, "width_per_group", 4)
466
+ return _resnet(Bottleneck, [3, 4, 6, 3], num_classes=num_classes, **kwargs)
467
+
468
+
469
+ def ResNext101_32x8d(num_classes: int, **kwargs: Any) -> ResNet:
470
+ """ResNeXt-101 32x8d model from
471
+ `Aggregated Residual Transformation for Deep Neural Networks <https://arxiv.org/abs/1611.05431>`_.
472
+ Args:
473
+ weights (:class:`~torchvision.models.ResNeXt101_32X8D_Weights`, optional): The
474
+ pretrained weights to use. See
475
+ :class:`~torchvision.models.ResNeXt101_32X8D_Weights` below for
476
+ more details, and possible values. By default, no pre-trained
477
+ weights are used.
478
+ progress (bool, optional): If True, displays a progress bar of the
479
+ download to stderr. Default is True.
480
+ **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet``
481
+ base class. Please refer to the `source code
482
+ <https://github.com/pytorch/vision/blob/main/torchvision/models/resnet.py>`_
483
+ for more details about this class.
484
+ .. autoclass:: torchvision.models.ResNeXt101_32X8D_Weights
485
+ :members:
486
+ """
487
+ _ovewrite_named_param(kwargs, "groups", 32)
488
+ _ovewrite_named_param(kwargs, "width_per_group", 8)
489
+ return _resnet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes, **kwargs)
490
+
491
+
492
+ def ResNext101_64x4d(num_classes: int, **kwargs: Any) -> ResNet:
493
+ """ResNeXt-101 64x4d model from
494
+ `Aggregated Residual Transformation for Deep Neural Networks <https://arxiv.org/abs/1611.05431>`_.
495
+ Args:
496
+ weights (:class:`~torchvision.models.ResNeXt101_64X4D_Weights`, optional): The
497
+ pretrained weights to use. See
498
+ :class:`~torchvision.models.ResNeXt101_64X4D_Weights` below for
499
+ more details, and possible values. By default, no pre-trained
500
+ weights are used.
501
+ progress (bool, optional): If True, displays a progress bar of the
502
+ download to stderr. Default is True.
503
+ **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet``
504
+ base class. Please refer to the `source code
505
+ <https://github.com/pytorch/vision/blob/main/torchvision/models/resnet.py>`_
506
+ for more details about this class.
507
+ .. autoclass:: torchvision.models.ResNeXt101_64X4D_Weights
508
+ :members:
509
+ """
510
+ _ovewrite_named_param(kwargs, "groups", 64)
511
+ _ovewrite_named_param(kwargs, "width_per_group", 4)
512
+ return _resnet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes, **kwargs)
513
+
514
+
515
+ def wide_resnet50_2(num_classes: int, **kwargs: Any) -> ResNet:
516
+ """Wide ResNet-50-2 model from
517
+ `Wide Residual Networks <https://arxiv.org/abs/1605.07146>`_.
518
+ The model is the same as ResNet except for the bottleneck number of channels
519
+ which is twice larger in every block. The number of channels in outer 1x1
520
+ convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048
521
+ channels, and in Wide ResNet-50-2 has 2048-1024-2048.
522
+ Args:
523
+ weights (:class:`~torchvision.models.Wide_ResNet50_2_Weights`, optional): The
524
+ pretrained weights to use. See
525
+ :class:`~torchvision.models.Wide_ResNet50_2_Weights` below for
526
+ more details, and possible values. By default, no pre-trained
527
+ weights are used.
528
+ progress (bool, optional): If True, displays a progress bar of the
529
+ download to stderr. Default is True.
530
+ **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet``
531
+ base class. Please refer to the `source code
532
+ <https://github.com/pytorch/vision/blob/main/torchvision/models/resnet.py>`_
533
+ for more details about this class.
534
+ .. autoclass:: torchvision.models.Wide_ResNet50_2_Weights
535
+ :members:
536
+ """
537
+ _ovewrite_named_param(kwargs, "width_per_group", 64 * 2)
538
+ return _resnet(Bottleneck, [3, 4, 6, 3], num_classes=num_classes, **kwargs)
539
+
540
+
541
+ def wide_resnet101_2(num_classes: int, **kwargs: Any) -> ResNet:
542
+ """Wide ResNet-101-2 model from
543
+ `Wide Residual Networks <https://arxiv.org/abs/1605.07146>`_.
544
+ The model is the same as ResNet except for the bottleneck number of channels
545
+ which is twice larger in every block. The number of channels in outer 1x1
546
+ convolutions is the same, e.g. last block in ResNet-101 has 2048-512-2048
547
+ channels, and in Wide ResNet-101-2 has 2048-1024-2048.
548
+ Args:
549
+ weights (:class:`~torchvision.models.Wide_ResNet101_2_Weights`, optional): The
550
+ pretrained weights to use. See
551
+ :class:`~torchvision.models.Wide_ResNet101_2_Weights` below for
552
+ more details, and possible values. By default, no pre-trained
553
+ weights are used.
554
+ progress (bool, optional): If True, displays a progress bar of the
555
+ download to stderr. Default is True.
556
+ **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet``
557
+ base class. Please refer to the `source code
558
+ <https://github.com/pytorch/vision/blob/main/torchvision/models/resnet.py>`_
559
+ for more details about this class.
560
+ .. autoclass:: torchvision.models.Wide_ResNet101_2_Weights
561
+ :members:
562
+ """
563
+ _ovewrite_named_param(kwargs, "width_per_group", 64 * 2)
564
+ return _resnet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes, **kwargs)
@@ -0,0 +1,72 @@
1
+ import torch.nn as nn
2
+ import torch
3
+ from torch import Tensor
4
+
5
+
6
+ def conv_block(in_channels, out_channels, pool=False):
7
+ layers = [nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),
8
+ nn.BatchNorm2d(out_channels),
9
+ nn.ReLU(inplace=True)]
10
+ if pool: layers.append(nn.MaxPool2d(2))
11
+ return nn.Sequential(*layers)
12
+
13
+ class ResNet9(nn.Module):
14
+ def __init__(self, in_channels, num_classes):
15
+ super().__init__()
16
+
17
+ self.conv1 = conv_block(in_channels, 64)
18
+ self.conv2 = conv_block(64, 128, pool=True)
19
+ self.res1 = nn.Sequential(conv_block(128, 128), conv_block(128, 128))
20
+
21
+ self.conv3 = conv_block(128, 256, pool=True)
22
+ self.conv4 = conv_block(256, 512, pool=True)
23
+ self.res2 = nn.Sequential(conv_block(512, 512), conv_block(512, 512))
24
+
25
+ self.pool = nn.MaxPool2d(4)
26
+ self.fc = nn.Linear(512, num_classes)
27
+ # self.classifier = nn.Sequential(nn.MaxPool2d(4),
28
+ # nn.Flatten(),
29
+ # nn.Linear(512, num_classes))
30
+
31
+ # def forward(self, xb):
32
+ # out = self.conv1(xb)
33
+ # out = self.conv2(out)
34
+ # out = self.res1(out) + out
35
+ # out = self.conv3(out)
36
+ # out = self.conv4(out)
37
+ # out = self.res2(out) + out
38
+ # out = self.classifier(out)
39
+ # return out
40
+
41
+ def _forward_impl(self, x: Tensor, last=False, freeze=False) -> Tensor:
42
+ # See note [TorchScript super()]
43
+ if freeze:
44
+ with torch.no_grad():
45
+ self.eval()
46
+ x = self.conv1(x)
47
+ x = self.conv2(x)
48
+ x = self.res1(x) + x
49
+ x = self.conv3(x)
50
+ x = self.conv4(x)
51
+ x = self.res2(x) + x
52
+ x = self.pool(x)
53
+ features = torch.flatten(x, 1)
54
+ self.train()
55
+ else:
56
+ x = self.conv1(x)
57
+ x = self.conv2(x)
58
+ x = self.res1(x) + x
59
+ x = self.conv3(x)
60
+ x = self.conv4(x)
61
+ x = self.res2(x) + x
62
+ x = self.pool(x)
63
+ features = torch.flatten(x, 1)
64
+
65
+ out = self.fc(features)
66
+ if last:
67
+ return out, features
68
+ else:
69
+ return out
70
+
71
+ def forward(self, x: Tensor, last=False, freeze=False) -> Tensor:
72
+ return self._forward_impl(x, last, freeze)