netloader 3.11.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.
@@ -0,0 +1,582 @@
1
+ """
2
+ PyTorch-Network-Loader Python implementation of ConvNeXt.
3
+ See the ConvNeXt paper: arXiv:2201.03545.
4
+ See the ConvNeXt GitHub: https://github.com/facebookresearch/ConvNeXt.
5
+ """
6
+ from typing import Any
7
+
8
+ import numpy as np
9
+ from torch import nn
10
+
11
+ from netloader import layers
12
+ from netloader.network import Network
13
+ from netloader.utils import Config, Shapes
14
+ from netloader.layers.base import BaseLayer
15
+
16
+
17
+ class ConvNeXt(Network):
18
+ """
19
+ ConvNeXt network using Network.
20
+
21
+ Original paper implementation: arXiv:2201.03545.
22
+
23
+ Attributes
24
+ ----------
25
+ layer_num : int, Optional
26
+ Number of layers to use, if None use all layers
27
+ group : int
28
+ Which group is the active group if a layer has the group attribute
29
+ name : str
30
+ Name of the network, used for saving
31
+ version : str
32
+ NetLoader version string
33
+ checkpoints : list[TensorListLike]
34
+ Outputs from each checkpoint with each Tensor having shape (N,...) and type float, where N
35
+ is the batch size
36
+ config : dict[str, Any]
37
+ Network configuration
38
+ kl_loss : Tensor
39
+ KL divergence loss on the latent space, of shape (1) and type float, if using a sample layer
40
+ net : ModuleList
41
+ Network construction
42
+ shapes : Shapes
43
+ Layer output shapes
44
+ check_shapes : Shapes
45
+ Checkpoint output shapes
46
+ """
47
+ def __init__(
48
+ self,
49
+ name: str,
50
+ in_shape: list[int] | tuple[int, ...],
51
+ out_shape: list[int],
52
+ *,
53
+ max_drop_path: float = 0,
54
+ layer_scale: float = 1e-6,
55
+ dims: list[int] | None = None,
56
+ depths: list[int] | None = None) -> None:
57
+ """
58
+ Parameters
59
+ ----------
60
+ name : str
61
+ Name of the network configuration file
62
+ in_shape : list[int] | tuple[int, ...]
63
+ Shape of the input tensor, excluding batch size
64
+ out_shape : list[int]
65
+ shape of the output tensor, excluding batch size
66
+ max_drop_path : float, Optional
67
+ Maximum drop path fraction, default = 0
68
+ layer_scale : float, Optional
69
+ Default value for learnable parameters to scale the convolutional filters in a ConvNeXt
70
+ block, default = 1e-6
71
+ dims : list[int] | None, Optional
72
+ Number of convolutional filters in each downscaled section of the network,
73
+ default = [96, 192, 384, 768]
74
+ depths : list[int] | None, Optional
75
+ Number of ConvNeXt blocks in each downscaled section of the network,
76
+ default = [3, 3, 9, 3]
77
+ """
78
+ super().__init__(
79
+ name,
80
+ Config(),
81
+ in_shape,
82
+ [],
83
+ suppress_warning=True,
84
+ )
85
+ self._layer_scale: float = layer_scale
86
+ self._max_drop_path: float = max_drop_path
87
+ self._dims: list[int] = dims or [96, 192, 384, 768]
88
+ self._depths: list[int] = depths or [3, 3, 9, 3]
89
+ self._build_net(out_shape)
90
+ self.apply(self._init_weights)
91
+
92
+ def __getstate__(self) -> dict[str, Any]:
93
+ """
94
+ Returns a dictionary containing the state of the network for pickling
95
+
96
+ Returns
97
+ -------
98
+ dict[str, Any]
99
+ Dictionary containing the state of the network
100
+ """
101
+ return super().__getstate__() | {
102
+ 'dims': self._dims,
103
+ 'depths': self._depths,
104
+ 'layer_scale': self._layer_scale,
105
+ 'max_drop_path': self._max_drop_path,
106
+ }
107
+
108
+ def __setstate__(self, state: dict[str, Any]) -> None:
109
+ """
110
+ Sets the state of the network for pickling
111
+
112
+ Parameters
113
+ ----------
114
+ state : dict[str, Any]
115
+ Dictionary containing the state of the network
116
+ """
117
+ super().__init__(
118
+ state['name'],
119
+ Config(),
120
+ state['shapes'][0],
121
+ [],
122
+ suppress_warning=True,
123
+ )
124
+ self._layer_scale = state['layer_scale']
125
+ self._max_drop_path = state['max_drop_path']
126
+ self._dims = state['dims']
127
+ self._depths = state['depths']
128
+ self.shapes = Shapes([state['shapes'][0]])
129
+
130
+ self._build_net(state['shapes'][-1])
131
+ self.load_state_dict(state['layers'])
132
+
133
+ @staticmethod
134
+ def _init_weights(layer: nn.Module) -> None:
135
+ """
136
+ Initialises the weights of the convolutional and linear layers.
137
+
138
+ Parameters
139
+ ----------
140
+ layer : Module
141
+ Layer to initialise if it is convolutional or linear
142
+ """
143
+ if isinstance(layer, (nn.Conv1d, nn.Conv2d, nn.Conv3d, nn.Linear)):
144
+ nn.init.trunc_normal_(layer.weight, std=0.02)
145
+
146
+ if layer.bias is not None:
147
+ nn.init.constant_(layer.bias, 0)
148
+
149
+ def _build_net(self, out_shape: list[int]) -> None:
150
+ """
151
+ Constructs the ConvNeXt network layers.
152
+
153
+ Parameters
154
+ ----------
155
+ out_shape : list[int]
156
+ shape of the output tensor, excluding batch size
157
+ """
158
+ assert isinstance(self.shapes, list)
159
+ drop_paths: list[float]
160
+ depths: list[int] = np.cumsum(self._depths).tolist()
161
+ kwargs: dict[str, Any] = {'check_shapes': Shapes()}
162
+ drop_paths = np.linspace(0, self._max_drop_path, depths[-1]).tolist()
163
+
164
+ # Stem
165
+ self.layers.extend(self._stem(out_shape, **kwargs))
166
+
167
+ # Main body
168
+ for dim, in_depth, out_depth in zip(self._dims, [0, *depths], depths):
169
+ # Downscaling, this is skipped in the first iteration
170
+ self.layers.extend([
171
+ layers.LayerNorm(dims=1, shapes=self.shapes, **kwargs),
172
+ layers.ConvDownscale(
173
+ out_shape,
174
+ self.shapes,
175
+ filters=dim,
176
+ scale=2,
177
+ activation=None if self.version != '<3.8.1' else 'ELU',
178
+ **kwargs,
179
+ ),
180
+ ] if dim != self._dims[0] else [])
181
+
182
+ # ConvNeXt blocks
183
+ self.layers.extend([layers.ConvNeXtBlock(
184
+ out_shape,
185
+ self.shapes,
186
+ drop_path=drop_path,
187
+ layer_scale=self._layer_scale,
188
+ ) for drop_path in drop_paths[in_depth:out_depth]])
189
+
190
+ # Head
191
+ self.layers.extend(self._head(out_shape, **kwargs))
192
+
193
+ def _head(self, out_shape: list[int], **kwargs: Any) -> list[BaseLayer]:
194
+ """
195
+ Head of ConvNeXt for adapting the learned features into the desired output.
196
+
197
+ Parameters
198
+ ----------
199
+ out_shape : list[int]
200
+ shape of the output tensor, excluding batch size
201
+
202
+ **kwargs
203
+ Global network parameters
204
+
205
+ Returns
206
+ -------
207
+ list[BaseLayer]
208
+ Layers used in the head
209
+ """
210
+ return [
211
+ layers.AdaptivePool(1, self.shapes, **kwargs),
212
+ layers.Reshape([-1], shapes=self.shapes, **kwargs),
213
+ layers.LayerNorm(dims=1, shapes=self.shapes, **kwargs),
214
+ layers.Linear(
215
+ out_shape,
216
+ self.shapes,
217
+ factor=1,
218
+ activation=None if self.version != '<3.8.1' else 'SELU',
219
+ **kwargs,
220
+ ),
221
+ ]
222
+
223
+ def _stem(self, out_shape: list[int], **kwargs: Any) -> list[BaseLayer]:
224
+ """
225
+ Stem of ConvNeXt for initial downscaling of the input.
226
+
227
+ Parameters
228
+ ----------
229
+ out_shape : list[int]
230
+ shape of the output tensor, excluding batch size
231
+
232
+ **kwargs
233
+ Global network parameters
234
+
235
+ Returns
236
+ -------
237
+ list[BaseLayer]
238
+ Layers used in the stem
239
+ """
240
+ return [
241
+ layers.ConvDownscale(
242
+ out_shape,
243
+ self.shapes,
244
+ filters=self._dims[0],
245
+ scale=4,
246
+ activation=None if self.version != '<3.8.1' else 'ELU',
247
+ norm='layer',
248
+ **kwargs,
249
+ ),
250
+ ]
251
+
252
+
253
+ class ConvNeXtTiny(ConvNeXt):
254
+ """
255
+ Tiny version of ConvNeXt with the number of convolutional filters in each downscaled section
256
+ following [96, 192, 384, 768] with the number of ConvNeXt blocks in each downscaled section
257
+ following [3, 3, 9, 3].
258
+
259
+ Original paper implementation: arXiv:2201.03545.
260
+
261
+ Attributes
262
+ ----------
263
+ layer_num : int, Optional
264
+ Number of layers to use, if None use all layers
265
+ group : int
266
+ Which group is the active group if a layer has the group attribute
267
+ name : str
268
+ Name of the network, used for saving
269
+ version : str
270
+ NetLoader version string
271
+ checkpoints : list[TensorListLike]
272
+ Outputs from each checkpoint with each Tensor having shape (N,...) and type float, where N
273
+ is the batch size
274
+ config : dict[str, Any]
275
+ Network configuration
276
+ kl_loss : Tensor
277
+ KL divergence loss on the latent space, of shape (1) and type float, if using a sample layer
278
+ net : ModuleList
279
+ Network construction
280
+ shapes : Shapes
281
+ Layer output shapes
282
+ check_shapes : Shapes
283
+ Checkpoint output shapes
284
+ """
285
+ _name: str = 'convnext_tiny'
286
+
287
+ def __init__(
288
+ self,
289
+ in_shape: list[int] | tuple[int, ...],
290
+ out_shape: list[int],
291
+ *,
292
+ max_drop_path: float = 0,
293
+ layer_scale: float = 1e-6) -> None:
294
+ """
295
+ Parameters
296
+ ----------
297
+ in_shape : list[int] | list[list[int]] | tuple[int, ...]
298
+ Shape of the input tensor(s), excluding batch size
299
+ out_shape : list[int]
300
+ shape of the output tensor, excluding batch size
301
+ max_drop_path : float, Optional
302
+ Maximum drop path fraction, default = 0
303
+ layer_scale : float, Optional
304
+ Default value for learnable parameters to scale the convolutional filters in a ConvNeXt
305
+ block, default = 1e-6
306
+ """
307
+ super().__init__(
308
+ self._name,
309
+ in_shape,
310
+ out_shape,
311
+ max_drop_path=max_drop_path,
312
+ layer_scale=layer_scale,
313
+ )
314
+
315
+
316
+ class ConvNeXtSmall(ConvNeXt):
317
+ """
318
+ Small version of ConvNeXt with the number of convolutional filters in each downscaled section
319
+ following [96, 192, 384, 768] with the number of ConvNeXt blocks in each downscaled section
320
+ following [3, 3, 27, 3].
321
+
322
+ Original paper implementation: arXiv:2201.03545.
323
+
324
+ Attributes
325
+ ----------
326
+ layer_num : int, Optional
327
+ Number of layers to use, if None use all layers
328
+ group : int
329
+ Which group is the active group if a layer has the group attribute
330
+ name : str
331
+ Name of the network, used for saving
332
+ version : str
333
+ NetLoader version string
334
+ checkpoints : list[TensorListLike]
335
+ Outputs from each checkpoint with each Tensor having shape (N,...) and type float, where N
336
+ is the batch size
337
+ config : dict[str, Any]
338
+ Network configuration
339
+ kl_loss : Tensor
340
+ KL divergence loss on the latent space, of shape (1) and type float, if using a sample layer
341
+ net : ModuleList
342
+ Network construction
343
+ shapes : Shapes
344
+ Layer output shapes
345
+ check_shapes : Shapes
346
+ Checkpoint output shapes
347
+ """
348
+ _name: str = 'convnext_small'
349
+
350
+ def __init__(
351
+ self,
352
+ in_shape: list[int] | tuple[int, ...],
353
+ out_shape: list[int],
354
+ *,
355
+ max_drop_path: float = 0,
356
+ layer_scale: float = 1e-6) -> None:
357
+ """
358
+ Parameters
359
+ ----------
360
+ in_shape : list[int] | list[list[int]] | tuple[int, ...]
361
+ Shape of the input tensor(s), excluding batch size
362
+ out_shape : list[int]
363
+ shape of the output tensor, excluding batch size
364
+ max_drop_path : float, Optional
365
+ Maximum drop path fraction, default = 0
366
+ layer_scale : float, Optional
367
+ Default value for learnable parameters to scale the convolutional filters in a ConvNeXt
368
+ block, default = 1e-6
369
+ """
370
+ super().__init__(
371
+ self._name,
372
+ in_shape,
373
+ out_shape,
374
+ max_drop_path=max_drop_path,
375
+ layer_scale=layer_scale,
376
+ depths=[3, 3, 27, 3],
377
+ )
378
+
379
+
380
+ class ConvNeXtBase(ConvNeXt):
381
+ """
382
+ Base version of ConvNeXt with the number of convolutional filters in each downscaled section
383
+ following [128, 256, 512, 1024] with the number of ConvNeXt blocks in each downscaled section
384
+ following [3, 3, 27, 3].
385
+
386
+ Original paper implementation: arXiv:2201.03545.
387
+
388
+ Attributes
389
+ ----------
390
+ layer_num : int, Optional
391
+ Number of layers to use, if None use all layers
392
+ group : int
393
+ Which group is the active group if a layer has the group attribute
394
+ name : str
395
+ Name of the network, used for saving
396
+ version : str
397
+ NetLoader version string
398
+ checkpoints : list[TensorListLike]
399
+ Outputs from each checkpoint with each Tensor having shape (N,...) and type float, where N
400
+ is the batch size
401
+ config : dict[str, Any]
402
+ Network configuration
403
+ kl_loss : Tensor
404
+ KL divergence loss on the latent space, of shape (1) and type float, if using a sample layer
405
+ net : ModuleList
406
+ Network construction
407
+ shapes : Shapes
408
+ Layer output shapes
409
+ check_shapes : Shapes
410
+ Checkpoint output shapes
411
+ """
412
+ _name: str = 'convnext_base'
413
+
414
+ def __init__(
415
+ self,
416
+ in_shape: list[int] | tuple[int, ...],
417
+ out_shape: list[int],
418
+ *,
419
+ max_drop_path: float = 0,
420
+ layer_scale: float = 1e-6) -> None:
421
+ """
422
+ Parameters
423
+ ----------
424
+ in_shape : list[int] | list[list[int]] | tuple[int, ...]
425
+ Shape of the input tensor(s), excluding batch size
426
+ out_shape : list[int]
427
+ shape of the output tensor, excluding batch size
428
+ max_drop_path : float, Optional
429
+ Maximum drop path fraction, default = 0
430
+ layer_scale : float, Optional
431
+ Default value for learnable parameters to scale the convolutional filters in a ConvNeXt
432
+ block, default = 1e-6
433
+ """
434
+ super().__init__(
435
+ self._name,
436
+ in_shape,
437
+ out_shape,
438
+ max_drop_path=max_drop_path,
439
+ layer_scale=layer_scale,
440
+ dims=[128, 256, 512, 1024],
441
+ depths=[3, 3, 27, 3],
442
+ )
443
+
444
+
445
+ class ConvNeXtLarge(ConvNeXt):
446
+ """
447
+ Large version of ConvNeXt with the number of convolutional filters in each downscaled section
448
+ following [192, 384, 768, 1536] with the number of ConvNeXt blocks in each downscaled section
449
+ following [3, 3, 27, 3].
450
+
451
+ Original paper implementation: arXiv:2201.03545.
452
+
453
+ Attributes
454
+ ----------
455
+ layer_num : int, Optional
456
+ Number of layers to use, if None use all layers
457
+ group : int
458
+ Which group is the active group if a layer has the group attribute
459
+ name : str
460
+ Name of the network, used for saving
461
+ version : str
462
+ NetLoader version string
463
+ checkpoints : list[TensorListLike]
464
+ Outputs from each checkpoint with each Tensor having shape (N,...) and type float, where N
465
+ is the batch size
466
+ config : dict[str, Any]
467
+ Network configuration
468
+ kl_loss : Tensor
469
+ KL divergence loss on the latent space, of shape (1) and type float, if using a sample layer
470
+ net : ModuleList
471
+ Network construction
472
+ shapes : Shapes
473
+ Layer output shapes
474
+ check_shapes : Shapes
475
+ Checkpoint output shapes
476
+ """
477
+ _name: str = 'convnext_large'
478
+
479
+ def __init__(
480
+ self,
481
+ in_shape: list[int] | tuple[int, ...],
482
+ out_shape: list[int],
483
+ *,
484
+ max_drop_path: float = 0,
485
+ layer_scale: float = 1e-6) -> None:
486
+ """
487
+ Parameters
488
+ ----------
489
+ in_shape : list[int] | list[list[int]] | tuple[int, ...]
490
+ Shape of the input tensor(s), excluding batch size
491
+ out_shape : list[int]
492
+ shape of the output tensor, excluding batch size
493
+ max_drop_path : float, Optional
494
+ Maximum drop path fraction, default = 0
495
+ layer_scale : float, Optional
496
+ Default value for learnable parameters to scale the convolutional filters in a ConvNeXt
497
+ block, default = 1e-6
498
+ """
499
+ super().__init__(
500
+ self._name,
501
+ in_shape,
502
+ out_shape,
503
+ max_drop_path=max_drop_path,
504
+ layer_scale=layer_scale,
505
+ dims=[192, 384, 768, 1536],
506
+ depths=[3, 3, 27, 3],
507
+ )
508
+
509
+
510
+ class ConvNeXtXLarge(ConvNeXt):
511
+ """
512
+ Extra large version of ConvNeXt with the number of convolutional filters in each downscaled
513
+ section following [256, 512, 1024, 2048] with the number of ConvNeXt blocks in each downscaled
514
+ section following [3, 3, 27, 3].
515
+
516
+ Original paper implementation: arXiv:2201.03545.
517
+
518
+ Attributes
519
+ ----------
520
+ layer_num : int, Optional
521
+ Number of layers to use, if None use all layers
522
+ group : int
523
+ Which group is the active group if a layer has the group attribute
524
+ name : str
525
+ Name of the network, used for saving
526
+ version : str
527
+ NetLoader version string
528
+ checkpoints : list[TensorListLike]
529
+ Outputs from each checkpoint with each Tensor having shape (N,...) and type float, where N
530
+ is the batch size
531
+ config : dict[str, Any]
532
+ Network configuration
533
+ kl_loss : Tensor
534
+ KL divergence loss on the latent space, of shape (1) and type float, if using a sample layer
535
+ net : ModuleList
536
+ Network construction
537
+ shapes : Shapes
538
+ Layer output shapes
539
+ check_shapes : Shapes
540
+ Checkpoint output shapes
541
+ """
542
+ _name: str = 'convnext_xlarge'
543
+
544
+ def __init__(
545
+ self,
546
+ in_shape: list[int] | tuple[int, ...],
547
+ out_shape: list[int],
548
+ *,
549
+ max_drop_path: float = 0,
550
+ layer_scale: float = 1e-6) -> None:
551
+ """
552
+ Parameters
553
+ ----------
554
+ in_shape : list[int] | list[list[int]] | tuple[int, ...]
555
+ Shape of the input tensor(s), excluding batch size
556
+ out_shape : list[int]
557
+ shape of the output tensor, excluding batch size
558
+ max_drop_path : float, Optional
559
+ Maximum drop path fraction, default = 0
560
+ layer_scale : float, Optional
561
+ Default value for learnable parameters to scale the convolutional filters in a ConvNeXt
562
+ block, default = 1e-6
563
+ """
564
+ super().__init__(
565
+ self._name,
566
+ in_shape,
567
+ out_shape,
568
+ max_drop_path=max_drop_path,
569
+ layer_scale=layer_scale,
570
+ dims=[256, 512, 1024, 2048],
571
+ depths=[3, 3, 27, 3],
572
+ )
573
+
574
+
575
+ __all__ = [
576
+ 'ConvNeXt',
577
+ 'ConvNeXtTiny',
578
+ 'ConvNeXtSmall',
579
+ 'ConvNeXtBase',
580
+ 'ConvNeXtLarge',
581
+ 'ConvNeXtXLarge',
582
+ ]