dynamic-network-architectures 0.2__tar.gz

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 (26) hide show
  1. dynamic_network_architectures-0.2/LICENCE +201 -0
  2. dynamic_network_architectures-0.2/PKG-INFO +8 -0
  3. dynamic_network_architectures-0.2/README.md +25 -0
  4. dynamic_network_architectures-0.2/dynamic_network_architectures/__init__.py +0 -0
  5. dynamic_network_architectures-0.2/dynamic_network_architectures/architectures/__init__.py +0 -0
  6. dynamic_network_architectures-0.2/dynamic_network_architectures/architectures/resnet.py +236 -0
  7. dynamic_network_architectures-0.2/dynamic_network_architectures/architectures/unet.py +150 -0
  8. dynamic_network_architectures-0.2/dynamic_network_architectures/architectures/vgg.py +85 -0
  9. dynamic_network_architectures-0.2/dynamic_network_architectures/building_blocks/__init__.py +0 -0
  10. dynamic_network_architectures-0.2/dynamic_network_architectures/building_blocks/helper.py +242 -0
  11. dynamic_network_architectures-0.2/dynamic_network_architectures/building_blocks/plain_conv_encoder.py +105 -0
  12. dynamic_network_architectures-0.2/dynamic_network_architectures/building_blocks/regularization.py +86 -0
  13. dynamic_network_architectures-0.2/dynamic_network_architectures/building_blocks/residual.py +371 -0
  14. dynamic_network_architectures-0.2/dynamic_network_architectures/building_blocks/residual_encoders.py +172 -0
  15. dynamic_network_architectures-0.2/dynamic_network_architectures/building_blocks/simple_conv_blocks.py +167 -0
  16. dynamic_network_architectures-0.2/dynamic_network_architectures/building_blocks/unet_decoder.py +127 -0
  17. dynamic_network_architectures-0.2/dynamic_network_architectures/initialization/__init__.py +0 -0
  18. dynamic_network_architectures-0.2/dynamic_network_architectures/initialization/weight_init.py +31 -0
  19. dynamic_network_architectures-0.2/dynamic_network_architectures.egg-info/PKG-INFO +8 -0
  20. dynamic_network_architectures-0.2/dynamic_network_architectures.egg-info/SOURCES.txt +24 -0
  21. dynamic_network_architectures-0.2/dynamic_network_architectures.egg-info/dependency_links.txt +1 -0
  22. dynamic_network_architectures-0.2/dynamic_network_architectures.egg-info/not-zip-safe +1 -0
  23. dynamic_network_architectures-0.2/dynamic_network_architectures.egg-info/requires.txt +2 -0
  24. dynamic_network_architectures-0.2/dynamic_network_architectures.egg-info/top_level.txt +1 -0
  25. dynamic_network_architectures-0.2/setup.cfg +4 -0
  26. dynamic_network_architectures-0.2/setup.py +14 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2022] [Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,8 @@
1
+ Metadata-Version: 2.1
2
+ Name: dynamic_network_architectures
3
+ Version: 0.2
4
+ Summary: none
5
+ Author: Fabian Isensee
6
+ Author-email: f.isensee@dkfz.de
7
+ License: private
8
+ License-File: LICENCE
@@ -0,0 +1,25 @@
1
+ # Dynamic Network Architectures
2
+
3
+ This repository contains several ResNet, U-Net and VGG architectures in pytorch that can be dynamically adapted to a varying number of image dimensions (1D, 2D or 3D) and the number of input channels.
4
+
5
+ ## Available models
6
+ ### ResNet
7
+ We implement the standard [ResNetD](https://arxiv.org/pdf/1812.01187.pdf) 18, 34, 50 and 152. For ResNets 50 and 152 also bottleneck implementations are available. Moreover, adapted versions that are better suited for smaller image sizes such as CIFAR can be used.
8
+
9
+ All models additionally include regularization techniques like [Stochastic Depth](https://arxiv.org/pdf/1603.09382.pdf), [Squeeze & Excitation](https://arxiv.org/pdf/1709.01507.pdf) and [Final Layer Dropout](https://jmlr.org/papers/volume15/srivastava14a/srivastava14a.pdf).
10
+
11
+ ### VGG
12
+ In contrast to the original [VGG](https://arxiv.org/pdf/1409.1556.pdf) implementation we exclude the final fully-connected layers in the end and replace it by additional convolutional layers and only one fully-connected layer in the end. Adapted versions that are better suited for smaller image sizes such as CIFAR can be used.
13
+
14
+ ### U-Net
15
+ For the [U-Net](https://arxiv.org/pdf/1505.04597.pdf) a plain convolutional encoder as well as a residual encoder are available.
16
+
17
+ # Acknowledgements
18
+
19
+ <p align="left">
20
+ <img src="imgs/Logos/HI_Logo.png" width="150"> &nbsp;&nbsp;&nbsp;&nbsp;
21
+ <img src="imgs/Logos/DKFZ_Logo.png" width="500">
22
+ </p>
23
+
24
+ This Repository is developed and maintained by the Applied Computer Vision Lab (ACVL)
25
+ of [Helmholtz Imaging](https://www.helmholtz-imaging.de/).
@@ -0,0 +1,236 @@
1
+ import torch
2
+ from dynamic_network_architectures.building_blocks.residual_encoders import ResidualEncoder, BottleneckD, BasicBlockD
3
+ from dynamic_network_architectures.building_blocks.helper import get_matching_pool_op, get_default_network_config
4
+ from dynamic_network_architectures.building_blocks.simple_conv_blocks import ConvDropoutNormReLU
5
+ from torch import nn
6
+
7
+ _ResNet_CONFIGS = {
8
+ '18': {'features_per_stage': (64, 128, 256, 512), 'n_blocks_per_stage': (2, 2, 2, 2), 'strides': (1, 2, 2, 2),
9
+ 'block': BasicBlockD, 'bottleneck_channels': None, 'disable_default_stem': True, 'stem_channels': None},
10
+ '34': {'features_per_stage': (64, 128, 256, 512), 'n_blocks_per_stage': (3, 4, 6, 3), 'strides': (1, 2, 2, 2),
11
+ 'block': BasicBlockD, 'bottleneck_channels': None, 'disable_default_stem': True, 'stem_channels': None},
12
+ '50': {'features_per_stage': (64, 128, 256, 512), 'n_blocks_per_stage': (4, 6, 10, 5), 'strides': (1, 2, 2, 2),
13
+ 'block': BasicBlockD, 'bottleneck_channels': None, 'disable_default_stem': True, 'stem_channels': None},
14
+ '152': {'features_per_stage': (64, 128, 256, 512), 'n_blocks_per_stage': (4, 13, 55, 4), 'strides': (1, 2, 2, 2),
15
+ 'block': BasicBlockD, 'bottleneck_channels': None, 'disable_default_stem': True, 'stem_channels': None},
16
+ '50_bn': {'features_per_stage': (256, 512, 1024, 2048), 'n_blocks_per_stage': (3, 4, 6, 3), 'strides': (1, 2, 2, 2),
17
+ 'block': BottleneckD, 'bottleneck_channels': (64, 128, 256, 512), 'disable_default_stem': True,
18
+ 'stem_channels': 64},
19
+ '152_bn': {'features_per_stage': (256, 512, 1024, 2048), 'n_blocks_per_stage': (3, 8, 36, 3),
20
+ 'strides': (1, 2, 2, 2),
21
+ 'block': BottleneckD, 'bottleneck_channels': (64, 128, 256, 512), 'disable_default_stem': True,
22
+ 'stem_channels': 64},
23
+ '18_cifar': {'features_per_stage': (64, 128, 256, 512), 'n_blocks_per_stage': (2, 2, 2, 2), 'strides': (1, 2, 2, 2),
24
+ 'block': BasicBlockD, 'bottleneck_channels': None, 'disable_default_stem': False,
25
+ 'stem_channels': None},
26
+ '34_cifar': {'features_per_stage': (64, 128, 256, 512), 'n_blocks_per_stage': (3, 4, 6, 3), 'strides': (1, 2, 2, 2),
27
+ 'block': BasicBlockD, 'bottleneck_channels': None, 'disable_default_stem': False,
28
+ 'stem_channels': None},
29
+ '50_cifar': {'features_per_stage': (64, 128, 256, 512), 'n_blocks_per_stage': (4, 6, 10, 5),
30
+ 'strides': (1, 2, 2, 2),
31
+ 'block': BasicBlockD, 'bottleneck_channels': None, 'disable_default_stem': False,
32
+ 'stem_channels': None},
33
+ '152_cifar': {'features_per_stage': (64, 128, 256, 512), 'n_blocks_per_stage': (4, 13, 55, 4),
34
+ 'strides': (1, 2, 2, 2),
35
+ 'block': BasicBlockD, 'bottleneck_channels': None, 'disable_default_stem': False,
36
+ 'stem_channels': None},
37
+ '50_cifar_bn': {'features_per_stage': (256, 512, 1024, 2048), 'n_blocks_per_stage': (3, 4, 6, 3),
38
+ 'strides': (1, 2, 2, 2),
39
+ 'block': BottleneckD, 'bottleneck_channels': (64, 128, 256, 512), 'disable_default_stem': False,
40
+ 'stem_channels': 64},
41
+ '152_cifar_bn': {'features_per_stage': (256, 512, 1024, 2048), 'n_blocks_per_stage': (3, 8, 36, 3),
42
+ 'strides': (1, 2, 2, 2),
43
+ 'block': BottleneckD, 'bottleneck_channels': (64, 128, 256, 512), 'disable_default_stem': False,
44
+ 'stem_channels': 64},
45
+ }
46
+
47
+
48
+ class ResNetD(nn.Module):
49
+ def __init__(self, n_classes: int, n_input_channel: int = 3, config='18', input_dimension=2,
50
+ final_layer_dropout=0.0, stochastic_depth_p=0.0, squeeze_excitation=False,
51
+ squeeze_excitation_rd_ratio=1./16):
52
+ """
53
+ Implements ResNetD (https://arxiv.org/pdf/1812.01187.pdf).
54
+ Args:
55
+ n_classes: Number of classes
56
+ n_input_channel: Number of input channels (e.g. 3 for RGB)
57
+ config: Configuration of the ResNet
58
+ input_dimension: Number of dimensions of the data (1, 2 or 3)
59
+ final_layer_dropout: Probability of dropout before the final classifier
60
+ stochastic_depth_p: Stochastic Depth probability
61
+ squeeze_excitation: Whether Squeeze and Excitation should be applied
62
+ squeeze_excitation_rd_ratio: Squeeze and Excitation Reduction Ratio
63
+ Returns:
64
+ ResNet Model
65
+ """
66
+ super().__init__()
67
+ self.input_channels = n_input_channel
68
+ self.cfg = _ResNet_CONFIGS[config]
69
+ self.ops = get_default_network_config(dimension=input_dimension)
70
+ self.final_layer_dropout_p = final_layer_dropout
71
+
72
+ if self.cfg['disable_default_stem']:
73
+ stem_features = self.cfg['stem_channels'] if self.cfg['stem_channels'] is not None else \
74
+ self.cfg['features_per_stage'][0]
75
+ self.stem = self._build_imagenet_stem_D(stem_features)
76
+ encoder_input_features = stem_features
77
+ else:
78
+ encoder_input_features = n_input_channel
79
+ self.stem = None
80
+
81
+ self.encoder = ResidualEncoder(encoder_input_features, n_stages=len(self.cfg['features_per_stage']),
82
+ features_per_stage=self.cfg['features_per_stage'], conv_op=self.ops['conv_op'],
83
+ kernel_sizes=3, strides=self.cfg['strides'],
84
+ n_blocks_per_stage=self.cfg['n_blocks_per_stage'], conv_bias=False,
85
+ norm_op=self.ops['norm_op'], norm_op_kwargs=None, dropout_op=None,
86
+ dropout_op_kwargs=None, nonlin=nn.ReLU,
87
+ nonlin_kwargs={'inplace': True}, block=self.cfg['block'],
88
+ bottleneck_channels=self.cfg['bottleneck_channels'], return_skips=False,
89
+ disable_default_stem=self.cfg['disable_default_stem'],
90
+ stem_channels=self.cfg['stem_channels'],
91
+ stochastic_depth_p=stochastic_depth_p,
92
+ squeeze_excitation=squeeze_excitation,
93
+ squeeze_excitation_reduction_ratio=squeeze_excitation_rd_ratio)
94
+
95
+ self.gap = get_matching_pool_op(conv_op=self.ops['conv_op'], adaptive=True, pool_type='avg')(1)
96
+ self.classifier = nn.Linear(self.cfg['features_per_stage'][-1], n_classes, True)
97
+ self.final_layer_dropout = self.ops['dropout_op'](p=self.final_layer_dropout_p)
98
+
99
+ def forward(self, x):
100
+ if self.stem is not None:
101
+ x = self.stem(x)
102
+ x = self.encoder(x)
103
+ x = self.gap(x)
104
+ x = self.final_layer_dropout(x).squeeze()
105
+
106
+ return self.classifier(x)
107
+
108
+ def _build_imagenet_stem_D(self, stem_features):
109
+ """
110
+ https://arxiv.org/pdf/1812.01187.pdf
111
+
112
+ use 3 3x3(x3) convs instead of one 7x7. Stride is located in first conv.
113
+
114
+ Fig2 b) describes this
115
+ :return:
116
+ """
117
+ c1 = ConvDropoutNormReLU(self.ops['conv_op'], self.input_channels, stem_features, 3, 2, False,
118
+ self.ops['norm_op'], None, None, None, nn.ReLU, {'inplace': True})
119
+ c2 = ConvDropoutNormReLU(self.ops['conv_op'], stem_features, stem_features, 3, 1, False,
120
+ self.ops['norm_op'], None, None, None, nn.ReLU, {'inplace': True})
121
+ c3 = ConvDropoutNormReLU(self.ops['conv_op'], stem_features, stem_features, 3, 1, False,
122
+ self.ops['norm_op'], None, None, None, nn.ReLU, {'inplace': True})
123
+ pl = get_matching_pool_op(conv_op=self.ops['conv_op'], adaptive=False, pool_type='max')(2)
124
+ stem = nn.Sequential(c1, c2, c3, pl)
125
+ return stem
126
+
127
+
128
+ class ResNet18_CIFAR(ResNetD):
129
+ def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2,
130
+ final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False,
131
+ squeeze_excitation_rd_ratio: float = 1./16):
132
+ super().__init__(n_classes, n_input_channels, config='18_cifar', input_dimension=input_dimension,
133
+ final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p,
134
+ squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
135
+
136
+ class ResNet34_CIFAR(ResNetD):
137
+ def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2,
138
+ final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False,
139
+ squeeze_excitation_rd_ratio: float = 1./16):
140
+ super().__init__(n_classes, n_input_channels, config='34_cifar', input_dimension=input_dimension,
141
+ final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p,
142
+ squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
143
+
144
+ class ResNet50_CIFAR(ResNetD):
145
+ def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2,
146
+ final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False,
147
+ squeeze_excitation_rd_ratio: float = 1./16):
148
+ super().__init__(n_classes, n_input_channels, config='50_cifar', input_dimension=input_dimension,
149
+ final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p,
150
+ squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
151
+
152
+ class ResNet152_CIFAR(ResNetD):
153
+ def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2,
154
+ final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False,
155
+ squeeze_excitation_rd_ratio: float = 1./16):
156
+ super().__init__(n_classes, n_input_channels, config='152_cifar', input_dimension=input_dimension,
157
+ final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p,
158
+ squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
159
+
160
+ class ResNet50bn_CIFAR(ResNetD):
161
+ def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2,
162
+ final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False,
163
+ squeeze_excitation_rd_ratio: float = 1./16):
164
+ super().__init__(n_classes, n_input_channels, config='50_cifar_bn', input_dimension=input_dimension,
165
+ final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p,
166
+ squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
167
+
168
+ class ResNet152bn_CIFAR(ResNetD):
169
+ def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2,
170
+ final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False,
171
+ squeeze_excitation_rd_ratio: float = 1./16):
172
+ super().__init__(n_classes, n_input_channels, config='152_cifar_bn', input_dimension=input_dimension,
173
+ final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p,
174
+ squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
175
+
176
+ class ResNet18(ResNetD):
177
+ def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2,
178
+ final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False,
179
+ squeeze_excitation_rd_ratio: float = 1./16):
180
+ super().__init__(n_classes, n_input_channels, config='18', input_dimension=input_dimension,
181
+ final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p,
182
+ squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
183
+
184
+ class ResNet34(ResNetD):
185
+ def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2,
186
+ final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False,
187
+ squeeze_excitation_rd_ratio: float = 1./16):
188
+ super().__init__(n_classes, n_input_channels, config='34', input_dimension=input_dimension,
189
+ final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p,
190
+ squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
191
+
192
+ class ResNet50(ResNetD):
193
+ def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2,
194
+ final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False,
195
+ squeeze_excitation_rd_ratio: float = 1./16):
196
+ super().__init__(n_classes, n_input_channels, config='50', input_dimension=input_dimension,
197
+ final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p,
198
+ squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
199
+
200
+ class ResNet152(ResNetD):
201
+ def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2,
202
+ final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False,
203
+ squeeze_excitation_rd_ratio: float = 1./16):
204
+ super().__init__(n_classes, n_input_channels, config='152', input_dimension=input_dimension,
205
+ final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p,
206
+ squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
207
+
208
+ class ResNet50bn(ResNetD):
209
+ def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2,
210
+ final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False,
211
+ squeeze_excitation_rd_ratio: float = 1./16):
212
+ super().__init__(n_classes, n_input_channels, config='50_bn', input_dimension=input_dimension,
213
+ final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p,
214
+ squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
215
+
216
+ class ResNet152bn(ResNetD):
217
+ def __init__(self, n_classes: int, n_input_channels: int = 3, input_dimension: int = 2,
218
+ final_layer_dropout: float = 0.0, stochastic_depth_p: float = 0.0, squeeze_excitation: bool = False,
219
+ squeeze_excitation_rd_ratio: float = 1./16):
220
+ super().__init__(n_classes, n_input_channels, config='152_bn', input_dimension=input_dimension,
221
+ final_layer_dropout=final_layer_dropout, stochastic_depth_p=stochastic_depth_p,
222
+ squeeze_excitation=squeeze_excitation, squeeze_excitation_rd_ratio=squeeze_excitation_rd_ratio)
223
+
224
+
225
+ if __name__ == '__main__':
226
+ data = torch.rand((1, 3, 224, 224))
227
+
228
+ model = ResNet50bn(10, 3)
229
+ import hiddenlayer as hl
230
+
231
+ g = hl.build_graph(model, data,
232
+ transforms=None)
233
+ g.save("network_architecture.pdf")
234
+ del g
235
+
236
+ #print(model.compute_conv_feature_map_size((32, 32)))
@@ -0,0 +1,150 @@
1
+ from typing import Union, Type, List, Tuple
2
+
3
+ import torch
4
+ from dynamic_network_architectures.building_blocks.residual_encoders import ResidualEncoder
5
+ from dynamic_network_architectures.building_blocks.residual import BasicBlockD, BottleneckD
6
+ from torch import nn
7
+ from torch.nn.modules.conv import _ConvNd
8
+ from torch.nn.modules.dropout import _DropoutNd
9
+
10
+ from dynamic_network_architectures.building_blocks.plain_conv_encoder import PlainConvEncoder
11
+ from dynamic_network_architectures.building_blocks.unet_decoder import UNetDecoder
12
+ from dynamic_network_architectures.building_blocks.helper import convert_conv_op_to_dim
13
+
14
+
15
+ class PlainConvUNet(nn.Module):
16
+ def __init__(self,
17
+ input_channels: int,
18
+ n_stages: int,
19
+ features_per_stage: Union[int, List[int], Tuple[int, ...]],
20
+ conv_op: Type[_ConvNd],
21
+ kernel_sizes: Union[int, List[int], Tuple[int, ...]],
22
+ strides: Union[int, List[int], Tuple[int, ...]],
23
+ n_conv_per_stage: Union[int, List[int], Tuple[int, ...]],
24
+ num_classes: int,
25
+ n_conv_per_stage_decoder: Union[int, Tuple[int, ...], List[int]],
26
+ conv_bias: bool = False,
27
+ norm_op: Union[None, Type[nn.Module]] = None,
28
+ norm_op_kwargs: dict = None,
29
+ dropout_op: Union[None, Type[_DropoutNd]] = None,
30
+ dropout_op_kwargs: dict = None,
31
+ nonlin: Union[None, Type[torch.nn.Module]] = None,
32
+ nonlin_kwargs: dict = None,
33
+ deep_supervision: bool = False,
34
+ nonlin_first: bool = False
35
+ ):
36
+ """
37
+ nonlin_first: if True you get conv -> nonlin -> norm. Else it's conv -> norm -> nonlin
38
+ """
39
+ super().__init__()
40
+ if isinstance(n_conv_per_stage, int):
41
+ n_conv_per_stage = [n_conv_per_stage] * n_stages
42
+ if isinstance(n_conv_per_stage_decoder, int):
43
+ n_conv_per_stage_decoder = [n_conv_per_stage_decoder] * (n_stages - 1)
44
+ assert len(n_conv_per_stage) == n_stages, "n_conv_per_stage must have as many entries as we have " \
45
+ f"resolution stages. here: {n_stages}. " \
46
+ f"n_conv_per_stage: {n_conv_per_stage}"
47
+ assert len(n_conv_per_stage_decoder) == (n_stages - 1), "n_conv_per_stage_decoder must have one less entries " \
48
+ f"as we have resolution stages. here: {n_stages} " \
49
+ f"stages, so it should have {n_stages - 1} entries. " \
50
+ f"n_conv_per_stage_decoder: {n_conv_per_stage_decoder}"
51
+ self.encoder = PlainConvEncoder(input_channels, n_stages, features_per_stage, conv_op, kernel_sizes, strides,
52
+ n_conv_per_stage, conv_bias, norm_op, norm_op_kwargs, dropout_op,
53
+ dropout_op_kwargs, nonlin, nonlin_kwargs, return_skips=True,
54
+ nonlin_first=nonlin_first)
55
+ self.decoder = UNetDecoder(self.encoder, num_classes, n_conv_per_stage_decoder, deep_supervision,
56
+ nonlin_first=nonlin_first)
57
+
58
+ def forward(self, x):
59
+ skips = self.encoder(x)
60
+ return self.decoder(skips)
61
+
62
+ def compute_conv_feature_map_size(self, input_size):
63
+ assert len(input_size) == convert_conv_op_to_dim(self.encoder.conv_op), "just give the image size without color/feature channels or " \
64
+ "batch channel. Do not give input_size=(b, c, x, y(, z)). " \
65
+ "Give input_size=(x, y(, z))!"
66
+ return self.encoder.compute_conv_feature_map_size(input_size) + self.decoder.compute_conv_feature_map_size(input_size)
67
+
68
+
69
+ class ResidualEncoderUNet(nn.Module):
70
+ def __init__(self,
71
+ input_channels: int,
72
+ n_stages: int,
73
+ features_per_stage: Union[int, List[int], Tuple[int, ...]],
74
+ conv_op: Type[_ConvNd],
75
+ kernel_sizes: Union[int, List[int], Tuple[int, ...]],
76
+ strides: Union[int, List[int], Tuple[int, ...]],
77
+ n_blocks_per_stage: Union[int, List[int], Tuple[int, ...]],
78
+ num_classes: int,
79
+ n_conv_per_stage_decoder: Union[int, Tuple[int, ...], List[int]],
80
+ conv_bias: bool = False,
81
+ norm_op: Union[None, Type[nn.Module]] = None,
82
+ norm_op_kwargs: dict = None,
83
+ dropout_op: Union[None, Type[_DropoutNd]] = None,
84
+ dropout_op_kwargs: dict = None,
85
+ nonlin: Union[None, Type[torch.nn.Module]] = None,
86
+ nonlin_kwargs: dict = None,
87
+ deep_supervision: bool = False,
88
+ block: Union[Type[BasicBlockD], Type[BottleneckD]] = BasicBlockD,
89
+ bottleneck_channels: Union[int, List[int], Tuple[int, ...]] = None,
90
+ stem_channels: int = None
91
+ ):
92
+ super().__init__()
93
+ if isinstance(n_blocks_per_stage, int):
94
+ n_blocks_per_stage = [n_blocks_per_stage] * n_stages
95
+ if isinstance(n_conv_per_stage_decoder, int):
96
+ n_conv_per_stage_decoder = [n_conv_per_stage_decoder] * (n_stages - 1)
97
+ assert len(n_blocks_per_stage) == n_stages, "n_blocks_per_stage must have as many entries as we have " \
98
+ f"resolution stages. here: {n_stages}. " \
99
+ f"n_blocks_per_stage: {n_blocks_per_stage}"
100
+ assert len(n_conv_per_stage_decoder) == (n_stages - 1), "n_conv_per_stage_decoder must have one less entries " \
101
+ f"as we have resolution stages. here: {n_stages} " \
102
+ f"stages, so it should have {n_stages - 1} entries. " \
103
+ f"n_conv_per_stage_decoder: {n_conv_per_stage_decoder}"
104
+ self.encoder = ResidualEncoder(input_channels, n_stages, features_per_stage, conv_op, kernel_sizes, strides,
105
+ n_blocks_per_stage, conv_bias, norm_op, norm_op_kwargs, dropout_op,
106
+ dropout_op_kwargs, nonlin, nonlin_kwargs, block, bottleneck_channels,
107
+ return_skips=True, disable_default_stem=False, stem_channels=stem_channels)
108
+ self.decoder = UNetDecoder(self.encoder, num_classes, n_conv_per_stage_decoder, deep_supervision)
109
+
110
+ def forward(self, x):
111
+ skips = self.encoder(x)
112
+ return self.decoder(skips)
113
+
114
+ def compute_conv_feature_map_size(self, input_size):
115
+ assert len(input_size) == convert_conv_op_to_dim(self.encoder.conv_op), "just give the image size without color/feature channels or " \
116
+ "batch channel. Do not give input_size=(b, c, x, y(, z)). " \
117
+ "Give input_size=(x, y(, z))!"
118
+ return self.encoder.compute_conv_feature_map_size(input_size) + self.decoder.compute_conv_feature_map_size(input_size)
119
+
120
+
121
+ if __name__ == '__main__':
122
+ data = torch.rand((1, 4, 128, 128, 128))
123
+
124
+ model = PlainConvUNet(4, 6, (32, 64, 125, 256, 320, 320), nn.Conv3d, 3, (1, 2, 2, 2, 2, 2), (2, 2, 2, 2, 2, 2), 4,
125
+ (2, 2, 2, 2, 2), False, nn.BatchNorm3d, None, None, None, nn.ReLU, deep_supervision=True)
126
+
127
+ if False:
128
+ import hiddenlayer as hl
129
+
130
+ g = hl.build_graph(model, data,
131
+ transforms=None)
132
+ g.save("network_architecture.pdf")
133
+ del g
134
+
135
+ print(model.compute_conv_feature_map_size(data.shape[2:]))
136
+
137
+ data = torch.rand((1, 4, 512, 512))
138
+
139
+ model = PlainConvUNet(4, 8, (32, 64, 125, 256, 512, 512, 512, 512), nn.Conv2d, 3, (1, 2, 2, 2, 2, 2, 2, 2), (2, 2, 2, 2, 2, 2, 2, 2), 4,
140
+ (2, 2, 2, 2, 2, 2, 2), False, nn.BatchNorm2d, None, None, None, nn.ReLU, deep_supervision=True)
141
+
142
+ if False:
143
+ import hiddenlayer as hl
144
+
145
+ g = hl.build_graph(model, data,
146
+ transforms=None)
147
+ g.save("network_architecture.pdf")
148
+ del g
149
+
150
+ print(model.compute_conv_feature_map_size(data.shape[2:]))