├── LICENSE ├── README.md ├── adaptive_avgmax_pool.py ├── convert_from_mxnet.py ├── dataset.py ├── dpn.py ├── hubconf.py ├── inference.py ├── model_factory.py └── validate.py /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PyTorch Pretrained Dual Path Networks (DPN) 2 | 3 | This repository includes a PyTorch implementation of DualPathNetworks (https://arxiv.org/abs/1707.01629) that works with cypw's pretrained weights. 4 | 5 | The code is based upon cypw's original MXNet implementation (https://github.com/cypw/DPNs) with oyam's PyTorch implementation (https://github.com/oyam/pytorch-DPNs) as a reference. 6 | 7 | Original testing of these models and all validation was done with torch (0.2.0.post1) and mxnet (0.11.0) pip packages installed. The models have since been updated and tested with Conda installs of PyTorch 1.0 and 1.1. 8 | 9 | ## Pretrained 10 | 11 | The model weights have already been converted to PyTorch and hosted at a fixed URL. You can use those pretrained weights by calling the model entrypoint functions with `pretrained=True` 12 | 13 | ## PyTorch Hub 14 | 15 | Models can also be access via the PyTorch Hub API 16 | 17 | ``` 18 | >>> torch.hub.list('rwightman/pytorch-dpn-pretrained') 19 | ['dpn68', ...] 20 | >>> model = torch.hub.load('rwightman/pytorch-dpn-pretrained', 'dpn68', pretrained=True) 21 | >>> model.eval() 22 | >>> output = model(torch.randn(1,3,224,224)) 23 | ``` 24 | 25 | ## Conversion 26 | 27 | If you want to convert the weights yourself, download and untar trained weights files from https://github.com/cypw/DPNs#trained-models into a './pretrained' folder where this code is located. 28 | 29 | The weights can be converted by running the conversion script as so: 30 | 31 | python convert_from_mxnet.py ./pretrained/ --model dpn107 32 | 33 | ## Results 34 | 35 | The following tables contain the validation results (from included validation code) on ImageNet-1K. The DPN models are using the converted weights from the pretrained MXNet models. Also included are results from Torchvision ResNet, DenseNet as well as an InceptionV4 and InceptionResnetV2 port (by Cadene, https://github.com/Cadene/pretrained-models.pytorch) for reference. 36 | 37 | All DPN runs at image size above 224x224 are using the mean-max pooling scheme (https://github.com/cypw/DPNs#mean-max-pooling) described by cypw. 38 | 39 | Note that results are sensitive to image crop, scaling interpolation, and even the image library used. All image operations for these models are performed with PIL. Bicubic interpolation is used for all but the ResNet models where bilinear produced better results. Results for InceptionV4 and InceptionResnetV2 where better at 100% crop, all other networks being evaluated at their native training resolution use 87.5% crop. 40 | 41 | Models with a '*' are using weights that were trained on ImageNet-5k and fine-tuned on ImageNet-1k. The MXNet weights files for these have an '-extra' suffix in their name. 42 | 43 | ### Results @224x224 44 | 45 | |Model | Prec@1 (Err) | Prec@5 (Err) | #Params | Crop | 46 | |---|---|---|---|---| 47 | | DenseNet121 | 74.752 (25.248) | 92.152 (7.848) | 7.98 | 87.5% | 48 | | ResNet50 | 76.130 (23.870) | 92.862 (7.138) | 25.56 | 87.5% | 49 | | DenseNet169 | 75.912 (24.088) | 93.024 (6.976) | 14.15 | 87.5% | 50 | | DualPathNet68 | 76.346 (23.654) | 93.008 (6.992) | 12.61 | 87.5% | 51 | | ResNet101 | 77.374 (22.626) | 93.546 (6.454) | 44.55 | 87.5% | 52 | | DenseNet201 | 77.290 (22.710) | 93.478 (6.522) | 20.01 | 87.5% | 53 | | DenseNet161 | 77.348 (22.652) | 93.646 (6.354) | 28.68 | 87.5% | 54 | | DualPathNet68b* | 77.528 (22.472) | 93.846 (6.154) | 12.61 | 87.5% | 55 | | ResNet152 | 78.312 (21.688) | 94.046 (5.954) | 60.19 | 87.5% | 56 | | DualPathNet92 | 79.128 (20.872) | 94.448 (5.552) | 37.67 | 87.5% | 57 | | DualPathNet98 | 79.666 (20.334) | 94.646 (5.354) | 61.57 | 87.5% | 58 | | DualPathNet131 | 79.806 (20.194) | 94.706 (5.294) | 79.25 | 87.5% | 59 | | DualPathNet92* | 80.034 (19.966) | 94.868 (5.132) | 37.67 | 87.5% | 60 | | DualPathNet107 | 80.172 (19.828) | 94.938 (5.062) | 86.92 | 87.5% | 61 | 62 | ### Results @299x299 (test_time_pool=True for DPN) 63 | 64 | |Model | Prec@1 (Err) | Prec@5 (Err) | #Params | Crop | 65 | |---|---|---|---|---| 66 | | InceptionV3 | 77.436 (22.564) | 93.476 (6.524) | 27.16 | 87.5% | 67 | | DualPathNet68 | 78.006 (21.994) | 94.158 (5.842) | 12.61 | 100% | 68 | | DualPathNet68b* | 78.582 (21.418) | 94.470 (5.530) | 12.61 | 100% | 69 | | InceptionV4 | 80.138 (19.862) | 95.010 (4.99) | 42.68 | 100% | 70 | | DualPathNet92* | 80.408 (19.592) | 95.190 (4.810) | 37.67 | 100% | 71 | | DualPathNet92 | 80.480 (19.520) | 95.192 (4.808) | 37.67 | 100% | 72 | | InceptionResnetV2 | 80.492 (19.508) | 95.270 (4.730) | 55.85 | 100% | 73 | | DualPathNet98 | 81.062 (18.938) | 95.404 (4.596) | 61.57 | 100% | 74 | | DualPathNet131 | 81.208 (18.792) | 95.630 (4.370) | 79.25 | 100% | 75 | | DualPathNet107* | 81.432 (18.568) | 95.706 (4.294) | 86.92 | 100% | 76 | 77 | ### Results @320x320 (test_time_pool=True) 78 | 79 | |Model | Prec@1 (Err) | Prec@5 (Err) | #Params | Crop | 80 | |---|---|---|---|---| 81 | | DualPathNet68 | 78.450 (21.550) | 94.358 (5.642) | 12.61 | 100% | 82 | | DualPathNet68b* | 78.764 (21.236) | 94.726 (5.274) | 12.61 | 100% | 83 | | DualPathNet92* | 80.824 (19.176) | 95.570 (4.430) | 37.67 | 100% | 84 | | DualPathNet92 | 80.960 (19.040) | 95.500 (4.500) | 37.67 | 100% | 85 | | DualPathNet98 | 81.276 (18.724) | 95.666 (4.334) | 61.57 | 100% | 86 | | DualPathNet131 | 81.458 (18.542) | 95.786 (4.214) | 79.25 | 100% | 87 | | DualPathNet107* | 81.800 (18.200) | 95.910 (4.090) | 86.92 | 100% | 88 | 89 | -------------------------------------------------------------------------------- /adaptive_avgmax_pool.py: -------------------------------------------------------------------------------- 1 | """ PyTorch selectable adaptive pooling 2 | Adaptive pooling with the ability to select the type of pooling from: 3 | * 'avg' - Average pooling 4 | * 'max' - Max pooling 5 | * 'avgmax' - Sum of average and max pooling re-scaled by 0.5 6 | * 'avgmaxc' - Concatenation of average and max pooling along feature dim, doubles feature dim 7 | 8 | Both a functional and a nn.Module version of the pooling is provided. 9 | 10 | Author: Ross Wightman (rwightman) 11 | """ 12 | import torch 13 | import torch.nn as nn 14 | import torch.nn.functional as F 15 | 16 | 17 | def pooling_factor(pool_type='avg'): 18 | return 2 if pool_type == 'avgmaxc' else 1 19 | 20 | 21 | def adaptive_avgmax_pool2d(x, pool_type='avg', padding=0, count_include_pad=False): 22 | """Selectable global pooling function with dynamic input kernel size 23 | """ 24 | if pool_type == 'avgmaxc': 25 | x = torch.cat([ 26 | F.avg_pool2d( 27 | x, kernel_size=(x.size(2), x.size(3)), padding=padding, count_include_pad=count_include_pad), 28 | F.max_pool2d(x, kernel_size=(x.size(2), x.size(3)), padding=padding) 29 | ], dim=1) 30 | elif pool_type == 'avgmax': 31 | x_avg = F.avg_pool2d( 32 | x, kernel_size=(x.size(2), x.size(3)), padding=padding, count_include_pad=count_include_pad) 33 | x_max = F.max_pool2d(x, kernel_size=(x.size(2), x.size(3)), padding=padding) 34 | x = 0.5 * (x_avg + x_max) 35 | elif pool_type == 'max': 36 | x = F.max_pool2d(x, kernel_size=(x.size(2), x.size(3)), padding=padding) 37 | else: 38 | if pool_type != 'avg': 39 | print('Invalid pool type %s specified. Defaulting to average pooling.' % pool_type) 40 | x = F.avg_pool2d( 41 | x, kernel_size=(x.size(2), x.size(3)), padding=padding, count_include_pad=count_include_pad) 42 | return x 43 | 44 | 45 | class AdaptiveAvgMaxPool2d(torch.nn.Module): 46 | """Selectable global pooling layer with dynamic input kernel size 47 | """ 48 | def __init__(self, output_size=1, pool_type='avg'): 49 | super(AdaptiveAvgMaxPool2d, self).__init__() 50 | self.output_size = output_size 51 | self.pool_type = pool_type 52 | if pool_type == 'avgmaxc' or pool_type == 'avgmax': 53 | self.pool = nn.ModuleList([nn.AdaptiveAvgPool2d(output_size), nn.AdaptiveMaxPool2d(output_size)]) 54 | elif pool_type == 'max': 55 | self.pool = nn.AdaptiveMaxPool2d(output_size) 56 | else: 57 | if pool_type != 'avg': 58 | print('Invalid pool type %s specified. Defaulting to average pooling.' % pool_type) 59 | self.pool = nn.AdaptiveAvgPool2d(output_size) 60 | 61 | def forward(self, x): 62 | if self.pool_type == 'avgmaxc': 63 | x = torch.cat([p(x) for p in self.pool], dim=1) 64 | elif self.pool_type == 'avgmax': 65 | x = 0.5 * torch.sum(torch.stack([p(x) for p in self.pool]), 0).squeeze(dim=0) 66 | else: 67 | x = self.pool(x) 68 | return x 69 | 70 | def factor(self): 71 | return pooling_factor(self.pool_type) 72 | 73 | def __repr__(self): 74 | return self.__class__.__name__ + ' (' \ 75 | + 'output_size=' + str(self.output_size) \ 76 | + ', pool_type=' + self.pool_type + ')' 77 | -------------------------------------------------------------------------------- /convert_from_mxnet.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from __future__ import division 3 | from __future__ import print_function 4 | 5 | import os 6 | import argparse 7 | import torch 8 | import model_factory 9 | 10 | try: 11 | import mxnet 12 | has_mxnet = True 13 | except ImportError: 14 | has_mxnet = False 15 | 16 | 17 | def _convert_bn(k): 18 | aux = False 19 | if k == 'bias': 20 | add = 'beta' 21 | elif k == 'weight': 22 | add = 'gamma' 23 | elif k == 'running_mean': 24 | aux = True 25 | add = 'moving_mean' 26 | elif k == 'running_var': 27 | aux = True 28 | add = 'moving_var' 29 | else: 30 | assert False, 'Unknown key: %s' % k 31 | return aux, add 32 | 33 | 34 | def convert_from_mxnet(model, checkpoint_prefix, debug=False): 35 | _, mxnet_weights, mxnet_aux = mxnet.model.load_checkpoint(checkpoint_prefix, 0) 36 | remapped_state = {} 37 | for state_key in model.state_dict().keys(): 38 | k = state_key.split('.') 39 | aux = False 40 | mxnet_key = '' 41 | if k[-1] == 'num_batches_tracked': 42 | continue 43 | if k[0] == 'features': 44 | if k[1] == 'conv1_1': 45 | # input block 46 | mxnet_key += 'conv1_x_1__' 47 | if k[2] == 'bn': 48 | mxnet_key += 'relu-sp__bn_' 49 | aux, key_add = _convert_bn(k[3]) 50 | mxnet_key += key_add 51 | else: 52 | assert k[3] == 'weight' 53 | mxnet_key += 'conv_' + k[3] 54 | elif k[1] == 'conv5_bn_ac': 55 | # bn + ac at end of features block 56 | mxnet_key += 'conv5_x_x__relu-sp__bn_' 57 | assert k[2] == 'bn' 58 | aux, key_add = _convert_bn(k[3]) 59 | mxnet_key += key_add 60 | else: 61 | # middle blocks 62 | if model.b and 'c1x1_c' in k[2]: 63 | bc_block = True # b-variant split c-block special treatment 64 | else: 65 | bc_block = False 66 | ck = k[1].split('_') 67 | mxnet_key += ck[0] + '_x__' + ck[1] + '_' 68 | ck = k[2].split('_') 69 | mxnet_key += ck[0] + '-' + ck[1] 70 | if ck[1] == 'w' and len(ck) > 2: 71 | mxnet_key += '(s/2)' if ck[2] == 's2' else '(s/1)' 72 | mxnet_key += '__' 73 | if k[3] == 'bn': 74 | mxnet_key += 'bn_' if bc_block else 'bn__bn_' 75 | aux, key_add = _convert_bn(k[4]) 76 | mxnet_key += key_add 77 | else: 78 | ki = 3 if bc_block else 4 79 | assert k[ki] == 'weight' 80 | mxnet_key += 'conv_' + k[ki] 81 | elif k[0] == 'classifier': 82 | if 'fc6-1k_weight' in mxnet_weights: 83 | mxnet_key += 'fc6-1k_' 84 | else: 85 | mxnet_key += 'fc6_' 86 | mxnet_key += k[1] 87 | else: 88 | assert False, 'Unexpected token' 89 | 90 | if debug: 91 | print(mxnet_key, '=> ', state_key, end=' ') 92 | 93 | mxnet_array = mxnet_aux[mxnet_key] if aux else mxnet_weights[mxnet_key] 94 | torch_tensor = torch.from_numpy(mxnet_array.asnumpy()) 95 | if k[0] == 'classifier' and k[1] == 'weight': 96 | torch_tensor = torch_tensor.view(torch_tensor.size() + (1, 1)) 97 | remapped_state[state_key] = torch_tensor 98 | 99 | if debug: 100 | print(list(torch_tensor.size()), torch_tensor.mean(), torch_tensor.std()) 101 | 102 | model.load_state_dict(remapped_state) 103 | 104 | return model 105 | 106 | parser = argparse.ArgumentParser(description='MXNet to PyTorch DPN conversion') 107 | parser.add_argument('checkpoint_path', metavar='DIR', help='path to mxnet checkpoints') 108 | parser.add_argument('--model', '-m', metavar='MODEL', default='dpn92', 109 | help='model architecture (default: dpn92)') 110 | 111 | 112 | def main(): 113 | args = parser.parse_args() 114 | if 'dpn' not in args.model: 115 | print('Error: Can only convert DPN models.') 116 | exit(1) 117 | if not has_mxnet: 118 | print('Error: Cannot import MXNet module. Please install.') 119 | exit(1) 120 | 121 | model = model_factory.create_model(args.model, num_classes=1000, pretrained=False) 122 | 123 | model_prefix = args.model 124 | if model_prefix in ['dpn107', 'dpn68b', 'dpn92']: 125 | model_prefix += '-extra' 126 | checkpoint_base = os.path.join(args.checkpoint_path, model_prefix) 127 | convert_from_mxnet(model, checkpoint_base) 128 | 129 | output_checkpoint = os.path.join(args.checkpoint_path, model_prefix + '.pth') 130 | torch.save(model.state_dict(), output_checkpoint) 131 | 132 | 133 | if __name__ == '__main__': 134 | main() 135 | -------------------------------------------------------------------------------- /dataset.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from __future__ import division 3 | from __future__ import print_function 4 | 5 | import torch.utils.data as data 6 | 7 | import os 8 | import re 9 | import torch 10 | from PIL import Image 11 | 12 | IMG_EXTENSIONS = ['.png', '.jpg', '.jpeg'] 13 | 14 | 15 | def natural_key(string_): 16 | """See http://www.codinghorror.com/blog/archives/001018.html""" 17 | return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())] 18 | 19 | 20 | def find_images_and_targets(folder, types=IMG_EXTENSIONS, class_to_idx=None, leaf_name_only=True, sort=True): 21 | if class_to_idx is None: 22 | class_to_idx = dict() 23 | build_class_idx = True 24 | else: 25 | build_class_idx = False 26 | labels = [] 27 | filenames = [] 28 | for root, subdirs, files in os.walk(folder, topdown=False): 29 | rel_path = os.path.relpath(root, folder) if (root != folder) else '' 30 | label = os.path.basename(rel_path) if leaf_name_only else rel_path.replace(os.path.sep, '_') 31 | if build_class_idx and not subdirs: 32 | class_to_idx[label] = None 33 | for f in files: 34 | base, ext = os.path.splitext(f) 35 | if ext.lower() in types: 36 | filenames.append(os.path.join(root, f)) 37 | labels.append(label) 38 | if build_class_idx: 39 | classes = sorted(class_to_idx.keys(), key=natural_key) 40 | for idx, c in enumerate(classes): 41 | class_to_idx[c] = idx 42 | images_and_targets = zip(filenames, [class_to_idx[l] for l in labels]) 43 | if sort: 44 | images_and_targets = sorted(images_and_targets, key=lambda k: natural_key(k[0])) 45 | if build_class_idx: 46 | return images_and_targets, classes, class_to_idx 47 | else: 48 | return images_and_targets 49 | 50 | 51 | class Dataset(data.Dataset): 52 | 53 | def __init__( 54 | self, 55 | root, 56 | transform=None): 57 | 58 | imgs, _, _ = find_images_and_targets(root) 59 | if len(imgs) == 0: 60 | raise(RuntimeError("Found 0 images in subfolders of: " + root + "\n" 61 | "Supported image extensions are: " + ",".join(IMG_EXTENSIONS))) 62 | self.root = root 63 | self.imgs = imgs 64 | self.transform = transform 65 | 66 | def __getitem__(self, index): 67 | path, target = self.imgs[index] 68 | img = Image.open(path).convert('RGB') 69 | if self.transform is not None: 70 | img = self.transform(img) 71 | if target is None: 72 | target = torch.zeros(1).long() 73 | return img, target 74 | 75 | def __len__(self): 76 | return len(self.imgs) 77 | 78 | def set_transform(self, transform): 79 | self.transform = transform 80 | 81 | def filenames(self, indices=[], basename=False): 82 | if indices: 83 | if basename: 84 | return [os.path.basename(self.imgs[i][0]) for i in indices] 85 | else: 86 | return [self.imgs[i][0] for i in indices] 87 | else: 88 | if basename: 89 | return [os.path.basename(x[0]) for x in self.imgs] 90 | else: 91 | return [x[0] for x in self.imgs] 92 | -------------------------------------------------------------------------------- /dpn.py: -------------------------------------------------------------------------------- 1 | """ PyTorch implementation of DualPathNetworks 2 | Based on original MXNet implementation https://github.com/cypw/DPNs with 3 | many ideas from another PyTorch implementation https://github.com/oyam/pytorch-DPNs. 4 | 5 | This implementation is compatible with the pretrained weights 6 | from cypw's MXNet implementation. 7 | """ 8 | from __future__ import absolute_import 9 | from __future__ import division 10 | from __future__ import print_function 11 | 12 | import torch 13 | import torch.nn as nn 14 | import torch.nn.functional as F 15 | try: 16 | from torch.hub import load_state_dict_from_url 17 | except ImportError: 18 | from torch.utils.model_zoo import load_url as load_state_dict_from_url 19 | 20 | from collections import OrderedDict 21 | 22 | from adaptive_avgmax_pool import adaptive_avgmax_pool2d 23 | 24 | 25 | __all__ = ['DPN', 'dpn68', 'dpn68b', 'dpn92', 'dpn98', 'dpn131', 'dpn107'] 26 | 27 | 28 | model_urls = { 29 | 'dpn68': 30 | 'https://github.com/rwightman/pytorch-dpn-pretrained/releases/download/v0.1/dpn68-66bebafa7.pth', 31 | 'dpn68b-extra': 32 | 'https://github.com/rwightman/pytorch-dpn-pretrained/releases/download/v0.1/dpn68b_extra-84854c156.pth', 33 | 'dpn92-extra': 34 | 'https://github.com/rwightman/pytorch-dpn-pretrained/releases/download/v0.1/dpn92_extra-b040e4a9b.pth', 35 | 'dpn98': 36 | 'https://github.com/rwightman/pytorch-dpn-pretrained/releases/download/v0.1/dpn98-5b90dec4d.pth', 37 | 'dpn131': 38 | 'https://github.com/rwightman/pytorch-dpn-pretrained/releases/download/v0.1/dpn131-71dfe43e0.pth', 39 | 'dpn107-extra': 40 | 'https://github.com/rwightman/pytorch-dpn-pretrained/releases/download/v0.1/dpn107_extra-1ac7121e2.pth' 41 | } 42 | 43 | 44 | def dpn68(pretrained=False, test_time_pool=False, **kwargs): 45 | """Constructs a DPN-68 model. 46 | 47 | Args: 48 | pretrained (bool): If True, returns a model pre-trained on ImageNet-1K 49 | test_time_pool (bool): If True, pools features for input resolution beyond 50 | standard 224x224 input with avg+max at inference/validation time 51 | 52 | **kwargs : Keyword args passed to model __init__ 53 | num_classes (int): Number of classes for classifier linear layer, default=1000 54 | """ 55 | model = DPN( 56 | small=True, num_init_features=10, k_r=128, groups=32, 57 | k_sec=(3, 4, 12, 3), inc_sec=(16, 32, 32, 64), 58 | test_time_pool=test_time_pool, **kwargs) 59 | if pretrained: 60 | model.load_state_dict(load_state_dict_from_url(model_urls['dpn68'])) 61 | return model 62 | 63 | 64 | def dpn68b(pretrained=False, test_time_pool=False, **kwargs): 65 | """Constructs a DPN-68b model. 66 | 67 | Args: 68 | pretrained (bool): If True, returns a model pre-trained on ImageNet-1K 69 | test_time_pool (bool): If True, pools features for input resolution beyond 70 | standard 224x224 input with avg+max at inference/validation time 71 | 72 | **kwargs : Keyword args passed to model __init__ 73 | num_classes (int): Number of classes for classifier linear layer, default=1000 74 | """ 75 | model = DPN( 76 | small=True, num_init_features=10, k_r=128, groups=32, 77 | b=True, k_sec=(3, 4, 12, 3), inc_sec=(16, 32, 32, 64), 78 | test_time_pool=test_time_pool, **kwargs) 79 | if pretrained: 80 | model.load_state_dict(load_state_dict_from_url(model_urls['dpn68b-extra'])) 81 | return model 82 | 83 | 84 | def dpn92(pretrained=False, test_time_pool=False, **kwargs): 85 | """Constructs a DPN-92 model. 86 | 87 | Args: 88 | pretrained (bool): If True, returns a model pre-trained on ImageNet-1K 89 | test_time_pool (bool): If True, pools features for input resolution beyond 90 | standard 224x224 input with avg+max at inference/validation time 91 | 92 | **kwargs : Keyword args passed to model __init__ 93 | num_classes (int): Number of classes for classifier linear layer, default=1000 94 | """ 95 | model = DPN( 96 | num_init_features=64, k_r=96, groups=32, 97 | k_sec=(3, 4, 20, 3), inc_sec=(16, 32, 24, 128), 98 | test_time_pool=test_time_pool, **kwargs) 99 | if pretrained: 100 | model.load_state_dict(load_state_dict_from_url(model_urls['dpn92-extra'])) 101 | return model 102 | 103 | 104 | def dpn98(pretrained=False, test_time_pool=False, **kwargs): 105 | """Constructs a DPN-98 model. 106 | 107 | Args: 108 | pretrained (bool): If True, returns a model pre-trained on ImageNet-1K 109 | test_time_pool (bool): If True, pools features for input resolution beyond 110 | standard 224x224 input with avg+max at inference/validation time 111 | 112 | **kwargs : Keyword args passed to model __init__ 113 | num_classes (int): Number of classes for classifier linear layer, default=1000 114 | """ 115 | model = DPN( 116 | num_init_features=96, k_r=160, groups=40, 117 | k_sec=(3, 6, 20, 3), inc_sec=(16, 32, 32, 128), 118 | test_time_pool=test_time_pool, **kwargs) 119 | if pretrained: 120 | model.load_state_dict(load_state_dict_from_url(model_urls['dpn98'])) 121 | return model 122 | 123 | 124 | def dpn131(pretrained=False, test_time_pool=False, **kwargs): 125 | """Constructs a DPN-131 model. 126 | 127 | Args: 128 | pretrained (bool): If True, returns a model pre-trained on ImageNet-1K 129 | test_time_pool (bool): If True, pools features for input resolution beyond 130 | standard 224x224 input with avg+max at inference/validation time 131 | 132 | **kwargs : Keyword args passed to model __init__ 133 | num_classes (int): Number of classes for classifier linear layer, default=1000 134 | """ 135 | model = DPN( 136 | num_init_features=128, k_r=160, groups=40, 137 | k_sec=(4, 8, 28, 3), inc_sec=(16, 32, 32, 128), 138 | test_time_pool=test_time_pool, **kwargs) 139 | if pretrained: 140 | model.load_state_dict(load_state_dict_from_url(model_urls['dpn131'])) 141 | return model 142 | 143 | 144 | def dpn107(pretrained=False, test_time_pool=False, **kwargs): 145 | """Constructs a DPN-107 model. 146 | 147 | Args: 148 | pretrained (bool): If True, returns a model pre-trained on ImageNet-1K 149 | test_time_pool (bool): If True, pools features for input resolution beyond 150 | standard 224x224 input with avg+max at inference/validation time 151 | 152 | **kwargs : Keyword args passed to model __init__ 153 | num_classes (int): Number of classes for classifier linear layer, default=1000 154 | """ 155 | model = DPN( 156 | num_init_features=128, k_r=200, groups=50, 157 | k_sec=(4, 8, 20, 3), inc_sec=(20, 64, 64, 128), 158 | test_time_pool=test_time_pool, **kwargs) 159 | if pretrained: 160 | model.load_state_dict(load_state_dict_from_url(model_urls['dpn107-extra'])) 161 | return model 162 | 163 | 164 | class CatBnAct(nn.Module): 165 | def __init__(self, in_chs, activation_fn=nn.ReLU(inplace=True)): 166 | super(CatBnAct, self).__init__() 167 | self.bn = nn.BatchNorm2d(in_chs, eps=0.001) 168 | self.act = activation_fn 169 | 170 | def forward(self, x): 171 | x = torch.cat(x, dim=1) if isinstance(x, tuple) else x 172 | return self.act(self.bn(x)) 173 | 174 | 175 | class BnActConv2d(nn.Module): 176 | def __init__(self, in_chs, out_chs, kernel_size, stride, 177 | padding=0, groups=1, activation_fn=nn.ReLU(inplace=True)): 178 | super(BnActConv2d, self).__init__() 179 | self.bn = nn.BatchNorm2d(in_chs, eps=0.001) 180 | self.act = activation_fn 181 | self.conv = nn.Conv2d(in_chs, out_chs, kernel_size, stride, padding, groups=groups, bias=False) 182 | 183 | def forward(self, x): 184 | return self.conv(self.act(self.bn(x))) 185 | 186 | 187 | class InputBlock(nn.Module): 188 | def __init__(self, num_init_features, kernel_size=7, 189 | padding=3, activation_fn=nn.ReLU(inplace=True)): 190 | super(InputBlock, self).__init__() 191 | self.conv = nn.Conv2d( 192 | 3, num_init_features, kernel_size=kernel_size, stride=2, padding=padding, bias=False) 193 | self.bn = nn.BatchNorm2d(num_init_features, eps=0.001) 194 | self.act = activation_fn 195 | self.pool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) 196 | 197 | def forward(self, x): 198 | x = self.conv(x) 199 | x = self.bn(x) 200 | x = self.act(x) 201 | x = self.pool(x) 202 | return x 203 | 204 | 205 | class DualPathBlock(nn.Module): 206 | def __init__( 207 | self, in_chs, num_1x1_a, num_3x3_b, num_1x1_c, inc, groups, block_type='normal', b=False): 208 | super(DualPathBlock, self).__init__() 209 | self.num_1x1_c = num_1x1_c 210 | self.inc = inc 211 | self.b = b 212 | if block_type == 'proj': 213 | self.key_stride = 1 214 | self.has_proj = True 215 | elif block_type == 'down': 216 | self.key_stride = 2 217 | self.has_proj = True 218 | else: 219 | assert block_type == 'normal' 220 | self.key_stride = 1 221 | self.has_proj = False 222 | 223 | if self.has_proj: 224 | # Using different member names here to allow easier parameter key matching for conversion 225 | if self.key_stride == 2: 226 | self.c1x1_w_s2 = BnActConv2d( 227 | in_chs=in_chs, out_chs=num_1x1_c + 2 * inc, kernel_size=1, stride=2) 228 | else: 229 | self.c1x1_w_s1 = BnActConv2d( 230 | in_chs=in_chs, out_chs=num_1x1_c + 2 * inc, kernel_size=1, stride=1) 231 | self.c1x1_a = BnActConv2d(in_chs=in_chs, out_chs=num_1x1_a, kernel_size=1, stride=1) 232 | self.c3x3_b = BnActConv2d( 233 | in_chs=num_1x1_a, out_chs=num_3x3_b, kernel_size=3, 234 | stride=self.key_stride, padding=1, groups=groups) 235 | if b: 236 | self.c1x1_c = CatBnAct(in_chs=num_3x3_b) 237 | self.c1x1_c1 = nn.Conv2d(num_3x3_b, num_1x1_c, kernel_size=1, bias=False) 238 | self.c1x1_c2 = nn.Conv2d(num_3x3_b, inc, kernel_size=1, bias=False) 239 | else: 240 | self.c1x1_c = BnActConv2d(in_chs=num_3x3_b, out_chs=num_1x1_c + inc, kernel_size=1, stride=1) 241 | 242 | def forward(self, x): 243 | x_in = torch.cat(x, dim=1) if isinstance(x, tuple) else x 244 | if self.has_proj: 245 | if self.key_stride == 2: 246 | x_s = self.c1x1_w_s2(x_in) 247 | else: 248 | x_s = self.c1x1_w_s1(x_in) 249 | x_s1 = x_s[:, :self.num_1x1_c, :, :] 250 | x_s2 = x_s[:, self.num_1x1_c:, :, :] 251 | else: 252 | x_s1 = x[0] 253 | x_s2 = x[1] 254 | x_in = self.c1x1_a(x_in) 255 | x_in = self.c3x3_b(x_in) 256 | if self.b: 257 | x_in = self.c1x1_c(x_in) 258 | out1 = self.c1x1_c1(x_in) 259 | out2 = self.c1x1_c2(x_in) 260 | else: 261 | x_in = self.c1x1_c(x_in) 262 | out1 = x_in[:, :self.num_1x1_c, :, :] 263 | out2 = x_in[:, self.num_1x1_c:, :, :] 264 | resid = x_s1 + out1 265 | dense = torch.cat([x_s2, out2], dim=1) 266 | return resid, dense 267 | 268 | 269 | class DPN(nn.Module): 270 | def __init__(self, small=False, num_init_features=64, k_r=96, groups=32, 271 | b=False, k_sec=(3, 4, 20, 3), inc_sec=(16, 32, 24, 128), 272 | num_classes=1000, test_time_pool=False): 273 | super(DPN, self).__init__() 274 | self.test_time_pool = test_time_pool 275 | self.b = b 276 | bw_factor = 1 if small else 4 277 | 278 | blocks = OrderedDict() 279 | 280 | # conv1 281 | if small: 282 | blocks['conv1_1'] = InputBlock(num_init_features, kernel_size=3, padding=1) 283 | else: 284 | blocks['conv1_1'] = InputBlock(num_init_features, kernel_size=7, padding=3) 285 | 286 | # conv2 287 | bw = 64 * bw_factor 288 | inc = inc_sec[0] 289 | r = (k_r * bw) // (64 * bw_factor) 290 | blocks['conv2_1'] = DualPathBlock(num_init_features, r, r, bw, inc, groups, 'proj', b) 291 | in_chs = bw + 3 * inc 292 | for i in range(2, k_sec[0] + 1): 293 | blocks['conv2_' + str(i)] = DualPathBlock(in_chs, r, r, bw, inc, groups, 'normal', b) 294 | in_chs += inc 295 | 296 | # conv3 297 | bw = 128 * bw_factor 298 | inc = inc_sec[1] 299 | r = (k_r * bw) // (64 * bw_factor) 300 | blocks['conv3_1'] = DualPathBlock(in_chs, r, r, bw, inc, groups, 'down', b) 301 | in_chs = bw + 3 * inc 302 | for i in range(2, k_sec[1] + 1): 303 | blocks['conv3_' + str(i)] = DualPathBlock(in_chs, r, r, bw, inc, groups, 'normal', b) 304 | in_chs += inc 305 | 306 | # conv4 307 | bw = 256 * bw_factor 308 | inc = inc_sec[2] 309 | r = (k_r * bw) // (64 * bw_factor) 310 | blocks['conv4_1'] = DualPathBlock(in_chs, r, r, bw, inc, groups, 'down', b) 311 | in_chs = bw + 3 * inc 312 | for i in range(2, k_sec[2] + 1): 313 | blocks['conv4_' + str(i)] = DualPathBlock(in_chs, r, r, bw, inc, groups, 'normal', b) 314 | in_chs += inc 315 | 316 | # conv5 317 | bw = 512 * bw_factor 318 | inc = inc_sec[3] 319 | r = (k_r * bw) // (64 * bw_factor) 320 | blocks['conv5_1'] = DualPathBlock(in_chs, r, r, bw, inc, groups, 'down', b) 321 | in_chs = bw + 3 * inc 322 | for i in range(2, k_sec[3] + 1): 323 | blocks['conv5_' + str(i)] = DualPathBlock(in_chs, r, r, bw, inc, groups, 'normal', b) 324 | in_chs += inc 325 | blocks['conv5_bn_ac'] = CatBnAct(in_chs) 326 | 327 | self.features = nn.Sequential(blocks) 328 | 329 | # Using 1x1 conv for the FC layer to allow the extra pooling scheme 330 | self.classifier = nn.Conv2d(in_chs, num_classes, kernel_size=1, bias=True) 331 | 332 | def forward(self, x): 333 | x = self.features(x) 334 | if not self.training and self.test_time_pool: 335 | x = F.avg_pool2d(x, kernel_size=7, stride=1) 336 | out = self.classifier(x) 337 | # The extra test time pool should be pooling an img_size//32 - 6 size patch 338 | out = adaptive_avgmax_pool2d(out, pool_type='avgmax') 339 | else: 340 | x = adaptive_avgmax_pool2d(x, pool_type='avg') 341 | out = self.classifier(x) 342 | return out.view(out.size(0), -1) 343 | -------------------------------------------------------------------------------- /hubconf.py: -------------------------------------------------------------------------------- 1 | """ PyTorch DPN hubconf.py 2 | 3 | ## Users can get this published model by calling: 4 | hub_model = hub.load( 5 | 'rwightman/pytorch-dpn-pretrained:master', # repo_owner/repo_name:branch 6 | 'dpn92', # entrypoint 7 | pretrained=True) # kwargs for callable 8 | """ 9 | dependencies = ['torch', 'math'] 10 | 11 | from dpn import dpn68, dpn68b, dpn92, dpn98, dpn131, dpn107 12 | -------------------------------------------------------------------------------- /inference.py: -------------------------------------------------------------------------------- 1 | """Sample PyTorch Inference script 2 | """ 3 | 4 | from __future__ import absolute_import 5 | from __future__ import division 6 | from __future__ import print_function 7 | 8 | import os 9 | import time 10 | import argparse 11 | import numpy as np 12 | import torch 13 | import torch.autograd as autograd 14 | import torch.utils.data as data 15 | 16 | import model_factory 17 | from dataset import Dataset 18 | 19 | 20 | parser = argparse.ArgumentParser(description='PyTorch ImageNet Inference') 21 | parser.add_argument('data', metavar='DIR', 22 | help='path to dataset') 23 | parser.add_argument('--output_dir', metavar='DIR', default='./', 24 | help='path to output files') 25 | parser.add_argument('--model', '-m', metavar='MODEL', default='dpn92', 26 | help='model architecture (default: dpn92)') 27 | parser.add_argument('-j', '--workers', default=2, type=int, metavar='N', 28 | help='number of data loading workers (default: 2)') 29 | parser.add_argument('-b', '--batch-size', default=256, type=int, 30 | metavar='N', help='mini-batch size (default: 256)') 31 | parser.add_argument('--img-size', default=224, type=int, 32 | metavar='N', help='Input image dimension') 33 | parser.add_argument('--print-freq', '-p', default=10, type=int, 34 | metavar='N', help='print frequency (default: 10)') 35 | parser.add_argument('--restore-checkpoint', default='', type=str, metavar='PATH', 36 | help='path to latest checkpoint (default: none)') 37 | parser.add_argument('--pretrained', dest='pretrained', action='store_true', 38 | help='use pre-trained model') 39 | parser.add_argument('--multi-gpu', dest='multi_gpu', action='store_true', 40 | help='use multiple-gpus') 41 | parser.add_argument('--no-test-pool', dest='test_time_pool', action='store_false', 42 | help='use pre-trained model') 43 | 44 | 45 | def main(): 46 | args = parser.parse_args() 47 | 48 | # create model 49 | num_classes = 1000 50 | model = model_factory.create_model( 51 | args.model, 52 | num_classes=num_classes, 53 | pretrained=args.pretrained, 54 | test_time_pool=args.test_time_pool) 55 | 56 | # resume from a checkpoint 57 | if args.restore_checkpoint and os.path.isfile(args.restore_checkpoint): 58 | print("=> loading checkpoint '{}'".format(args.restore_checkpoint)) 59 | checkpoint = torch.load(args.restore_checkpoint) 60 | if isinstance(checkpoint, dict) and 'state_dict' in checkpoint: 61 | model.load_state_dict(checkpoint['state_dict']) 62 | else: 63 | model.load_state_dict(checkpoint) 64 | print("=> loaded checkpoint '{}'".format(args.restore_checkpoint)) 65 | elif not args.pretrained: 66 | print("=> no checkpoint found at '{}'".format(args.restore_checkpoint)) 67 | exit(1) 68 | 69 | if args.multi_gpu: 70 | model = torch.nn.DataParallel(model).cuda() 71 | else: 72 | model = model.cuda() 73 | 74 | transforms = model_factory.get_transforms_eval( 75 | args.model, 76 | args.img_size) 77 | 78 | dataset = Dataset( 79 | args.data, 80 | transforms) 81 | 82 | loader = data.DataLoader( 83 | dataset, 84 | batch_size=args.batch_size, shuffle=False, 85 | num_workers=args.workers, pin_memory=True) 86 | 87 | model.eval() 88 | 89 | batch_time = AverageMeter() 90 | end = time.time() 91 | top5_ids = [] 92 | with torch.no_grad(): 93 | for batch_idx, (input, _) in enumerate(loader): 94 | input = input.cuda() 95 | labels = model(input) 96 | top5 = labels.topk(5)[1] 97 | top5_ids.append(top5.cpu().numpy()) 98 | 99 | # measure elapsed time 100 | batch_time.update(time.time() - end) 101 | end = time.time() 102 | 103 | if batch_idx % args.print_freq == 0: 104 | print('Predict: [{0}/{1}]\t' 105 | 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})'.format( 106 | batch_idx, len(loader), batch_time=batch_time)) 107 | 108 | top5_ids = np.concatenate(top5_ids, axis=0).squeeze() 109 | 110 | with open(os.path.join(args.output_dir, './top5_ids.csv'), 'w') as out_file: 111 | filenames = dataset.filenames() 112 | for filename, label in zip(filenames, top5_ids): 113 | filename = os.path.basename(filename) 114 | out_file.write('{0},{1},{2},{3},{4},{5}\n'.format( 115 | filename, label[0], label[1], label[2], label[3], label[4])) 116 | 117 | 118 | class AverageMeter(object): 119 | """Computes and stores the average and current value""" 120 | 121 | def __init__(self): 122 | self.reset() 123 | 124 | def reset(self): 125 | self.val = 0 126 | self.avg = 0 127 | self.sum = 0 128 | self.count = 0 129 | 130 | def update(self, val, n=1): 131 | self.val = val 132 | self.sum += val * n 133 | self.count += n 134 | self.avg = self.sum / self.count 135 | 136 | 137 | if __name__ == '__main__': 138 | main() 139 | -------------------------------------------------------------------------------- /model_factory.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from __future__ import division 3 | from __future__ import print_function 4 | 5 | import math 6 | from dpn import dpn68, dpn68b, dpn92, dpn98, dpn131, dpn107 7 | from torchvision.models.resnet import resnet18, resnet34, resnet50, resnet101, resnet152 8 | from torchvision.models.densenet import densenet121, densenet169, densenet161, densenet201 9 | from torchvision.models.inception import inception_v3 10 | import torchvision.transforms as transforms 11 | from PIL import Image 12 | 13 | 14 | def create_model(model_name, num_classes=1000, pretrained=False, **kwargs): 15 | if 'test_time_pool' in kwargs: 16 | test_time_pool = kwargs.pop('test_time_pool') 17 | else: 18 | test_time_pool = True 19 | if model_name == 'dpn68': 20 | model = dpn68( 21 | pretrained=pretrained, test_time_pool=test_time_pool, num_classes=num_classes) 22 | elif model_name == 'dpn68b': 23 | model = dpn68b( 24 | pretrained=pretrained, test_time_pool=test_time_pool, num_classes=num_classes) 25 | elif model_name == 'dpn92': 26 | model = dpn92( 27 | pretrained=pretrained, test_time_pool=test_time_pool, num_classes=num_classes) 28 | elif model_name == 'dpn98': 29 | model = dpn98( 30 | pretrained=pretrained, test_time_pool=test_time_pool, num_classes=num_classes) 31 | elif model_name == 'dpn131': 32 | model = dpn131( 33 | pretrained=pretrained, test_time_pool=test_time_pool, num_classes=num_classes) 34 | elif model_name == 'dpn107': 35 | model = dpn107( 36 | pretrained=pretrained, test_time_pool=test_time_pool, num_classes=num_classes) 37 | elif model_name == 'resnet18': 38 | model = resnet18(pretrained=pretrained, num_classes=num_classes, **kwargs) 39 | elif model_name == 'resnet34': 40 | model = resnet34(pretrained=pretrained, num_classes=num_classes, **kwargs) 41 | elif model_name == 'resnet50': 42 | model = resnet50(pretrained=pretrained, num_classes=num_classes, **kwargs) 43 | elif model_name == 'resnet101': 44 | model = resnet101(pretrained=pretrained, num_classes=num_classes, **kwargs) 45 | elif model_name == 'resnet152': 46 | model = resnet152(pretrained=pretrained, num_classes=num_classes, **kwargs) 47 | elif model_name == 'densenet121': 48 | model = densenet121(pretrained=pretrained, num_classes=num_classes, **kwargs) 49 | elif model_name == 'densenet161': 50 | model = densenet161(pretrained=pretrained, num_classes=num_classes, **kwargs) 51 | elif model_name == 'densenet169': 52 | model = densenet169(pretrained=pretrained, num_classes=num_classes, **kwargs) 53 | elif model_name == 'densenet201': 54 | model = densenet201(pretrained=pretrained, num_classes=num_classes, **kwargs) 55 | elif model_name == 'inception_v3': 56 | model = inception_v3( 57 | pretrained=pretrained, num_classes=num_classes, transform_input=False, **kwargs) 58 | else: 59 | assert False, "Unknown model architecture (%s)" % model_name 60 | return model 61 | 62 | 63 | class LeNormalize(object): 64 | """Normalize to -1..1 in Google Inception style 65 | """ 66 | def __call__(self, tensor): 67 | for t in tensor: 68 | t.sub_(0.5).mul_(2.0) 69 | return tensor 70 | 71 | 72 | DEFAULT_CROP_PCT = 0.875 73 | 74 | 75 | def get_transforms_eval(model_name, img_size=224, crop_pct=None): 76 | crop_pct = crop_pct or DEFAULT_CROP_PCT 77 | if 'dpn' in model_name: 78 | if crop_pct is None: 79 | # Use default 87.5% crop for model's native img_size 80 | # but use 100% crop for larger than native as it 81 | # improves test time results across all models. 82 | if img_size == 224: 83 | scale_size = int(math.floor(img_size / DEFAULT_CROP_PCT)) 84 | else: 85 | scale_size = img_size 86 | else: 87 | scale_size = int(math.floor(img_size / crop_pct)) 88 | normalize = transforms.Normalize( 89 | mean=[124 / 255, 117 / 255, 104 / 255], 90 | std=[1 / (.0167 * 255)] * 3) 91 | elif 'inception' in model_name: 92 | scale_size = int(math.floor(img_size / crop_pct)) 93 | normalize = LeNormalize() 94 | else: 95 | scale_size = int(math.floor(img_size / crop_pct)) 96 | normalize = transforms.Normalize( 97 | mean=[0.485, 0.456, 0.406], 98 | std=[0.229, 0.224, 0.225]) 99 | 100 | return transforms.Compose([ 101 | transforms.Resize(scale_size, Image.BICUBIC), 102 | transforms.CenterCrop(img_size), 103 | transforms.ToTensor(), 104 | normalize]) 105 | -------------------------------------------------------------------------------- /validate.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from __future__ import division 3 | from __future__ import print_function 4 | 5 | import argparse 6 | import os 7 | import time 8 | import torch 9 | import torch.backends.cudnn as cudnn 10 | import torch.nn as nn 11 | import torch.nn.parallel 12 | import torch.utils.data as data 13 | 14 | 15 | import model_factory 16 | from dataset import Dataset 17 | 18 | 19 | parser = argparse.ArgumentParser(description='PyTorch ImageNet Validation') 20 | parser.add_argument('data', metavar='DIR', 21 | help='path to dataset') 22 | parser.add_argument('--model', '-m', metavar='MODEL', default='dpn92', 23 | help='model architecture (default: dpn92)') 24 | parser.add_argument('-j', '--workers', default=2, type=int, metavar='N', 25 | help='number of data loading workers (default: 2)') 26 | parser.add_argument('-b', '--batch-size', default=256, type=int, 27 | metavar='N', help='mini-batch size (default: 256)') 28 | parser.add_argument('--img-size', default=224, type=int, 29 | metavar='N', help='Input image dimension') 30 | parser.add_argument('--print-freq', '-p', default=10, type=int, 31 | metavar='N', help='print frequency (default: 10)') 32 | parser.add_argument('--checkpoint', default='', type=str, metavar='PATH', 33 | help='path to latest checkpoint (default: none)') 34 | parser.add_argument('--pretrained', dest='pretrained', action='store_true', 35 | help='use pre-trained model') 36 | parser.add_argument('--multi-gpu', dest='multi_gpu', action='store_true', 37 | help='use multiple-gpus') 38 | parser.add_argument('--no-test-pool', dest='no_test_pool', action='store_true', 39 | help='disable test time pool for DPN models') 40 | 41 | 42 | def main(): 43 | args = parser.parse_args() 44 | 45 | test_time_pool = False 46 | if 'dpn' in args.model and args.img_size > 224 and not args.no_test_pool: 47 | test_time_pool = True 48 | 49 | if not args.checkpoint and not args.pretrained: 50 | args.pretrained = True # might as well do something... 51 | 52 | # create model 53 | num_classes = 1000 54 | model = model_factory.create_model( 55 | args.model, 56 | num_classes=num_classes, 57 | pretrained=args.pretrained, 58 | test_time_pool=test_time_pool) 59 | 60 | print('Model %s created, param count: %d' % 61 | (args.model, sum([m.numel() for m in model.parameters()]))) 62 | 63 | # optionally resume from a checkpoint 64 | if args.checkpoint and os.path.isfile(args.checkpoint): 65 | print("=> loading checkpoint '{}'".format(args.checkpoint)) 66 | checkpoint = torch.load(args.checkpoint) 67 | if isinstance(checkpoint, dict) and 'state_dict' in checkpoint: 68 | model.load_state_dict(checkpoint['state_dict']) 69 | else: 70 | model.load_state_dict(checkpoint) 71 | print("=> loaded checkpoint '{}'".format(args.checkpoint)) 72 | elif args.checkpoint: 73 | print("=> no checkpoint found at '{}'".format(args.checkpoint)) 74 | exit(1) 75 | 76 | if args.multi_gpu: 77 | model = torch.nn.DataParallel(model).cuda() 78 | else: 79 | model = model.cuda() 80 | 81 | # define loss function (criterion) and optimizer 82 | criterion = nn.CrossEntropyLoss().cuda() 83 | 84 | cudnn.benchmark = True 85 | 86 | transforms = model_factory.get_transforms_eval( 87 | args.model, 88 | args.img_size) 89 | 90 | dataset = Dataset( 91 | args.data, 92 | transforms) 93 | 94 | loader = data.DataLoader( 95 | dataset, 96 | batch_size=args.batch_size, shuffle=False, num_workers=args.workers) 97 | 98 | batch_time = AverageMeter() 99 | losses = AverageMeter() 100 | top1 = AverageMeter() 101 | top5 = AverageMeter() 102 | 103 | # switch to evaluate mode 104 | model.eval() 105 | end = time.time() 106 | with torch.no_grad(): 107 | for i, (input, target) in enumerate(loader): 108 | target = target.cuda() 109 | input = input.cuda() 110 | 111 | # compute output 112 | output = model(input) 113 | loss = criterion(output, target) 114 | 115 | # measure accuracy and record loss 116 | prec1, prec5 = accuracy(output.data, target, topk=(1, 5)) 117 | losses.update(loss.item(), input.size(0)) 118 | top1.update(prec1.item(), input.size(0)) 119 | top5.update(prec5.item(), input.size(0)) 120 | 121 | # measure elapsed time 122 | batch_time.update(time.time() - end) 123 | end = time.time() 124 | 125 | if i % args.print_freq == 0: 126 | print('Test: [{0}/{1}]\t' 127 | 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 128 | 'Loss {loss.val:.4f} ({loss.avg:.4f})\t' 129 | 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t' 130 | 'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format( 131 | i, len(loader), batch_time=batch_time, loss=losses, 132 | top1=top1, top5=top5)) 133 | 134 | print(' * Prec@1 {top1.avg:.3f} ({top1a:.3f}) Prec@5 {top5.avg:.3f} ({top5a:.3f})'.format( 135 | top1=top1, top1a=100-top1.avg, top5=top5, top5a=100.-top5.avg)) 136 | 137 | 138 | class AverageMeter(object): 139 | """Computes and stores the average and current value""" 140 | 141 | def __init__(self): 142 | self.reset() 143 | 144 | def reset(self): 145 | self.val = 0 146 | self.avg = 0 147 | self.sum = 0 148 | self.count = 0 149 | 150 | def update(self, val, n=1): 151 | self.val = val 152 | self.sum += val * n 153 | self.count += n 154 | self.avg = self.sum / self.count 155 | 156 | 157 | def accuracy(output, target, topk=(1,)): 158 | """Computes the precision@k for the specified values of k""" 159 | maxk = max(topk) 160 | batch_size = target.size(0) 161 | 162 | _, pred = output.topk(maxk, 1, True, True) 163 | pred = pred.t() 164 | correct = pred.eq(target.view(1, -1).expand_as(pred)) 165 | 166 | res = [] 167 | for k in topk: 168 | correct_k = correct[:k].view(-1).float().sum(0) 169 | res.append(correct_k.mul_(100.0 / batch_size)) 170 | return res 171 | 172 | 173 | if __name__ == '__main__': 174 | main() 175 | --------------------------------------------------------------------------------