├── INPLACE_ABN_TIPS.md
├── LICENSE
├── MODEL_ZOO.md
├── README.md
├── figures
├── herbarium_2020.png
├── main_pic.png
├── ms_coco_scores.png
├── sotabench.png
├── table_1.png
├── table_3.png
├── table_4.png
├── table_5.png
└── table_6.png
├── infer.py
├── requirements.txt
├── src
├── helper_functions
│ └── helper_functions.py
└── models
│ ├── __init__.py
│ ├── tresnet
│ ├── __init__.py
│ ├── layers
│ │ ├── anti_aliasing.py
│ │ ├── avg_pool.py
│ │ ├── space_to_depth.py
│ │ └── squeeze_and_excite.py
│ └── tresnet.py
│ ├── tresnet_v2
│ ├── __init__.py
│ ├── layers
│ │ ├── anti_aliasing.py
│ │ ├── avg_pool.py
│ │ ├── space_to_depth.py
│ │ └── squeeze_and_excite.py
│ └── tresnet_v2.py
│ └── utils
│ ├── __init__.py
│ └── factory.py
└── tests
└── test_TResNetV2
/INPLACE_ABN_TIPS.md:
--------------------------------------------------------------------------------
1 | ## Some Tips For Working With Inplace-ABN
2 |
3 | Inplace batch-norm
4 | ([Inplace-ABN](https://github.com/mapillary/inplace_abn)) module has
5 | exactly the same fields as
6 | [regular BatchNorm](https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/batchnorm.py):
7 | * module.weight
8 | * module.bias
9 | * module.running_mean
10 | * module.running_var
11 | * module.num_batches_tracked
12 |
13 | Therefore, any function that operates on BatchNorm can run on
14 | Inplace-ABN.
15 |
16 | However, problems can arise when a logic condition seeks explicitly for
17 | BatchNorm layers only:
18 | ```
19 | if isinstance(module, nn.BatchNorm2d):
20 | do_something(module)
21 | ```
22 |
23 | Anywhere you see a code segement like this, it needs to be replaced with
24 | a condition that includes Inplace-ABN:
25 | ```
26 | if isinstance(module, nn.BatchNorm2d) or isinstance(module, inplace_abn.InPlaceABN):
27 | do_something(module)
28 | ```
29 |
30 | ##### NVIDIA Apex mixed precision
31 | [NVIDIA Apex](https://github.com/NVIDIA/apex) O0, O1 and O3
32 | mixed-precision options work seemlesly on Inplace-ABN.
33 |
34 | For O2 mixed precision, we need to convert manually Inplace-ABN to fp32,
35 | since NVIDIA Apex inner code has explicit 'if' condition for BatchNorm
36 | only.
37 |
38 | Conversion can be done easily with the helper function
39 | 'IABN2float':
40 | ```
41 | if args.use_apex:
42 | model, optimizer = apex.amp.initialize(model, optimizer, opt_level=args.opt_level)
43 | if args.opt_level == 'O2': # IABN needs adjustment for O2
44 | from src.models.tresnet import IABN2Float
45 | model = IABN2Float(model)
46 | ```
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
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 [yyyy] [name of copyright owner]
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.
202 |
--------------------------------------------------------------------------------
/MODEL_ZOO.md:
--------------------------------------------------------------------------------
1 | # TResNet pre-trained models
2 |
3 | We provide a collection of TResNet models pre-trained on [ImageNet dataset](http://www.image-net.org/).
4 |
5 | | Model name | Input Size
6 | | ------------ | :--------------: |
7 | | [tresnet_m.pth](https://miil-public-eu.oss-eu-central-1.aliyuncs.com/model-zoo/tresnet/tresnet_m.pth) | 224 |
8 | | [tresnet_m_448.pth](https://miil-public-eu.oss-eu-central-1.aliyuncs.com/model-zoo/tresnet/tresnet_m_448.pth) | 448 |
9 | | [tresnet_l.pth](https://miil-public-eu.oss-eu-central-1.aliyuncs.com/model-zoo/tresnet/tresnet_l.pth) | 224 |
10 | | [tresnet_l_448.pth](https://miil-public-eu.oss-eu-central-1.aliyuncs.com/model-zoo/tresnet/tresnet_l_448.pth) | 448 |
11 | | [tresnet_xl.pth](https://miil-public-eu.oss-eu-central-1.aliyuncs.com/model-zoo/tresnet/tresnet_xl.pth) | 224 |
12 | | [tresnet_xl_448.pth](https://miil-public-eu.oss-eu-central-1.aliyuncs.com/model-zoo/tresnet/tresnet_xl_448.pth) | 448 |
13 |
14 | We also provide The TResNet model that achieved SOTA results on
15 | [stanford-cars](https://paperswithcode.com/sota/fine-grained-image-classification-on-stanford)
16 | dataset:
17 |
18 | | Model name | Input Size
19 | | ------------ | :--------------: |
20 | | [tresnet_l-v2.pth](https://miil-public-eu.oss-eu-central-1.aliyuncs.com/model-zoo/tresnet/stanford_cars_tresnet-l-v2_96_27.pth) | 368 |
21 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # TResNet: High Performance GPU-Dedicated Architecture
2 |
3 | [paperV2](https://arxiv.org/pdf/2003.13630.pdf) |
4 | [pretrained models](MODEL_ZOO.md)
5 |
6 | Official PyTorch Implementation
7 |
8 | > Tal Ridnik, Hussam Lawen, Asaf Noy, Itamar Friedman, Emanuel Ben Baruch, Gilad Sharir
9 | > DAMO Academy, Alibaba Group
10 |
11 |
12 |
13 | **Abstract**
14 |
15 | > Many deep learning models, developed in recent years, reach higher
16 | > ImageNet accuracy than ResNet50, with fewer or comparable FLOPS count.
17 | > While FLOPs are often seen as a proxy for network efficiency, when
18 | > measuring actual GPU training and inference throughput, vanilla
19 | > ResNet50 is usually significantly faster than its recent competitors,
20 | > offering better throughput-accuracy trade-off. In this work, we
21 | > introduce a series of architecture modifications that aim to boost
22 | > neural networks' accuracy, while retaining their GPU training and
23 | > inference efficiency. We first demonstrate and discuss the bottlenecks
24 | > induced by FLOPs-optimizations. We then suggest alternative designs
25 | > that better utilize GPU structure and assets. Finally, we introduce a
26 | > new family of GPU-dedicated models, called TResNet, which achieve
27 | > better accuracy and efficiency than previous ConvNets. Using a TResNet
28 | > model, with similar GPU throughput to ResNet50, we reach 80.7\%
29 | > top-1 accuracy on ImageNet. Our TResNet models also transfer well and
30 | > achieve state-of-the-art accuracy on competitive datasets such as
31 | > Stanford cars (96.0\%), CIFAR-10 (99.0\%), CIFAR-100 (91.5\%) and
32 | > Oxford-Flowers (99.1\%). They also perform well on multi-label classification and object detection tasks.
33 |
34 | ## 29/11/2021 Update - New article released, offering new classification head with state-of-the-art results
35 | Checkout our new project, [Ml-Decoder](https://github.com/Alibaba-MIIL/ML_Decoder), which presents a unified classification head for multi-label, single-label and
36 | zero-shot tasks. Backbones with ML-Decoder reach SOTA results, while also improving speed-accuracy tradeoff.
37 |
38 |
39 |
40 |
41 |  |
42 |  |
43 |
44 |
45 |
46 |
47 |
48 | ## 11/1/2023 Update
49 | Added [tests](https://github.com/Alibaba-MIIL/TResNet/blob/master/tests/test_TResNetV2) auto-generated by [CodiumAI](https://www.codium.ai/) tool
50 |
51 |
52 | ## 23/4/2021 Update - ImageNet21K Pretraining
53 | In a new [article](https://github.com/Alibaba-MIIL/ImageNet21K) we released, we share pretrain weights for TResNet models from ImageNet21K training, that dramatically outperfrom standard pretraining.
54 | TResNet-M model, for example, improves its ImageNet-1K score, from 80.7% to 83.1% !
55 | This kind of improvement is consistently achieved on all downstream tasks.
56 |
57 |
58 | ## 28/8/2020: V2 of TResNet Article Released
59 |
60 | ## Sotabench Comparisons
61 | Comparative results from
62 | [sotabench benchamrk](https://sotabench.com/benchmarks/image-classification-on-imagenet#code),
63 | demonstartaing that TReNset models give excellent speed-accuracy tradoff:
64 |
65 |
66 |
67 |  |
68 |
69 |
70 |
71 |
72 | ## 11/6/2020: V1 of TResNet Article Released
73 | The main change - In addition to single label SOTA results, we also
74 | added top results for multi-label classification and object detection
75 | tasks, using TResNet. For example, we set a new SOTA record for MS-COCO
76 | multi-label dataset, surpassing the previous top results by more than
77 | 2.5% mAP !
78 |
79 |
80 |
81 | Bacbkone |
82 | mAP |
83 |
84 |
85 | KSSNet (previous SOTA) |
86 | 83.7 |
87 |
88 |
89 | TResNet-L |
90 | 86.4 |
91 |
92 |
93 |
94 |
95 |
96 |
97 | ## 2/6/2020: CVPR-Kaggle competitions
98 | We participated and won top places in two
99 | major CVPR-Kaggle competitions:
100 | * [2nd place](https://www.kaggle.com/c/herbarium-2020-fgvc7/discussion/154186)
101 | in Herbarium 2020 competition, out of 153 teams.
102 | * [7th place](https://www.kaggle.com/c/plant-pathology-2020-fgvc7/discussion/154086)
103 | in Plant-Pathology 2020 competition, out of 1317 teams.
104 |
*TResNet* was a vital part of our solution for both competitions,
105 | allowing us to work on high resolutions and reach top scores while
106 | doing fast and efficient experiments.
107 |
108 |
109 |
110 |  |
111 |
112 |
113 |
114 |
115 |
116 | ## Main Article Results
117 | #### TResNet Models
118 | TResNet models accuracy and GPU throughput on ImageNet, compared to ResNet50. All measurements were done on Nvidia V100 GPU, with mixed precision. All models are trained on input resolution of 224.
119 |
120 |
121 |
122 | Models |
123 | Top Training Speed (img/sec) |
124 | Top Inference Speed (img/sec) |
125 | Max Train Batch Size |
126 | Top-1 Acc. |
127 |
128 |
129 | ResNet50 |
130 | 805 |
131 | 2830 |
132 | 288 |
133 | 79.0 |
134 |
135 |
136 | EfficientNetB1 |
137 | 440 |
138 | 2740 |
139 | 196 |
140 | 79.2 |
141 |
142 |
143 | TResNet-M |
144 | 730 |
145 | 2930 |
146 | 512 |
147 | 80.8 |
148 |
149 |
150 | TResNet-L |
151 | 345 |
152 | 1390 |
153 | 316 |
154 | 81.5 |
155 |
156 |
157 | TResNet-XL |
158 | 250 |
159 | 1060 |
160 | 240 |
161 | 82.0 |
162 |
163 |
164 |
165 |
166 | #### Comparison To Other Networks
167 |
168 | Comparison of ResNet50 to top modern networks, with similar top-1 ImageNet accuracy.
169 | All measurements were done on Nvidia V100 GPU with mixed precision. For gaining optimal speeds, training and inference were measured on 90\% of maximal possible batch size.
170 | Except TResNet-M, all the models' ImageNet scores were taken from the [public repository](https://github.com/rwightman/pytorch-image-models), which specialized in providing top implementations for modern networks. Except EfficientNet-B1, which has input resolution of 240, all other models have input resolution of 224.
171 |
172 |
173 |
174 | Model |
175 | Top Training Speed (img/sec) |
176 | Top Inference Speed (img/sec) |
177 | Top-1 Acc. |
178 | Flops[G] |
179 |
180 |
181 | ResNet50 |
182 | 805 |
183 | 2830 |
184 | 79.0 |
185 | 4.1 |
186 |
187 |
188 | ResNet50-D |
189 | 600 |
190 | 2670 |
191 | 79.3 |
192 | 4.4 |
193 |
194 |
195 | ResNeXt50 |
196 | 490 |
197 | 1940 |
198 | 79.4 |
199 | 4.3 |
200 |
201 |
202 | EfficientNetB1 |
203 | 440 |
204 | 2740 |
205 | 79.2 |
206 | 0.6 |
207 |
208 |
209 | SEResNeXt50 |
210 | 400 |
211 | 1770 |
212 | 79.9 |
213 | 4.3 |
214 |
215 |
216 | MixNet-L |
217 | 400 |
218 | 1400 |
219 | 79.0 |
220 | 0.5 |
221 |
222 |
223 | TResNet-M |
224 | 730 |
225 | 2930 |
226 | 80.8 |
227 | 5.5 |
228 |
229 |
230 |
231 |
232 |
233 |
234 |
235 |
236 |  |
237 |  |
238 |
239 |
240 |
241 |
242 |
243 |
244 |
245 | #### Transfer Learning SotA Results
246 | Comparison of TResNet to state-of-the-art models on transfer learning datasets (only ImageNet-based transfer learning results). Models inference speed is measured on a mixed precision V100 GPU. Since no official implementation of Gpipe was provided, its inference speed is unknown
247 |
248 |
249 |
250 |
251 |
252 | Dataset
253 | |
254 |
255 | Model
256 | |
257 |
258 | Top-1
259 |
260 | Acc.
261 | |
262 |
263 | Speed
264 |
265 | img/sec
266 | |
267 |
268 | Input
269 | |
270 |
271 |
272 |
273 | CIFAR-10
274 | |
275 |
276 | Gpipe
277 | |
278 |
279 | 99.0
280 | |
281 |
282 | -
283 | |
284 |
285 | 480
286 | |
287 |
288 |
289 |
290 | TResNet-XL
291 | |
292 |
293 | 99.0
294 | |
295 |
296 | 1060
297 | |
298 |
299 | 224
300 | |
301 |
302 |
303 |
304 | CIFAR-100
305 | |
306 |
307 | EfficientNet-B7
308 | |
309 |
310 | 91.7
311 | |
312 |
313 | 70
314 | |
315 |
316 | 600
317 | |
318 |
319 |
320 |
321 | TResNet-XL
322 | |
323 |
324 | 91.5
325 | |
326 |
327 | 1060
328 | |
329 |
330 | 224
331 | |
332 |
333 |
334 |
335 | Stanford Cars
336 | |
337 |
338 | EfficientNet-B7
339 | |
340 |
341 | 94.7
342 | |
343 |
344 | 70
345 | |
346 |
347 | 600
348 | |
349 |
350 |
351 |
352 | TResNet-L
353 | |
354 |
355 | 96.0
356 | |
357 |
358 | 500
359 | |
360 |
361 | 368
362 | |
363 |
364 |
365 |
366 | Oxford-Flowers
367 | |
368 |
369 | EfficientNet-B7
370 | |
371 |
372 | 98.8
373 | |
374 |
375 | 70
376 | |
377 |
378 | 600
379 | |
380 |
381 |
382 |
383 | TResNet-L
384 | |
385 |
386 | 99.1
387 | |
388 |
389 | 500
390 | |
391 |
392 | 368
393 | |
394 |
395 |
396 |
397 |
398 |
399 | ## Reproduce Article Scores
400 | We provide code for reproducing the validation top-1 score of TResNet
401 | models on ImageNet. First, download pretrained models from
402 | [here](MODEL_ZOO.md).
403 |
404 | Then, run the infer.py script. For example, for tresnet_m (input size 224)
405 | run:
406 | ```bash
407 | python -m infer.py \
408 | --val_dir=/path/to/imagenet_val_folder \
409 | --model_path=/model/path/to/tresnet_m.pth \
410 | --model_name=tresnet_m
411 | --input_size=224
412 | ```
413 | ## TResNet Training
414 | Due to IP limitations, we do not provide the exact training code that
415 | was used to obtain the article results.
416 |
417 | However, TResNet is now an integral part of the popular [rwightman /
418 | pytorch-image-models](https://github.com/rwightman/pytorch-image-models)
419 | repo. Using that repo, you can reach very similar results to the one
420 | stated in the article.
421 |
422 | For example, training tresnet_m on [rwightman /
423 | pytorch-image-models](https://github.com/rwightman/pytorch-image-models) with
424 | the command line:
425 | ```bash
426 | python -u -m torch.distributed.launch --nproc_per_node=8 \
427 | --nnodes=1 --node_rank=0 ./train.py /data/imagenet/ \
428 | -b=190 --lr=0.6 --model-ema --aa=rand-m9-mstd0.5-inc1 \
429 | --num-gpu=8 -j=16 --amp \
430 | --model=tresnet_m --epochs=300 --mixup=0.2 \
431 | --sched='cosine' --reprob=0.4 --remode=pixel
432 | ```
433 | gave accuracy of 80.5%.
434 |
435 |
436 | Also, during the merge request, we had interesting discussions and
437 | insights regarding TResNet design. I am attaching a pdf version the
438 | mentioned discussions. They can shed more light on TResNet design
439 | considerations and directions for the future.
440 |
441 | [TResNet discussion and insights](https://miil-public-eu.oss-eu-central-1.aliyuncs.com/model-zoo/tresnet/TResnet_discussion.pdf)
442 |
443 | (taken with permission from
444 | [here](https://github.com/rwightman/pytorch-image-models/issues/124))
445 |
446 |
447 |
448 | ## Tips For Working With Inplace-ABN
449 | See
450 | [INPLACE_ABN_TIPS](https://github.com/mrT23/TResNet/blob/master/INPLACE_ABN_TIPS.md).
451 |
452 |
453 | ## Citation
454 |
455 | ```
456 | @misc{ridnik2020tresnet,
457 | title={TResNet: High Performance GPU-Dedicated Architecture},
458 | author={Tal Ridnik and Hussam Lawen and Asaf Noy and Itamar Friedman},
459 | year={2020},
460 | eprint={2003.13630},
461 | archivePrefix={arXiv},
462 | primaryClass={cs.CV}
463 | }
464 | ```
465 |
466 | ## Contact
467 | Feel free to contact me if there are any questions or issues (Tal
468 | Ridnik, tal.ridnik@alibaba-inc.com).
469 |
--------------------------------------------------------------------------------
/figures/herbarium_2020.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Alibaba-MIIL/TResNet/aea5f0f96d0051800379160b994781cae2ad011c/figures/herbarium_2020.png
--------------------------------------------------------------------------------
/figures/main_pic.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Alibaba-MIIL/TResNet/aea5f0f96d0051800379160b994781cae2ad011c/figures/main_pic.png
--------------------------------------------------------------------------------
/figures/ms_coco_scores.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Alibaba-MIIL/TResNet/aea5f0f96d0051800379160b994781cae2ad011c/figures/ms_coco_scores.png
--------------------------------------------------------------------------------
/figures/sotabench.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Alibaba-MIIL/TResNet/aea5f0f96d0051800379160b994781cae2ad011c/figures/sotabench.png
--------------------------------------------------------------------------------
/figures/table_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Alibaba-MIIL/TResNet/aea5f0f96d0051800379160b994781cae2ad011c/figures/table_1.png
--------------------------------------------------------------------------------
/figures/table_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Alibaba-MIIL/TResNet/aea5f0f96d0051800379160b994781cae2ad011c/figures/table_3.png
--------------------------------------------------------------------------------
/figures/table_4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Alibaba-MIIL/TResNet/aea5f0f96d0051800379160b994781cae2ad011c/figures/table_4.png
--------------------------------------------------------------------------------
/figures/table_5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Alibaba-MIIL/TResNet/aea5f0f96d0051800379160b994781cae2ad011c/figures/table_5.png
--------------------------------------------------------------------------------
/figures/table_6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Alibaba-MIIL/TResNet/aea5f0f96d0051800379160b994781cae2ad011c/figures/table_6.png
--------------------------------------------------------------------------------
/infer.py:
--------------------------------------------------------------------------------
1 | import torch
2 | from src.helper_functions.helper_functions import validate, create_dataloader
3 | from src.models import create_model
4 | import argparse
5 |
6 | torch.backends.cudnn.benchmark = True
7 |
8 | parser = argparse.ArgumentParser(description='PyTorch TResNet ImageNet Inference')
9 | parser.add_argument('--val_dir')
10 | parser.add_argument('--model_path')
11 | parser.add_argument('--model_name', type=str, default='tresnet_m')
12 | parser.add_argument('--num_classes', type=int, default=1000)
13 | parser.add_argument('--input_size', type=int, default=224)
14 | parser.add_argument('--val_zoom_factor', type=int, default=0.875)
15 | parser.add_argument('--batch_size', type=int, default=48)
16 | parser.add_argument('--num_workers', type=int, default=8)
17 | parser.add_argument('--remove_aa_jit', action='store_true', default=False)
18 |
19 |
20 | def main():
21 | # parsing args
22 | args = parser.parse_args()
23 |
24 | # setup model
25 | print('creating model...')
26 | model = create_model(args).cuda()
27 | from src.models.tresnet_v2.tresnet_v2 import InplacABN_to_ABN
28 | model2 = InplacABN_to_ABN(model)
29 | aaa = torch.jit.script(model2)
30 | state = torch.load(args.model_path, map_location='cpu')['model']
31 | model.load_state_dict(state, strict=False)
32 | model.eval()
33 | print('done\n')
34 |
35 | # setup data loader
36 | print('creating data loader...')
37 | val_loader = create_dataloader(args)
38 | print('done\n')
39 |
40 | # actual validation process
41 | print('doing validation...')
42 | prec1_f = validate(model, val_loader)
43 | print("final top-1 validation accuracy: {:.2f}".format(prec1_f.avg))
44 |
45 |
46 | if __name__ == '__main__':
47 | main()
48 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | torch>=1.3
2 | torchvision>=0.4.0
3 | git+https://github.com/mapillary/inplace_abn.git@v1.0.11
--------------------------------------------------------------------------------
/src/helper_functions/helper_functions.py:
--------------------------------------------------------------------------------
1 | import time
2 | import torch
3 | from torchvision.datasets import ImageFolder
4 | from torchvision.transforms import transforms
5 |
6 |
7 | def create_dataloader(args):
8 | val_bs = args.batch_size
9 | if args.input_size == 448: # squish
10 | val_tfms = transforms.Compose(
11 | [transforms.Resize((args.input_size, args.input_size))])
12 | else: # crop
13 | val_tfms = transforms.Compose(
14 | [transforms.Resize(int(args.input_size / args.val_zoom_factor)),
15 | transforms.CenterCrop(args.input_size)])
16 | val_tfms.transforms.append(transforms.ToTensor())
17 | val_dataset = ImageFolder(args.val_dir, val_tfms)
18 | val_loader = torch.utils.data.DataLoader(
19 | val_dataset, batch_size=val_bs, shuffle=False,
20 | num_workers=args.num_workers, pin_memory=True, drop_last=False)
21 | return val_loader
22 |
23 |
24 | def accuracy(output, target, topk=(1,)):
25 | """Computes the precision@k for the specified values of k"""
26 | maxk = max(topk)
27 | batch_size = target.size(0)
28 |
29 | _, pred = output.topk(maxk, 1, True, True)
30 | pred = pred.t()
31 | correct = pred.eq(target.view(1, -1).expand_as(pred))
32 |
33 | res = []
34 | for k in topk:
35 | correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
36 | res.append(correct_k.mul_(100.0 / batch_size))
37 | return res
38 |
39 |
40 | class AverageMeter(object):
41 | """Computes and stores the average and current value"""
42 |
43 | def __init__(self): self.reset()
44 |
45 | def reset(self): self.val = self.avg = self.sum = self.count = 0
46 |
47 | def update(self, val, n=1):
48 | self.val = val
49 | self.sum += val * n
50 | self.count += n
51 | self.avg = self.sum / self.count
52 |
53 |
54 | def validate(model, val_loader):
55 | prec1_m = AverageMeter()
56 | last_idx = len(val_loader) - 1
57 |
58 | with torch.no_grad():
59 | for batch_idx, (input, target) in enumerate(val_loader):
60 | last_batch = batch_idx == last_idx
61 | input = input.cuda()
62 | target = target.cuda()
63 | output = model(input)
64 |
65 | prec1 = accuracy(output, target)
66 | prec1_m.update(prec1[0].item(), output.size(0))
67 |
68 | if (last_batch or batch_idx % 100 == 0):
69 | log_name = 'ImageNet Test'
70 | print(
71 | '{0}: [{1:>4d}/{2}] '
72 | 'Prec@1: {top1.val:>7.2f} ({top1.avg:>7.2f}) '.format(
73 | log_name, batch_idx, last_idx,
74 | top1=prec1_m))
75 | return prec1_m
76 |
--------------------------------------------------------------------------------
/src/models/__init__.py:
--------------------------------------------------------------------------------
1 | from .utils import create_model
2 |
3 | __all__ = ['create_model']
4 |
--------------------------------------------------------------------------------
/src/models/tresnet/__init__.py:
--------------------------------------------------------------------------------
1 | from .tresnet import TResnetM, TResnetL, TResnetXL
2 |
--------------------------------------------------------------------------------
/src/models/tresnet/layers/anti_aliasing.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn.parallel
3 | import numpy as np
4 | import torch.nn as nn
5 | import torch.nn.functional as F
6 |
7 |
8 | class AntiAliasDownsampleLayer(nn.Module):
9 | def __init__(self, remove_aa_jit: bool = False, filt_size: int = 3, stride: int = 2,
10 | channels: int = 0):
11 | super(AntiAliasDownsampleLayer, self).__init__()
12 | if not remove_aa_jit:
13 | self.op = DownsampleJIT(filt_size, stride, channels)
14 | else:
15 | self.op = Downsample(filt_size, stride, channels)
16 |
17 | def forward(self, x):
18 | return self.op(x)
19 |
20 |
21 | @torch.jit.script
22 | class DownsampleJIT(object):
23 | def __init__(self, filt_size: int = 3, stride: int = 2, channels: int = 0):
24 | self.stride = stride
25 | self.filt_size = filt_size
26 | self.channels = channels
27 |
28 | assert self.filt_size == 3
29 | assert stride == 2
30 | a = torch.tensor([1., 2., 1.])
31 |
32 | filt = (a[:, None] * a[None, :]).clone().detach()
33 | filt = filt / torch.sum(filt)
34 | self.filt = filt[None, None, :, :].repeat((self.channels, 1, 1, 1)).cuda().half()
35 |
36 | def __call__(self, input: torch.Tensor):
37 | if input.dtype != self.filt.dtype:
38 | self.filt = self.filt.float()
39 | input_pad = F.pad(input, (1, 1, 1, 1), 'reflect')
40 | return F.conv2d(input_pad, self.filt, stride=2, padding=0, groups=input.shape[1])
41 |
42 |
43 | class Downsample(nn.Module):
44 | def __init__(self, filt_size=3, stride=2, channels=None):
45 | super(Downsample, self).__init__()
46 | self.filt_size = filt_size
47 | self.stride = stride
48 | self.channels = channels
49 |
50 |
51 | assert self.filt_size == 3
52 | a = torch.tensor([1., 2., 1.])
53 |
54 | filt = (a[:, None] * a[None, :])
55 | filt = filt / torch.sum(filt)
56 |
57 | # self.filt = filt[None, None, :, :].repeat((self.channels, 1, 1, 1))
58 | self.register_buffer('filt', filt[None, None, :, :].repeat((self.channels, 1, 1, 1)))
59 |
60 | def forward(self, input):
61 | input_pad = F.pad(input, (1, 1, 1, 1), 'reflect')
62 | return F.conv2d(input_pad, self.filt, stride=self.stride, padding=0, groups=input.shape[1])
63 |
--------------------------------------------------------------------------------
/src/models/tresnet/layers/avg_pool.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import torch.nn.functional as F
4 |
5 |
6 |
7 | class FastGlobalAvgPool2d(nn.Module):
8 | def __init__(self, flatten=False):
9 | super(FastGlobalAvgPool2d, self).__init__()
10 | self.flatten = flatten
11 |
12 | def forward(self, x):
13 | if self.flatten:
14 | in_size = x.size()
15 | return x.view((in_size[0], in_size[1], -1)).mean(dim=2)
16 | else:
17 | return x.view(x.size(0), x.size(1), -1).mean(-1).view(x.size(0), x.size(1), 1, 1)
18 |
19 |
20 |
--------------------------------------------------------------------------------
/src/models/tresnet/layers/space_to_depth.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 |
4 |
5 | class SpaceToDepth(nn.Module):
6 | def __init__(self, block_size=4):
7 | super().__init__()
8 | assert block_size == 4
9 | self.bs = block_size
10 |
11 | def forward(self, x):
12 | N, C, H, W = x.size()
13 | x = x.view(N, C, H // self.bs, self.bs, W // self.bs, self.bs) # (N, C, H//bs, bs, W//bs, bs)
14 | x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # (N, bs, bs, C, H//bs, W//bs)
15 | x = x.view(N, C * (self.bs ** 2), H // self.bs, W // self.bs) # (N, C*bs^2, H//bs, W//bs)
16 | return x
17 |
18 |
19 | @torch.jit.script
20 | class SpaceToDepthJit(object):
21 | def __call__(self, x: torch.Tensor):
22 | # assuming hard-coded that block_size==4 for acceleration
23 | N, C, H, W = x.size()
24 | x = x.view(N, C, H // 4, 4, W // 4, 4) # (N, C, H//bs, bs, W//bs, bs)
25 | x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # (N, bs, bs, C, H//bs, W//bs)
26 | x = x.view(N, C * 16, H // 4, W // 4) # (N, C*bs^2, H//bs, W//bs)
27 | return x
28 |
29 |
30 | class SpaceToDepthModule(nn.Module):
31 | def __init__(self, remove_model_jit=False):
32 | super().__init__()
33 | if not remove_model_jit:
34 | self.op = SpaceToDepthJit()
35 | else:
36 | self.op = SpaceToDepth()
37 |
38 | def forward(self, x):
39 | return self.op(x)
40 |
41 |
42 | class DepthToSpace(nn.Module):
43 |
44 | def __init__(self, block_size):
45 | super().__init__()
46 | self.bs = block_size
47 |
48 | def forward(self, x):
49 | N, C, H, W = x.size()
50 | x = x.view(N, self.bs, self.bs, C // (self.bs ** 2), H, W) # (N, bs, bs, C//bs^2, H, W)
51 | x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # (N, C//bs^2, H, bs, W, bs)
52 | x = x.view(N, C // (self.bs ** 2), H * self.bs, W * self.bs) # (N, C//bs^2, H * bs, W * bs)
53 | return x
--------------------------------------------------------------------------------
/src/models/tresnet/layers/squeeze_and_excite.py:
--------------------------------------------------------------------------------
1 | import torch.nn as nn
2 | import torch.nn.functional as F
3 | from src.models.tresnet.layers.avg_pool import FastGlobalAvgPool2d
4 |
5 |
6 | class Flatten(nn.Module):
7 | def forward(self, x):
8 | return x.view(x.size(0), -1)
9 |
10 |
11 | class SEModule(nn.Module):
12 |
13 | def __init__(self, channels, reduction_channels, inplace=True):
14 | super(SEModule, self).__init__()
15 | self.avg_pool = FastGlobalAvgPool2d()
16 | self.fc1 = nn.Conv2d(channels, reduction_channels, kernel_size=1, padding=0, bias=True)
17 | self.relu = nn.ReLU(inplace=inplace)
18 | self.fc2 = nn.Conv2d(reduction_channels, channels, kernel_size=1, padding=0, bias=True)
19 | # self.activation = hard_sigmoid(inplace=inplace)
20 | self.activation = nn.Sigmoid()
21 |
22 | def forward(self, x):
23 | x_se = self.avg_pool(x)
24 | x_se2 = self.fc1(x_se)
25 | x_se2 = self.relu(x_se2)
26 | x_se = self.fc2(x_se2)
27 | x_se = self.activation(x_se)
28 | return x * x_se
29 |
30 | class hard_sigmoid(nn.Module):
31 | def __init__(self, inplace=True):
32 | super(hard_sigmoid, self).__init__()
33 | self.inplace = inplace
34 |
35 | def forward(self, x):
36 | if self.inplace:
37 | return x.add_(3.).clamp_(0., 6.).div_(6.)
38 | else:
39 | return F.relu6(x + 3.) / 6.
--------------------------------------------------------------------------------
/src/models/tresnet/tresnet.py:
--------------------------------------------------------------------------------
1 | from functools import partial
2 |
3 | import torch
4 | import torch.nn as nn
5 | from collections import OrderedDict
6 | from src.models.tresnet.layers.anti_aliasing import AntiAliasDownsampleLayer
7 | from .layers.avg_pool import FastGlobalAvgPool2d
8 | from .layers.squeeze_and_excite import SEModule
9 | from src.models.tresnet.layers.space_to_depth import SpaceToDepthModule
10 | from inplace_abn import InPlaceABN
11 |
12 |
13 | def IABN2Float(module: nn.Module) -> nn.Module:
14 | "If `module` is IABN don't use half precision."
15 | if isinstance(module, InPlaceABN):
16 | module.float()
17 | for child in module.children(): IABN2Float(child)
18 | return module
19 |
20 |
21 | def conv2d_ABN(ni, nf, stride, activation="leaky_relu", kernel_size=3, activation_param=1e-2, groups=1):
22 | return nn.Sequential(
23 | nn.Conv2d(ni, nf, kernel_size=kernel_size, stride=stride, padding=kernel_size // 2, groups=groups,
24 | bias=False),
25 | InPlaceABN(num_features=nf, activation=activation, activation_param=activation_param)
26 | )
27 |
28 |
29 | class BasicBlock(nn.Module):
30 | expansion = 1
31 |
32 | def __init__(self, inplanes, planes, stride=1, downsample=None, use_se=True, anti_alias_layer=None):
33 | super(BasicBlock, self).__init__()
34 | if stride == 1:
35 | self.conv1 = conv2d_ABN(inplanes, planes, stride=1, activation_param=1e-3)
36 | else:
37 | if anti_alias_layer is None:
38 | self.conv1 = conv2d_ABN(inplanes, planes, stride=2, activation_param=1e-3)
39 | else:
40 | self.conv1 = nn.Sequential(conv2d_ABN(inplanes, planes, stride=1, activation_param=1e-3),
41 | anti_alias_layer(channels=planes, filt_size=3, stride=2))
42 |
43 | self.conv2 = conv2d_ABN(planes, planes, stride=1, activation="identity")
44 | self.relu = nn.ReLU(inplace=True)
45 | self.downsample = downsample
46 | self.stride = stride
47 | reduce_layer_planes = max(planes * self.expansion // 4, 64)
48 | self.se = SEModule(planes * self.expansion, reduce_layer_planes) if use_se else None
49 |
50 | def forward(self, x):
51 | if self.downsample is not None:
52 | residual = self.downsample(x)
53 | else:
54 | residual = x
55 |
56 | out = self.conv1(x)
57 | out = self.conv2(out)
58 |
59 | if self.se is not None: out = self.se(out)
60 |
61 | out += residual
62 |
63 | out = self.relu(out)
64 |
65 | return out
66 |
67 |
68 | class Bottleneck(nn.Module):
69 | expansion = 4
70 |
71 | def __init__(self, inplanes, planes, stride=1, downsample=None, use_se=True, anti_alias_layer=None):
72 | super(Bottleneck, self).__init__()
73 | self.conv1 = conv2d_ABN(inplanes, planes, kernel_size=1, stride=1, activation="leaky_relu",
74 | activation_param=1e-3)
75 | if stride == 1:
76 | self.conv2 = conv2d_ABN(planes, planes, kernel_size=3, stride=1, activation="leaky_relu",
77 | activation_param=1e-3)
78 | else:
79 | if anti_alias_layer is None:
80 | self.conv2 = conv2d_ABN(planes, planes, kernel_size=3, stride=2, activation="leaky_relu",
81 | activation_param=1e-3)
82 | else:
83 | self.conv2 = nn.Sequential(conv2d_ABN(planes, planes, kernel_size=3, stride=1,
84 | activation="leaky_relu", activation_param=1e-3),
85 | anti_alias_layer(channels=planes, filt_size=3, stride=2))
86 |
87 | self.conv3 = conv2d_ABN(planes, planes * self.expansion, kernel_size=1, stride=1,
88 | activation="identity")
89 |
90 | self.relu = nn.ReLU(inplace=True)
91 | self.downsample = downsample
92 | self.stride = stride
93 |
94 | reduce_layer_planes = max(planes * self.expansion // 8, 64)
95 | self.se = SEModule(planes, reduce_layer_planes) if use_se else None
96 |
97 | def forward(self, x):
98 | if self.downsample is not None:
99 | residual = self.downsample(x)
100 | else:
101 | residual = x
102 |
103 | out = self.conv1(x)
104 | out = self.conv2(out)
105 | if self.se is not None: out = self.se(out)
106 |
107 | out = self.conv3(out)
108 | out = out + residual # no inplace
109 | out = self.relu(out)
110 |
111 | return out
112 |
113 |
114 | class TResNet(nn.Module):
115 |
116 | def __init__(self, layers, in_chans=3, num_classes=1000, width_factor=1.0, remove_aa_jit=False):
117 | super(TResNet, self).__init__()
118 |
119 | # JIT layers
120 | space_to_depth = SpaceToDepthModule()
121 | anti_alias_layer = partial(AntiAliasDownsampleLayer, remove_aa_jit=remove_aa_jit)
122 | global_pool_layer = FastGlobalAvgPool2d(flatten=True)
123 |
124 | # TResnet stages
125 | self.inplanes = int(64 * width_factor)
126 | self.planes = int(64 * width_factor)
127 | conv1 = conv2d_ABN(in_chans * 16, self.planes, stride=1, kernel_size=3)
128 | layer1 = self._make_layer(BasicBlock, self.planes, layers[0], stride=1, use_se=True,
129 | anti_alias_layer=anti_alias_layer) # 56x56
130 | layer2 = self._make_layer(BasicBlock, self.planes * 2, layers[1], stride=2, use_se=True,
131 | anti_alias_layer=anti_alias_layer) # 28x28
132 | layer3 = self._make_layer(Bottleneck, self.planes * 4, layers[2], stride=2, use_se=True,
133 | anti_alias_layer=anti_alias_layer) # 14x14
134 | layer4 = self._make_layer(Bottleneck, self.planes * 8, layers[3], stride=2, use_se=False,
135 | anti_alias_layer=anti_alias_layer) # 7x7
136 |
137 | # body
138 | self.body = nn.Sequential(OrderedDict([
139 | ('SpaceToDepth', space_to_depth),
140 | ('conv1', conv1),
141 | ('layer1', layer1),
142 | ('layer2', layer2),
143 | ('layer3', layer3),
144 | ('layer4', layer4)]))
145 |
146 | # head
147 | self.embeddings = []
148 | self.global_pool = nn.Sequential(OrderedDict([('global_pool_layer', global_pool_layer)]))
149 | self.num_features = (self.planes * 8) * Bottleneck.expansion
150 | fc = nn.Linear(self.num_features, num_classes)
151 | self.head = nn.Sequential(OrderedDict([('fc', fc)]))
152 |
153 | # model initilization
154 | for m in self.modules():
155 | if isinstance(m, nn.Conv2d):
156 | nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='leaky_relu')
157 | elif isinstance(m, nn.BatchNorm2d) or isinstance(m, InPlaceABN):
158 | nn.init.constant_(m.weight, 1)
159 | nn.init.constant_(m.bias, 0)
160 |
161 | # residual connections special initialization
162 | for m in self.modules():
163 | if isinstance(m, BasicBlock):
164 | m.conv2[1].weight = nn.Parameter(torch.zeros_like(m.conv2[1].weight)) # BN to zero
165 | if isinstance(m, Bottleneck):
166 | m.conv3[1].weight = nn.Parameter(torch.zeros_like(m.conv3[1].weight)) # BN to zero
167 | if isinstance(m, nn.Linear): m.weight.data.normal_(0, 0.01)
168 |
169 | def _make_layer(self, block, planes, blocks, stride=1, use_se=True, anti_alias_layer=None):
170 | downsample = None
171 | if stride != 1 or self.inplanes != planes * block.expansion:
172 | layers = []
173 | if stride == 2:
174 | # avg pooling before 1x1 conv
175 | layers.append(nn.AvgPool2d(kernel_size=2, stride=2, ceil_mode=True, count_include_pad=False))
176 | layers += [conv2d_ABN(self.inplanes, planes * block.expansion, kernel_size=1, stride=1,
177 | activation="identity")]
178 | downsample = nn.Sequential(*layers)
179 |
180 | layers = []
181 | layers.append(block(self.inplanes, planes, stride, downsample, use_se=use_se,
182 | anti_alias_layer=anti_alias_layer))
183 | self.inplanes = planes * block.expansion
184 | for i in range(1, blocks): layers.append(
185 | block(self.inplanes, planes, use_se=use_se, anti_alias_layer=anti_alias_layer))
186 | return nn.Sequential(*layers)
187 |
188 | def forward(self, x):
189 | x = self.body(x)
190 | self.embeddings = self.global_pool(x)
191 | logits = self.head(self.embeddings)
192 | return logits
193 |
194 |
195 | def TResnetM(model_params):
196 | """ Constructs a medium TResnet model.
197 | """
198 | in_chans = 3
199 | num_classes = model_params['num_classes']
200 | remove_aa_jit = model_params['remove_aa_jit']
201 | model = TResNet(layers=[3, 4, 11, 3], num_classes=num_classes, in_chans=in_chans,
202 | remove_aa_jit=remove_aa_jit)
203 | return model
204 |
205 |
206 | def TResnetL(model_params):
207 | """ Constructs a large TResnet model.
208 | """
209 | in_chans = 3
210 | num_classes = model_params['num_classes']
211 | remove_aa_jit = model_params['remove_aa_jit']
212 | model = TResNet(layers=[4, 5, 18, 3], num_classes=num_classes, in_chans=in_chans, width_factor=1.2,
213 | remove_aa_jit=remove_aa_jit)
214 | return model
215 |
216 |
217 | def TResnetXL(model_params):
218 | """ Constructs an extra-large TResnet model.
219 | """
220 | in_chans = 3
221 | num_classes = model_params['num_classes']
222 | remove_aa_jit = model_params['remove_aa_jit']
223 | model = TResNet(layers=[4, 5, 24, 3], num_classes=num_classes, in_chans=in_chans, width_factor=1.3,
224 | remove_aa_jit=remove_aa_jit)
225 |
226 | return model
227 |
--------------------------------------------------------------------------------
/src/models/tresnet_v2/__init__.py:
--------------------------------------------------------------------------------
1 | from .tresnet_v2 import TResnetL_V2
2 |
--------------------------------------------------------------------------------
/src/models/tresnet_v2/layers/anti_aliasing.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn.parallel
3 | import numpy as np
4 | import torch.nn as nn
5 | import torch.nn.functional as F
6 |
7 |
8 | class AntiAliasDownsampleLayer(nn.Module):
9 | def __init__(self, remove_aa_jit: bool = False, filt_size: int = 3, stride: int = 2,
10 | channels: int = 0):
11 | super(AntiAliasDownsampleLayer, self).__init__()
12 | if not remove_aa_jit:
13 | self.op = DownsampleJIT(filt_size, stride, channels)
14 | else:
15 | self.op = Downsample(filt_size, stride, channels)
16 |
17 | def forward(self, x):
18 | return self.op(x)
19 |
20 |
21 | @torch.jit.script
22 | class DownsampleJIT(object):
23 | def __init__(self, filt_size: int = 3, stride: int = 2, channels: int = 0):
24 | self.stride = stride
25 | self.filt_size = filt_size
26 | self.channels = channels
27 |
28 | assert self.filt_size == 3
29 | assert stride == 2
30 | a = torch.tensor([1., 2., 1.])
31 |
32 | filt = (a[:, None] * a[None, :]).clone().detach()
33 | filt = filt / torch.sum(filt)
34 | self.filt = filt[None, None, :, :].repeat((self.channels, 1, 1, 1)).cuda().half()
35 |
36 | def __call__(self, input: torch.Tensor):
37 | if input.dtype != self.filt.dtype:
38 | self.filt = self.filt.float()
39 | input_pad = F.pad(input, (1, 1, 1, 1), 'reflect')
40 | return F.conv2d(input_pad, self.filt, stride=2, padding=0, groups=input.shape[1])
41 |
42 |
43 | class Downsample(nn.Module):
44 | def __init__(self, filt_size=3, stride=2, channels=None):
45 | super(Downsample, self).__init__()
46 | self.filt_size = filt_size
47 | self.stride = stride
48 | self.channels = channels
49 |
50 |
51 | assert self.filt_size == 3
52 | a = torch.tensor([1., 2., 1.])
53 |
54 | filt = (a[:, None] * a[None, :])
55 | filt = filt / torch.sum(filt)
56 |
57 | # self.filt = filt[None, None, :, :].repeat((self.channels, 1, 1, 1))
58 | self.register_buffer('filt', filt[None, None, :, :].repeat((self.channels, 1, 1, 1)))
59 |
60 | def forward(self, input):
61 | input_pad = F.pad(input, (1, 1, 1, 1), 'reflect')
62 | return F.conv2d(input_pad, self.filt, stride=self.stride, padding=0, groups=input.shape[1])
63 |
--------------------------------------------------------------------------------
/src/models/tresnet_v2/layers/avg_pool.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import torch.nn.functional as F
4 |
5 |
6 |
7 | class FastGlobalAvgPool2d(nn.Module):
8 | def __init__(self, flatten=False):
9 | super(FastGlobalAvgPool2d, self).__init__()
10 | self.flatten = flatten
11 |
12 | def forward(self, x):
13 | if self.flatten:
14 | in_size = x.size()
15 | return x.view((in_size[0], in_size[1], -1)).mean(dim=2)
16 | else:
17 | return x.view(x.size(0), x.size(1), -1).mean(-1).view(x.size(0), x.size(1), 1, 1)
18 |
19 |
20 |
--------------------------------------------------------------------------------
/src/models/tresnet_v2/layers/space_to_depth.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 |
4 |
5 | class SpaceToDepth(nn.Module):
6 | def __init__(self, block_size=4):
7 | super().__init__()
8 | assert block_size == 4
9 | self.bs = block_size
10 |
11 | def forward(self, x):
12 | N, C, H, W = x.size()
13 | x = x.view(N, C, H // self.bs, self.bs, W // self.bs, self.bs) # (N, C, H//bs, bs, W//bs, bs)
14 | x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # (N, bs, bs, C, H//bs, W//bs)
15 | x = x.view(N, C * (self.bs ** 2), H // self.bs, W // self.bs) # (N, C*bs^2, H//bs, W//bs)
16 | return x
17 |
18 |
19 | @torch.jit.script
20 | class SpaceToDepthJit(object):
21 | def __call__(self, x: torch.Tensor):
22 | # assuming hard-coded that block_size==4 for acceleration
23 | N, C, H, W = x.size()
24 | x = x.view(N, C, H // 4, 4, W // 4, 4) # (N, C, H//bs, bs, W//bs, bs)
25 | x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # (N, bs, bs, C, H//bs, W//bs)
26 | x = x.view(N, C * 16, H // 4, W // 4) # (N, C*bs^2, H//bs, W//bs)
27 | return x
28 |
29 |
30 | class SpaceToDepthModule(nn.Module):
31 | def __init__(self, remove_model_jit=False):
32 | super().__init__()
33 | if not remove_model_jit:
34 | self.op = SpaceToDepthJit()
35 | else:
36 | self.op = SpaceToDepth()
37 |
38 | def forward(self, x):
39 | return self.op(x)
40 |
41 |
42 | class DepthToSpace(nn.Module):
43 |
44 | def __init__(self, block_size):
45 | super().__init__()
46 | self.bs = block_size
47 |
48 | def forward(self, x):
49 | N, C, H, W = x.size()
50 | x = x.view(N, self.bs, self.bs, C // (self.bs ** 2), H, W) # (N, bs, bs, C//bs^2, H, W)
51 | x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # (N, C//bs^2, H, bs, W, bs)
52 | x = x.view(N, C // (self.bs ** 2), H * self.bs, W * self.bs) # (N, C//bs^2, H * bs, W * bs)
53 | return x
--------------------------------------------------------------------------------
/src/models/tresnet_v2/layers/squeeze_and_excite.py:
--------------------------------------------------------------------------------
1 | import torch.nn as nn
2 | import torch.nn.functional as F
3 | from src.models.tresnet.layers.avg_pool import FastGlobalAvgPool2d
4 |
5 |
6 | class Flatten(nn.Module):
7 | def forward(self, x):
8 | return x.view(x.size(0), -1)
9 |
10 |
11 | class SEModule(nn.Module):
12 |
13 | def __init__(self, channels, reduction_channels, inplace=True):
14 | super(SEModule, self).__init__()
15 | self.avg_pool = FastGlobalAvgPool2d()
16 | self.fc1 = nn.Conv2d(channels, reduction_channels, kernel_size=1, padding=0, bias=True)
17 | self.relu = nn.ReLU(inplace=inplace)
18 | self.fc2 = nn.Conv2d(reduction_channels, channels, kernel_size=1, padding=0, bias=True)
19 | # self.activation = hard_sigmoid(inplace=inplace)
20 | self.activation = nn.Sigmoid()
21 |
22 | def forward(self, x):
23 | x_se = self.avg_pool(x)
24 | x_se2 = self.fc1(x_se)
25 | x_se2 = self.relu(x_se2)
26 | x_se = self.fc2(x_se2)
27 | x_se = self.activation(x_se)
28 | return x * x_se
29 |
30 | class hard_sigmoid(nn.Module):
31 | def __init__(self, inplace=True):
32 | super(hard_sigmoid, self).__init__()
33 | self.inplace = inplace
34 |
35 | def forward(self, x):
36 | if self.inplace:
37 | return x.add_(3.).clamp_(0., 6.).div_(6.)
38 | else:
39 | return F.relu6(x + 3.) / 6.
--------------------------------------------------------------------------------
/src/models/tresnet_v2/tresnet_v2.py:
--------------------------------------------------------------------------------
1 | import math
2 | from collections import OrderedDict
3 | from functools import partial
4 |
5 | import torch.nn as nn
6 | import torch
7 | from torch.nn import Module as Module
8 |
9 | from src.models.tresnet.layers.anti_aliasing import AntiAliasDownsampleLayer
10 | from .layers.avg_pool import FastGlobalAvgPool2d
11 | from src.models.tresnet.layers.space_to_depth import SpaceToDepthModule
12 | from .layers.squeeze_and_excite import SEModule
13 |
14 | from inplace_abn import InPlaceABN
15 | from inplace_abn import ABN
16 |
17 |
18 | def InplacABN_to_ABN(module: nn.Module) -> nn.Module:
19 | # convert all InplaceABN layer to bit-accurate ABN layers.
20 | if isinstance(module, InPlaceABN):
21 | module_new = ABN(module.num_features, activation=module.activation,
22 | activation_param=module.activation_param)
23 | for key in module.state_dict():
24 | module_new.state_dict()[key].copy_(module.state_dict()[key])
25 | module_new.training = module.training
26 | module_new.weight.data = module_new.weight.abs() + module_new.eps
27 | return module_new
28 | for name, child in reversed(module._modules.items()):
29 | new_child = InplacABN_to_ABN(child)
30 | if new_child != child:
31 | module._modules[name] = new_child
32 | return module
33 |
34 |
35 | def conv3x3(in_planes, out_planes, stride=1):
36 | return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
37 |
38 |
39 | def conv3x3_depth(planes, stride=1):
40 | return nn.Conv2d(planes, planes, groups=planes, kernel_size=3, stride=stride, padding=1, bias=False)
41 |
42 |
43 | def conv2d(ni, nf, stride):
44 | return nn.Sequential(
45 | nn.Conv2d(ni, nf, kernel_size=3, stride=stride, padding=1, bias=False),
46 | nn.BatchNorm2d(nf),
47 | nn.ReLU(inplace=True)
48 | )
49 |
50 |
51 | def conv2d_ABN(ni, nf, stride, activation="leaky_relu", kernel_size=3, activation_param=1e-2, groups=1):
52 | activation_param = 1e-6
53 | return nn.Sequential(
54 | nn.Conv2d(ni, nf, kernel_size=kernel_size, stride=stride, padding=kernel_size // 2, groups=groups,
55 | bias=False),
56 | InPlaceABN(num_features=nf, activation=activation, activation_param=activation_param)
57 | )
58 |
59 |
60 | class BasicBlock(Module):
61 | expansion = 1
62 |
63 | def __init__(self, inplanes, planes, stride=1, downsample=None, use_se=True, anti_alias_layer=None):
64 | super(BasicBlock, self).__init__()
65 | if stride == 1:
66 | self.conv1 = conv2d_ABN(inplanes, planes, stride=1, activation_param=1e-3)
67 | else:
68 | if anti_alias_layer is None:
69 | self.conv1 = conv2d_ABN(inplanes, planes, stride=2, activation_param=1e-3)
70 | else:
71 | self.conv1 = nn.Sequential(conv2d_ABN(inplanes, planes, stride=1, activation_param=1e-3),
72 | anti_alias_layer(channels=planes, filt_size=3, stride=2))
73 |
74 | self.conv2 = conv2d_ABN(planes, planes, stride=1, activation="identity")
75 | self.relu = nn.ReLU(inplace=True)
76 | self.downsample = downsample
77 | self.stride = stride
78 | reduce_layer_planes = max(planes * self.expansion // 4, 64)
79 | self.se = SEModule(channels=planes * self.expansion, reduction_channels=reduce_layer_planes) if \
80 | use_se else None
81 |
82 | def forward(self, x):
83 | if self.downsample is not None:
84 | residual = self.downsample(x)
85 | else:
86 | residual = x
87 |
88 | out = self.conv1(x)
89 | out = self.conv2(out)
90 |
91 | if self.se is not None: out = self.se(out)
92 |
93 | out += residual
94 |
95 | out = self.relu(out)
96 |
97 | return out
98 |
99 |
100 | class Bottleneck(Module):
101 | expansion = 4
102 |
103 | def __init__(self, inplanes, planes, stride=1, downsample=None, use_se=True, anti_alias_layer=None):
104 | super(Bottleneck, self).__init__()
105 | self.conv1 = conv2d_ABN(inplanes, planes, kernel_size=1, stride=1, activation="leaky_relu",
106 | activation_param=1e-3)
107 | if stride == 1:
108 | self.conv2 = conv2d_ABN(planes, planes, kernel_size=3, stride=1, activation="leaky_relu",
109 | activation_param=1e-3)
110 | else:
111 | if anti_alias_layer is None:
112 | self.conv2 = conv2d_ABN(planes, planes, kernel_size=3, stride=2, activation="leaky_relu",
113 | activation_param=1e-3)
114 | else:
115 | self.conv2 = nn.Sequential(conv2d_ABN(planes, planes, kernel_size=3, stride=1,
116 | activation="leaky_relu", activation_param=1e-3),
117 | anti_alias_layer(channels=planes, filt_size=3, stride=2))
118 |
119 | self.conv3 = conv2d_ABN(planes, planes * self.expansion, kernel_size=1, stride=1,
120 | activation="identity")
121 |
122 | self.relu = nn.ReLU(inplace=True)
123 | self.downsample = downsample
124 | self.stride = stride
125 |
126 | reduce_layer_planes = max(planes * self.expansion // 8, 64)
127 | self.se = SEModule(planes, reduce_layer_planes) if use_se else None
128 |
129 | def forward(self, x):
130 | if self.downsample is not None:
131 | residual = self.downsample(x)
132 | else:
133 | residual = x
134 |
135 | out = self.conv1(x)
136 | out = self.conv2(out)
137 | if self.se is not None: out = self.se(out)
138 |
139 | out = self.conv3(out)
140 | out = out + residual # no inplace
141 | out = self.relu(out)
142 |
143 | return out
144 |
145 |
146 | class TResNetV2(Module):
147 |
148 | def __init__(self, layers, in_chans=3, num_classes=1000, width_factor=1.0, remove_model_jit=False):
149 | super(TResNetV2, self).__init__()
150 | ## body
151 | self.inplanes = int(int(64 * width_factor + 4) / 8) * 8
152 | self.planes = int(int(64 * width_factor + 4) / 8) * 8
153 | SpaceToDepth = SpaceToDepthModule(remove_model_jit=remove_model_jit)
154 | conv1 = conv2d_ABN(in_chans * 16, self.planes, stride=1, kernel_size=3)
155 |
156 | anti_alias_layer = partial(AntiAliasDownsampleLayer, remove_aa_jit=remove_model_jit)
157 | global_pool_layer = FastGlobalAvgPool2d(flatten=True)
158 | layer1 = self._make_layer(Bottleneck, self.planes, layers[0], stride=1, use_se=True,
159 | anti_alias_layer=anti_alias_layer) # 56x56
160 | layer2 = self._make_layer(Bottleneck, self.planes * 2, layers[1], stride=2, use_se=True,
161 | anti_alias_layer=anti_alias_layer) # 28x28
162 | layer3 = self._make_layer(Bottleneck, self.planes * 4, layers[2], stride=2, use_se=True,
163 | anti_alias_layer=anti_alias_layer) # 14x14
164 | layer4 = self._make_layer(Bottleneck, self.planes * 8, layers[3], stride=2, use_se=False,
165 | anti_alias_layer=anti_alias_layer) # 7x7
166 |
167 | self.body = nn.Sequential(OrderedDict([
168 | ('SpaceToDepth', SpaceToDepth),
169 | ('conv1', conv1),
170 | ('layer1', layer1),
171 | ('layer2', layer2),
172 | ('layer3', layer3),
173 | ('layer4', layer4)]))
174 |
175 | # default head
176 | self.num_features = (self.planes * 8) * Bottleneck.expansion
177 |
178 | fc = nn.Linear(self.num_features , num_classes)
179 |
180 | self.global_pool = nn.Sequential(OrderedDict([('global_pool_layer', global_pool_layer)]))
181 |
182 | self.head = nn.Sequential(OrderedDict([('fc', fc)]))
183 |
184 | self.embeddings = []
185 |
186 | for m in self.modules():
187 | if isinstance(m, nn.Conv2d):
188 | nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='leaky_relu')
189 | elif isinstance(m, nn.BatchNorm2d) or isinstance(m, InPlaceABN):
190 | nn.init.constant_(m.weight, 1)
191 | nn.init.constant_(m.bias, 0)
192 |
193 | # initilize resnet in a magic way
194 | for m in self.modules():
195 | if isinstance(m, BasicBlock):
196 | m.conv2[1].weight = nn.Parameter(torch.zeros_like(m.conv2[1].weight)) # BN to zero
197 | if isinstance(m, Bottleneck):
198 | m.conv3[1].weight = nn.Parameter(torch.zeros_like(m.conv3[1].weight)) # BN to zero
199 | if isinstance(m, nn.Linear): m.weight.data.normal_(0, 0.01)
200 |
201 | def _make_layer(self, block, planes, blocks, stride=1, use_se=True, anti_alias_layer=None):
202 | downsample = None
203 | if stride != 1 or self.inplanes != planes * block.expansion:
204 | layers = []
205 | if stride == 2:
206 | # avg pooling before 1x1 conv
207 | layers.append(
208 | nn.AvgPool2d(kernel_size=2, stride=2, ceil_mode=True, count_include_pad=False))
209 | layers += [
210 | conv2d_ABN(self.inplanes, planes * block.expansion, kernel_size=1, stride=1,
211 | activation="identity")]
212 | downsample = nn.Sequential(*layers)
213 |
214 | layers = []
215 | layers.append(block(self.inplanes, planes, stride, downsample, use_se=use_se,
216 | anti_alias_layer=anti_alias_layer))
217 | self.inplanes = planes * block.expansion
218 | for i in range(1, blocks): layers.append(
219 | block(self.inplanes, planes, use_se=use_se, anti_alias_layer=anti_alias_layer))
220 | return nn.Sequential(*layers)
221 |
222 | def forward(self, x):
223 | x = self.body(x)
224 | # self.embeddings = self.global_pool(x)
225 | logits = self.head(self.global_pool(x))
226 | return logits
227 |
228 |
229 | def TResnetL_V2(model_params):
230 | """Constructs a large TResnet model.
231 | """
232 | in_chans = 3
233 | num_classes = model_params['num_classes']
234 | remove_model_jit = False
235 | layers_list = [3, 4, 23, 3]
236 | width_factor = 1.0
237 | model = TResNetV2(layers=layers_list, num_classes=num_classes, in_chans=in_chans,
238 | width_factor=width_factor, remove_model_jit=remove_model_jit)
239 | return model
240 |
--------------------------------------------------------------------------------
/src/models/utils/__init__.py:
--------------------------------------------------------------------------------
1 | from .factory import create_model
2 | __all__ = ['create_model']
--------------------------------------------------------------------------------
/src/models/utils/factory.py:
--------------------------------------------------------------------------------
1 | import logging
2 |
3 | from ..tresnet_v2 import TResnetL_V2
4 |
5 | logger = logging.getLogger(__name__)
6 |
7 | from ..tresnet import TResnetM, TResnetL, TResnetXL
8 |
9 |
10 | def create_model(args):
11 | """Create a model
12 | """
13 | model_params = {'args': args, 'num_classes': args.num_classes,'remove_aa_jit': args.remove_aa_jit}
14 | args = model_params['args']
15 | args.model_name = args.model_name.lower()
16 |
17 | if args.model_name=='tresnet_m':
18 | model = TResnetM(model_params)
19 | elif args.model_name=='tresnet_l':
20 | model = TResnetL(model_params)
21 | elif args.model_name=='tresnet_l_v2':
22 | model = TResnetL_V2(model_params)
23 | elif args.model_name=='tresnet_xl':
24 | model = TResnetXL(model_params)
25 | else:
26 | print("model: {} not found !!".format(args.model_name))
27 | exit(-1)
28 |
29 | return model
30 |
--------------------------------------------------------------------------------
/tests/test_TResNetV2:
--------------------------------------------------------------------------------
1 |
2 | # test_TResNetV2.py - Generated by https://www.codium.ai/
3 |
4 | import unittest
5 |
6 | """
7 | Code Analysis:
8 | - This class is a subclass of the Module class from the torch.nn library.
9 | - It initializes the TResNetV2 model with the given parameters.
10 | - It creates a convolutional neural network with a body, head, and global pooling layers.
11 | - It uses a SpaceToDepthModule, conv2d_ABN, AntiAliasDownsampleLayer, FastGlobalAvgPool2d, SEModule, InPlaceABN, and ABN.
12 | - It uses a Bottleneck block with a convolutional layer, batch normalization, and ReLU activation.
13 | - It uses a BasicBlock with a convolutional layer, batch normalization, and ReLU activation.
14 | - It initializes the weights and biases of the convolutional layers and linear layers with Kaiming normal and constant values, respectively.
15 | - It sets the conv2 and conv3 weights of the BasicBlock and Bottleneck layers to zero.
16 | - It has a forward method which takes in an input and returns the logits.
17 | """
18 |
19 |
20 | """
21 | Test strategies:
22 | - test_init(): tests that the TResNetV2 model is initialized correctly with the given parameters.
23 | - test_conv1(): tests that the conv1 layer is initialized correctly.
24 | - test_anti_alias_layer(): tests that the AntiAliasDownsampleLayer is initialized correctly.
25 | - test_global_pool_layer(): tests that the FastGlobalAvgPool2d is initialized correctly.
26 | - test_bottleneck_block(): tests that the Bottleneck block is initialized correctly.
27 | - test_basic_block(): tests that the BasicBlock is initialized correctly.
28 | - test_weights_and_biases(): tests that the weights and biases of the convolutional layers and linear layers are initialized correctly.
29 | - test_conv2_and_conv3_weights(): tests that the conv2 and conv3 weights of the BasicBlock and Bottleneck layers are set to zero.
30 | - test_forward(): tests that the forward method takes in an input and returns the logits.
31 | """
32 |
33 |
34 | class TestTResNetV2(unittest.TestCase):
35 |
36 | def setUp(self):
37 | self.layers = [3, 4, 6, 3]
38 | self.in_chans = 3
39 | self.num_classes = 1000
40 | self.width_factor = 1.0
41 | self.remove_model_jit = False
42 | self.model = TResNetV2(self.layers, self.in_chans, self.num_classes, self.width_factor, self.remove_model_jit)
43 |
44 | def test_init(self):
45 | self.assertEqual(self.model.inplanes, 64)
46 | self.assertEqual(self.model.planes, 64)
47 | self.assertEqual(self.model.num_features, 2048)
48 |
49 | def test_conv1(self):
50 | conv1 = self.model.body[1]
51 | self.assertIsInstance(conv1, ABN)
52 | self.assertEqual(conv1.in_channels, 48)
53 | self.assertEqual(conv1.out_channels, 64)
54 | self.assertEqual(conv1.kernel_size, (3, 3))
55 | self.assertEqual(conv1.stride, (1, 1))
56 |
57 | def test_anti_alias_layer(self):
58 | layer1 = self.model.body[3]
59 | anti_alias_layer = layer1[0].anti_alias_layer
60 | self.assertIsInstance(anti_alias_layer, partial)
61 | self.assertEqual(anti_alias_layer.func, AntiAliasDownsampleLayer)
62 | self.assertEqual(anti_alias_layer.args, (self.remove_model_jit,))
63 |
64 | def test_global_pool_layer(self):
65 | global_pool = self.model.global_pool[0]
66 | self.assertIsInstance(global_pool, FastGlobalAvgPool2d)
67 | self.assertTrue(global_pool.flatten)
68 |
69 | def test_bottleneck_block(self):
70 | layer1 = self.model.body[3]
71 | bottleneck = layer1[0]
72 | self.assertIsInstance(bottleneck, Bottleneck)
73 | self.assertEqual(bottleneck.inplanes, 64)
74 | self.assertEqual(bottleneck.planes, 64)
75 | self.assertEqual(bottleneck.stride, 1)
76 | self.assertIsInstance(bottleneck.downsample, nn.Sequential)
77 | self.assertIsInstance(bottleneck.se, SEModule)
78 |
79 | def test_basic_block(self):
80 | layer2 = self.model.body[4]
81 | basicblock = layer2[0]
82 | self.assertIsInstance(basicblock, BasicBlock)
83 | self.assertEqual(basicblock.inplanes, 128)
84 | self.assertEqual(basicblock.planes, 128)
85 | self.assertEqual(basicblock.stride, 2)
86 | self.assertIsInstance(basicblock.downsample, nn.Sequential)
87 |
88 | def test_weights_and_biases(self):
89 | for m in self.model.modules():
90 | if isinstance(m, nn.Conv2d):
91 | weight = m.weight
92 | fan = math.sqrt(weight[0].numel())
93 | nn.init.kaiming_normal_(weight, mode='fan_out', nonlinearity='leaky_relu')
94 | for w in weight:
95 | for i in range(w[0].numel()):
96 | self.assertAlmostEqual(w[0][i], 0, delta=0.001 * fan)
97 |
98 | elif isinstance(m, nn.BatchNorm2d) or isinstance(m, InPlaceABN):
99 | weight = m.weight
100 | bias = m.bias
101 | nn.init.constant_(weight, 1)
102 |
--------------------------------------------------------------------------------