Search is not available for this dataset
repo stringlengths 2 152 ⌀ | file stringlengths 15 239 | code stringlengths 0 58.4M | file_length int64 0 58.4M | avg_line_length float64 0 1.81M | max_line_length int64 0 12.7M | extension_type stringclasses 364 values |
|---|---|---|---|---|---|---|
null | qimera-main/other_train_scripts/run_imgnet_resnet18_5bit.sh | #!/bin/bash
python main.py --conf_path ./imagenet_resnet18.hocon --multi_label_prob 0.4 --multi_label_num 100 --id 01 --randemb --qw 5 --qa 5 | 143 | 47 | 130 | sh |
null | qimera-main/other_train_scripts/run_imgnet_resnet50_5bit.sh | #!/bin/bash
python main.py --conf_path ./imagenet_resnet50.hocon --multi_label_prob 0.7 --multi_label_num 100 --id 01 --qw 5 --qa 5 | 133 | 43.666667 | 120 | sh |
null | qimera-main/pytorchcv/__init__.py | 0 | 0 | 0 | py | |
null | qimera-main/pytorchcv/model_provider.py | from .models.alexnet import *
from .models.zfnet import *
from .models.vgg import *
from .models.bninception import *
from .models.resnet import *
from .models.preresnet import *
from .models.resnext import *
from .models.seresnet import *
from .models.sepreresnet import *
from .models.seresnext import *
from .models.senet import *
from .models.ibnresnet import *
from .models.ibnbresnet import *
from .models.ibnresnext import *
from .models.ibndensenet import *
from .models.airnet import *
from .models.airnext import *
from .models.bamresnet import *
from .models.cbamresnet import *
from .models.resattnet import *
from .models.sknet import *
from .models.diaresnet import *
from .models.diapreresnet import *
from .models.pyramidnet import *
from .models.diracnetv2 import *
from .models.sharesnet import *
from .models.densenet import *
from .models.condensenet import *
from .models.sparsenet import *
from .models.peleenet import *
from .models.wrn import *
from .models.drn import *
from .models.dpn import *
from .models.darknet import *
from .models.darknet53 import *
from .models.channelnet import *
from .models.isqrtcovresnet import *
from .models.revnet import *
from .models.irevnet import *
from .models.bagnet import *
from .models.dla import *
from .models.msdnet import *
from .models.fishnet import *
from .models.espnetv2 import *
from .models.xdensenet import *
from .models.squeezenet import *
from .models.squeezenext import *
from .models.shufflenet import *
from .models.shufflenetv2 import *
from .models.shufflenetv2b import *
from .models.menet import *
from .models.mobilenet import *
from .models.mobilenetv2 import *
from .models.mobilenetv3 import *
from .models.igcv3 import *
from .models.mnasnet import *
from .models.darts import *
from .models.proxylessnas import *
from .models.fbnet import *
from .models.xception import *
from .models.inceptionv3 import *
from .models.inceptionv4 import *
from .models.inceptionresnetv2 import *
from .models.polynet import *
from .models.nasnet import *
from .models.pnasnet import *
from .models.spnasnet import *
from .models.efficientnet import *
from .models.mixnet import *
from .models.nin_cifar import *
from .models.resnet_cifar import *
from .models.preresnet_cifar import *
from .models.resnext_cifar import *
from .models.seresnet_cifar import *
from .models.sepreresnet_cifar import *
from .models.pyramidnet_cifar import *
from .models.densenet_cifar import *
from .models.xdensenet_cifar import *
from .models.wrn_cifar import *
from .models.wrn1bit_cifar import *
from .models.ror_cifar import *
from .models.rir_cifar import *
from .models.msdnet_cifar10 import *
from .models.resdropresnet_cifar import *
from .models.shakeshakeresnet_cifar import *
from .models.shakedropresnet_cifar import *
from .models.fractalnet_cifar import *
from .models.diaresnet_cifar import *
from .models.diapreresnet_cifar import *
from .models.octresnet import *
from .models.resnetd import *
from .models.resnet_cub import *
from .models.seresnet_cub import *
from .models.mobilenet_cub import *
from .models.proxylessnas_cub import *
from .models.ntsnet_cub import *
from .models.fcn8sd import *
from .models.pspnet import *
from .models.deeplabv3 import *
from .models.superpointnet import *
# from .models.others.oth_gen_efficientnet import *
__all__ = ['get_model', 'trained_model_metainfo_list']
_models = {
'alexnet': alexnet,
'alexnetb': alexnetb,
'zfnet': zfnet,
'zfnetb': zfnetb,
'vgg11': vgg11,
'vgg13': vgg13,
'vgg16': vgg16,
'vgg19': vgg19,
'bn_vgg11': bn_vgg11,
'bn_vgg13': bn_vgg13,
'bn_vgg16': bn_vgg16,
'bn_vgg19': bn_vgg19,
'bn_vgg11b': bn_vgg11b,
'bn_vgg13b': bn_vgg13b,
'bn_vgg16b': bn_vgg16b,
'bn_vgg19b': bn_vgg19b,
'bninception': bninception,
'resnet10': resnet10,
'resnet12': resnet12,
'resnet14': resnet14,
'resnetbc14b': resnetbc14b,
'resnet16': resnet16,
'resnet18_wd4': resnet18_wd4,
'resnet18_wd2': resnet18_wd2,
'resnet18_w3d4': resnet18_w3d4,
'resnet18': resnet18,
'resnet26': resnet26,
'resnetbc26b': resnetbc26b,
'resnet34': resnet34,
'resnetbc38b': resnetbc38b,
'resnet50': resnet50,
'resnet50b': resnet50b,
'resnet101': resnet101,
'resnet101b': resnet101b,
'resnet152': resnet152,
'resnet152b': resnet152b,
'resnet200': resnet200,
'resnet200b': resnet200b,
'preresnet10': preresnet10,
'preresnet12': preresnet12,
'preresnet14': preresnet14,
'preresnetbc14b': preresnetbc14b,
'preresnet16': preresnet16,
'preresnet18_wd4': preresnet18_wd4,
'preresnet18_wd2': preresnet18_wd2,
'preresnet18_w3d4': preresnet18_w3d4,
'preresnet18': preresnet18,
'preresnet26': preresnet26,
'preresnetbc26b': preresnetbc26b,
'preresnet34': preresnet34,
'preresnetbc38b': preresnetbc38b,
'preresnet50': preresnet50,
'preresnet50b': preresnet50b,
'preresnet101': preresnet101,
'preresnet101b': preresnet101b,
'preresnet152': preresnet152,
'preresnet152b': preresnet152b,
'preresnet200': preresnet200,
'preresnet200b': preresnet200b,
'preresnet269b': preresnet269b,
'resnext14_16x4d': resnext14_16x4d,
'resnext14_32x2d': resnext14_32x2d,
'resnext14_32x4d': resnext14_32x4d,
'resnext26_16x4d': resnext26_16x4d,
'resnext26_32x2d': resnext26_32x2d,
'resnext26_32x4d': resnext26_32x4d,
'resnext38_32x4d': resnext38_32x4d,
'resnext50_32x4d': resnext50_32x4d,
'resnext101_32x4d': resnext101_32x4d,
'resnext101_64x4d': resnext101_64x4d,
'seresnet10': seresnet10,
'seresnet12': seresnet12,
'seresnet14': seresnet14,
'seresnet16': seresnet16,
'seresnet18': seresnet18,
'seresnet26': seresnet26,
'seresnetbc26b': seresnetbc26b,
'seresnet34': seresnet34,
'seresnetbc38b': seresnetbc38b,
'seresnet50': seresnet50,
'seresnet50b': seresnet50b,
'seresnet101': seresnet101,
'seresnet101b': seresnet101b,
'seresnet152': seresnet152,
'seresnet152b': seresnet152b,
'seresnet200': seresnet200,
'seresnet200b': seresnet200b,
'sepreresnet10': sepreresnet10,
'sepreresnet12': sepreresnet12,
'sepreresnet14': sepreresnet14,
'sepreresnet16': sepreresnet16,
'sepreresnet18': sepreresnet18,
'sepreresnet26': sepreresnet26,
'sepreresnetbc26b': sepreresnetbc26b,
'sepreresnet34': sepreresnet34,
'sepreresnetbc38b': sepreresnetbc38b,
'sepreresnet50': sepreresnet50,
'sepreresnet50b': sepreresnet50b,
'sepreresnet101': sepreresnet101,
'sepreresnet101b': sepreresnet101b,
'sepreresnet152': sepreresnet152,
'sepreresnet152b': sepreresnet152b,
'sepreresnet200': sepreresnet200,
'sepreresnet200b': sepreresnet200b,
'seresnext50_32x4d': seresnext50_32x4d,
'seresnext101_32x4d': seresnext101_32x4d,
'seresnext101_64x4d': seresnext101_64x4d,
'senet16': senet16,
'senet28': senet28,
'senet40': senet40,
'senet52': senet52,
'senet103': senet103,
'senet154': senet154,
'ibn_resnet50': ibn_resnet50,
'ibn_resnet101': ibn_resnet101,
'ibn_resnet152': ibn_resnet152,
'ibnb_resnet50': ibnb_resnet50,
'ibnb_resnet101': ibnb_resnet101,
'ibnb_resnet152': ibnb_resnet152,
'ibn_resnext50_32x4d': ibn_resnext50_32x4d,
'ibn_resnext101_32x4d': ibn_resnext101_32x4d,
'ibn_resnext101_64x4d': ibn_resnext101_64x4d,
'ibn_densenet121': ibn_densenet121,
'ibn_densenet161': ibn_densenet161,
'ibn_densenet169': ibn_densenet169,
'ibn_densenet201': ibn_densenet201,
'airnet50_1x64d_r2': airnet50_1x64d_r2,
'airnet50_1x64d_r16': airnet50_1x64d_r16,
'airnet101_1x64d_r2': airnet101_1x64d_r2,
'airnext50_32x4d_r2': airnext50_32x4d_r2,
'airnext101_32x4d_r2': airnext101_32x4d_r2,
'airnext101_32x4d_r16': airnext101_32x4d_r16,
'bam_resnet18': bam_resnet18,
'bam_resnet34': bam_resnet34,
'bam_resnet50': bam_resnet50,
'bam_resnet101': bam_resnet101,
'bam_resnet152': bam_resnet152,
'cbam_resnet18': cbam_resnet18,
'cbam_resnet34': cbam_resnet34,
'cbam_resnet50': cbam_resnet50,
'cbam_resnet101': cbam_resnet101,
'cbam_resnet152': cbam_resnet152,
'resattnet56': resattnet56,
'resattnet92': resattnet92,
'resattnet128': resattnet128,
'resattnet164': resattnet164,
'resattnet200': resattnet200,
'resattnet236': resattnet236,
'resattnet452': resattnet452,
'sknet50': sknet50,
'sknet101': sknet101,
'sknet152': sknet152,
'diaresnet10': diaresnet10,
'diaresnet12': diaresnet12,
'diaresnet14': diaresnet14,
'diaresnetbc14b': diaresnetbc14b,
'diaresnet16': diaresnet16,
'diaresnet18': diaresnet18,
'diaresnet26': diaresnet26,
'diaresnetbc26b': diaresnetbc26b,
'diaresnet34': diaresnet34,
'diaresnetbc38b': diaresnetbc38b,
'diaresnet50': diaresnet50,
'diaresnet50b': diaresnet50b,
'diaresnet101': diaresnet101,
'diaresnet101b': diaresnet101b,
'diaresnet152': diaresnet152,
'diaresnet152b': diaresnet152b,
'diaresnet200': diaresnet200,
'diaresnet200b': diaresnet200b,
'diapreresnet10': diapreresnet10,
'diapreresnet12': diapreresnet12,
'diapreresnet14': diapreresnet14,
'diapreresnetbc14b': diapreresnetbc14b,
'diapreresnet16': diapreresnet16,
'diapreresnet18': diapreresnet18,
'diapreresnet26': diapreresnet26,
'diapreresnetbc26b': diapreresnetbc26b,
'diapreresnet34': diapreresnet34,
'diapreresnetbc38b': diapreresnetbc38b,
'diapreresnet50': diapreresnet50,
'diapreresnet50b': diapreresnet50b,
'diapreresnet101': diapreresnet101,
'diapreresnet101b': diapreresnet101b,
'diapreresnet152': diapreresnet152,
'diapreresnet152b': diapreresnet152b,
'diapreresnet200': diapreresnet200,
'diapreresnet200b': diapreresnet200b,
'diapreresnet269b': diapreresnet269b,
'pyramidnet101_a360': pyramidnet101_a360,
'diracnet18v2': diracnet18v2,
'diracnet34v2': diracnet34v2,
'sharesnet18': sharesnet18,
'sharesnet34': sharesnet34,
'sharesnet50': sharesnet50,
'sharesnet50b': sharesnet50b,
'sharesnet101': sharesnet101,
'sharesnet101b': sharesnet101b,
'sharesnet152': sharesnet152,
'sharesnet152b': sharesnet152b,
'densenet121': densenet121,
'densenet161': densenet161,
'densenet169': densenet169,
'densenet201': densenet201,
'condensenet74_c4_g4': condensenet74_c4_g4,
'condensenet74_c8_g8': condensenet74_c8_g8,
'sparsenet121': sparsenet121,
'sparsenet161': sparsenet161,
'sparsenet169': sparsenet169,
'sparsenet201': sparsenet201,
'sparsenet264': sparsenet264,
'peleenet': peleenet,
'wrn50_2': wrn50_2,
'drnc26': drnc26,
'drnc42': drnc42,
'drnc58': drnc58,
'drnd22': drnd22,
'drnd38': drnd38,
'drnd54': drnd54,
'drnd105': drnd105,
'dpn68': dpn68,
'dpn68b': dpn68b,
'dpn98': dpn98,
'dpn107': dpn107,
'dpn131': dpn131,
'darknet_ref': darknet_ref,
'darknet_tiny': darknet_tiny,
'darknet19': darknet19,
'darknet53': darknet53,
'channelnet': channelnet,
'revnet38': revnet38,
'revnet110': revnet110,
'revnet164': revnet164,
'irevnet301': irevnet301,
'bagnet9': bagnet9,
'bagnet17': bagnet17,
'bagnet33': bagnet33,
'dla34': dla34,
'dla46c': dla46c,
'dla46xc': dla46xc,
'dla60': dla60,
'dla60x': dla60x,
'dla60xc': dla60xc,
'dla102': dla102,
'dla102x': dla102x,
'dla102x2': dla102x2,
'dla169': dla169,
'msdnet22': msdnet22,
'fishnet99': fishnet99,
'fishnet150': fishnet150,
'espnetv2_wd2': espnetv2_wd2,
'espnetv2_w1': espnetv2_w1,
'espnetv2_w5d4': espnetv2_w5d4,
'espnetv2_w3d2': espnetv2_w3d2,
'espnetv2_w2': espnetv2_w2,
'xdensenet121_2': xdensenet121_2,
'xdensenet161_2': xdensenet161_2,
'xdensenet169_2': xdensenet169_2,
'xdensenet201_2': xdensenet201_2,
'squeezenet_v1_0': squeezenet_v1_0,
'squeezenet_v1_1': squeezenet_v1_1,
'squeezeresnet_v1_0': squeezeresnet_v1_0,
'squeezeresnet_v1_1': squeezeresnet_v1_1,
'sqnxt23_w1': sqnxt23_w1,
'sqnxt23_w3d2': sqnxt23_w3d2,
'sqnxt23_w2': sqnxt23_w2,
'sqnxt23v5_w1': sqnxt23v5_w1,
'sqnxt23v5_w3d2': sqnxt23v5_w3d2,
'sqnxt23v5_w2': sqnxt23v5_w2,
'shufflenet_g1_w1': shufflenet_g1_w1,
'shufflenet_g2_w1': shufflenet_g2_w1,
'shufflenet_g3_w1': shufflenet_g3_w1,
'shufflenet_g4_w1': shufflenet_g4_w1,
'shufflenet_g8_w1': shufflenet_g8_w1,
'shufflenet_g1_w3d4': shufflenet_g1_w3d4,
'shufflenet_g3_w3d4': shufflenet_g3_w3d4,
'shufflenet_g1_wd2': shufflenet_g1_wd2,
'shufflenet_g3_wd2': shufflenet_g3_wd2,
'shufflenet_g1_wd4': shufflenet_g1_wd4,
'shufflenet_g3_wd4': shufflenet_g3_wd4,
'shufflenetv2_wd2': shufflenetv2_wd2,
'shufflenetv2_w1': shufflenetv2_w1,
'shufflenetv2_w3d2': shufflenetv2_w3d2,
'shufflenetv2_w2': shufflenetv2_w2,
'shufflenetv2b_wd2': shufflenetv2b_wd2,
'shufflenetv2b_w1': shufflenetv2b_w1,
'shufflenetv2b_w3d2': shufflenetv2b_w3d2,
'shufflenetv2b_w2': shufflenetv2b_w2,
'menet108_8x1_g3': menet108_8x1_g3,
'menet128_8x1_g4': menet128_8x1_g4,
'menet160_8x1_g8': menet160_8x1_g8,
'menet228_12x1_g3': menet228_12x1_g3,
'menet256_12x1_g4': menet256_12x1_g4,
'menet348_12x1_g3': menet348_12x1_g3,
'menet352_12x1_g8': menet352_12x1_g8,
'menet456_24x1_g3': menet456_24x1_g3,
'mobilenet_w1': mobilenet_w1,
'mobilenet_w3d4': mobilenet_w3d4,
'mobilenet_wd2': mobilenet_wd2,
'mobilenet_wd4': mobilenet_wd4,
'fdmobilenet_w1': fdmobilenet_w1,
'fdmobilenet_w3d4': fdmobilenet_w3d4,
'fdmobilenet_wd2': fdmobilenet_wd2,
'fdmobilenet_wd4': fdmobilenet_wd4,
'mobilenetv2_w1': mobilenetv2_w1,
'mobilenetv2_w3d4': mobilenetv2_w3d4,
'mobilenetv2_wd2': mobilenetv2_wd2,
'mobilenetv2_wd4': mobilenetv2_wd4,
'mobilenetv3_small_w7d20': mobilenetv3_small_w7d20,
'mobilenetv3_small_wd2': mobilenetv3_small_wd2,
'mobilenetv3_small_w3d4': mobilenetv3_small_w3d4,
'mobilenetv3_small_w1': mobilenetv3_small_w1,
'mobilenetv3_small_w5d4': mobilenetv3_small_w5d4,
'mobilenetv3_large_w7d20': mobilenetv3_large_w7d20,
'mobilenetv3_large_wd2': mobilenetv3_large_wd2,
'mobilenetv3_large_w3d4': mobilenetv3_large_w3d4,
'mobilenetv3_large_w1': mobilenetv3_large_w1,
'mobilenetv3_large_w5d4': mobilenetv3_large_w5d4,
'igcv3_w1': igcv3_w1,
'igcv3_w3d4': igcv3_w3d4,
'igcv3_wd2': igcv3_wd2,
'igcv3_wd4': igcv3_wd4,
'mnasnet': mnasnet,
'darts': darts,
'proxylessnas_cpu': proxylessnas_cpu,
'proxylessnas_gpu': proxylessnas_gpu,
'proxylessnas_mobile': proxylessnas_mobile,
'proxylessnas_mobile14': proxylessnas_mobile14,
'fbnet_cb': fbnet_cb,
'xception': xception,
'inceptionv3': inceptionv3,
'inceptionv4': inceptionv4,
'inceptionresnetv2': inceptionresnetv2,
'polynet': polynet,
'nasnet_4a1056': nasnet_4a1056,
'nasnet_6a4032': nasnet_6a4032,
'pnasnet5large': pnasnet5large,
'spnasnet': spnasnet,
'efficientnet_b0': efficientnet_b0,
'efficientnet_b1': efficientnet_b1,
'efficientnet_b2': efficientnet_b2,
'efficientnet_b3': efficientnet_b3,
'efficientnet_b4': efficientnet_b4,
'efficientnet_b5': efficientnet_b5,
'efficientnet_b6': efficientnet_b6,
'efficientnet_b7': efficientnet_b7,
'efficientnet_b0b': efficientnet_b0b,
'efficientnet_b1b': efficientnet_b1b,
'efficientnet_b2b': efficientnet_b2b,
'efficientnet_b3b': efficientnet_b3b,
'efficientnet_b4b': efficientnet_b4b,
'efficientnet_b5b': efficientnet_b5b,
'efficientnet_b6b': efficientnet_b6b,
'efficientnet_b7b': efficientnet_b7b,
'mixnet_s': mixnet_s,
'mixnet_m': mixnet_m,
'mixnet_l': mixnet_l,
'nin_cifar10': nin_cifar10,
'nin_cifar100': nin_cifar100,
'nin_svhn': nin_svhn,
'resnet20_cifar10': resnet20_cifar10,
'resnet20_cifar100': resnet20_cifar100,
'resnet20_svhn': resnet20_svhn,
'resnet56_cifar10': resnet56_cifar10,
'resnet56_cifar100': resnet56_cifar100,
'resnet56_svhn': resnet56_svhn,
'resnet110_cifar10': resnet110_cifar10,
'resnet110_cifar100': resnet110_cifar100,
'resnet110_svhn': resnet110_svhn,
'resnet164bn_cifar10': resnet164bn_cifar10,
'resnet164bn_cifar100': resnet164bn_cifar100,
'resnet164bn_svhn': resnet164bn_svhn,
'resnet272bn_cifar10': resnet272bn_cifar10,
'resnet272bn_cifar100': resnet272bn_cifar100,
'resnet272bn_svhn': resnet272bn_svhn,
'resnet542bn_cifar10': resnet542bn_cifar10,
'resnet542bn_cifar100': resnet542bn_cifar100,
'resnet542bn_svhn': resnet542bn_svhn,
'resnet1001_cifar10': resnet1001_cifar10,
'resnet1001_cifar100': resnet1001_cifar100,
'resnet1001_svhn': resnet1001_svhn,
'resnet1202_cifar10': resnet1202_cifar10,
'resnet1202_cifar100': resnet1202_cifar100,
'resnet1202_svhn': resnet1202_svhn,
'preresnet20_cifar10': preresnet20_cifar10,
'preresnet20_cifar100': preresnet20_cifar100,
'preresnet20_svhn': preresnet20_svhn,
'preresnet56_cifar10': preresnet56_cifar10,
'preresnet56_cifar100': preresnet56_cifar100,
'preresnet56_svhn': preresnet56_svhn,
'preresnet110_cifar10': preresnet110_cifar10,
'preresnet110_cifar100': preresnet110_cifar100,
'preresnet110_svhn': preresnet110_svhn,
'preresnet164bn_cifar10': preresnet164bn_cifar10,
'preresnet164bn_cifar100': preresnet164bn_cifar100,
'preresnet164bn_svhn': preresnet164bn_svhn,
'preresnet272bn_cifar10': preresnet272bn_cifar10,
'preresnet272bn_cifar100': preresnet272bn_cifar100,
'preresnet272bn_svhn': preresnet272bn_svhn,
'preresnet542bn_cifar10': preresnet542bn_cifar10,
'preresnet542bn_cifar100': preresnet542bn_cifar100,
'preresnet542bn_svhn': preresnet542bn_svhn,
'preresnet1001_cifar10': preresnet1001_cifar10,
'preresnet1001_cifar100': preresnet1001_cifar100,
'preresnet1001_svhn': preresnet1001_svhn,
'preresnet1202_cifar10': preresnet1202_cifar10,
'preresnet1202_cifar100': preresnet1202_cifar100,
'preresnet1202_svhn': preresnet1202_svhn,
'resnext20_16x4d_cifar10': resnext20_16x4d_cifar10,
'resnext20_16x4d_cifar100': resnext20_16x4d_cifar100,
'resnext20_16x4d_svhn': resnext20_16x4d_svhn,
'resnext20_32x2d_cifar10': resnext20_32x2d_cifar10,
'resnext20_32x2d_cifar100': resnext20_32x2d_cifar100,
'resnext20_32x2d_svhn': resnext20_32x2d_svhn,
'resnext20_32x4d_cifar10': resnext20_32x4d_cifar10,
'resnext20_32x4d_cifar100': resnext20_32x4d_cifar100,
'resnext20_32x4d_svhn': resnext20_32x4d_svhn,
'resnext29_32x4d_cifar10': resnext29_32x4d_cifar10,
'resnext29_32x4d_cifar100': resnext29_32x4d_cifar100,
'resnext29_32x4d_svhn': resnext29_32x4d_svhn,
'resnext29_16x64d_cifar10': resnext29_16x64d_cifar10,
'resnext29_16x64d_cifar100': resnext29_16x64d_cifar100,
'resnext29_16x64d_svhn': resnext29_16x64d_svhn,
'resnext272_1x64d_cifar10': resnext272_1x64d_cifar10,
'resnext272_1x64d_cifar100': resnext272_1x64d_cifar100,
'resnext272_1x64d_svhn': resnext272_1x64d_svhn,
'resnext272_2x32d_cifar10': resnext272_2x32d_cifar10,
'resnext272_2x32d_cifar100': resnext272_2x32d_cifar100,
'resnext272_2x32d_svhn': resnext272_2x32d_svhn,
'seresnet20_cifar10': seresnet20_cifar10,
'seresnet20_cifar100': seresnet20_cifar100,
'seresnet20_svhn': seresnet20_svhn,
'seresnet56_cifar10': seresnet56_cifar10,
'seresnet56_cifar100': seresnet56_cifar100,
'seresnet56_svhn': seresnet56_svhn,
'seresnet110_cifar10': seresnet110_cifar10,
'seresnet110_cifar100': seresnet110_cifar100,
'seresnet110_svhn': seresnet110_svhn,
'seresnet164bn_cifar10': seresnet164bn_cifar10,
'seresnet164bn_cifar100': seresnet164bn_cifar100,
'seresnet164bn_svhn': seresnet164bn_svhn,
'seresnet272bn_cifar10': seresnet272bn_cifar10,
'seresnet272bn_cifar100': seresnet272bn_cifar100,
'seresnet272bn_svhn': seresnet272bn_svhn,
'seresnet542bn_cifar10': seresnet542bn_cifar10,
'seresnet542bn_cifar100': seresnet542bn_cifar100,
'seresnet542bn_svhn': seresnet542bn_svhn,
'seresnet1001_cifar10': seresnet1001_cifar10,
'seresnet1001_cifar100': seresnet1001_cifar100,
'seresnet1001_svhn': seresnet1001_svhn,
'seresnet1202_cifar10': seresnet1202_cifar10,
'seresnet1202_cifar100': seresnet1202_cifar100,
'seresnet1202_svhn': seresnet1202_svhn,
'sepreresnet20_cifar10': sepreresnet20_cifar10,
'sepreresnet20_cifar100': sepreresnet20_cifar100,
'sepreresnet20_svhn': sepreresnet20_svhn,
'sepreresnet56_cifar10': sepreresnet56_cifar10,
'sepreresnet56_cifar100': sepreresnet56_cifar100,
'sepreresnet56_svhn': sepreresnet56_svhn,
'sepreresnet110_cifar10': sepreresnet110_cifar10,
'sepreresnet110_cifar100': sepreresnet110_cifar100,
'sepreresnet110_svhn': sepreresnet110_svhn,
'sepreresnet164bn_cifar10': sepreresnet164bn_cifar10,
'sepreresnet164bn_cifar100': sepreresnet164bn_cifar100,
'sepreresnet164bn_svhn': sepreresnet164bn_svhn,
'sepreresnet272bn_cifar10': sepreresnet272bn_cifar10,
'sepreresnet272bn_cifar100': sepreresnet272bn_cifar100,
'sepreresnet272bn_svhn': sepreresnet272bn_svhn,
'sepreresnet542bn_cifar10': sepreresnet542bn_cifar10,
'sepreresnet542bn_cifar100': sepreresnet542bn_cifar100,
'sepreresnet542bn_svhn': sepreresnet542bn_svhn,
'sepreresnet1001_cifar10': sepreresnet1001_cifar10,
'sepreresnet1001_cifar100': sepreresnet1001_cifar100,
'sepreresnet1001_svhn': sepreresnet1001_svhn,
'sepreresnet1202_cifar10': sepreresnet1202_cifar10,
'sepreresnet1202_cifar100': sepreresnet1202_cifar100,
'sepreresnet1202_svhn': sepreresnet1202_svhn,
'pyramidnet110_a48_cifar10': pyramidnet110_a48_cifar10,
'pyramidnet110_a48_cifar100': pyramidnet110_a48_cifar100,
'pyramidnet110_a48_svhn': pyramidnet110_a48_svhn,
'pyramidnet110_a84_cifar10': pyramidnet110_a84_cifar10,
'pyramidnet110_a84_cifar100': pyramidnet110_a84_cifar100,
'pyramidnet110_a84_svhn': pyramidnet110_a84_svhn,
'pyramidnet110_a270_cifar10': pyramidnet110_a270_cifar10,
'pyramidnet110_a270_cifar100': pyramidnet110_a270_cifar100,
'pyramidnet110_a270_svhn': pyramidnet110_a270_svhn,
'pyramidnet164_a270_bn_cifar10': pyramidnet164_a270_bn_cifar10,
'pyramidnet164_a270_bn_cifar100': pyramidnet164_a270_bn_cifar100,
'pyramidnet164_a270_bn_svhn': pyramidnet164_a270_bn_svhn,
'pyramidnet200_a240_bn_cifar10': pyramidnet200_a240_bn_cifar10,
'pyramidnet200_a240_bn_cifar100': pyramidnet200_a240_bn_cifar100,
'pyramidnet200_a240_bn_svhn': pyramidnet200_a240_bn_svhn,
'pyramidnet236_a220_bn_cifar10': pyramidnet236_a220_bn_cifar10,
'pyramidnet236_a220_bn_cifar100': pyramidnet236_a220_bn_cifar100,
'pyramidnet236_a220_bn_svhn': pyramidnet236_a220_bn_svhn,
'pyramidnet272_a200_bn_cifar10': pyramidnet272_a200_bn_cifar10,
'pyramidnet272_a200_bn_cifar100': pyramidnet272_a200_bn_cifar100,
'pyramidnet272_a200_bn_svhn': pyramidnet272_a200_bn_svhn,
'densenet40_k12_cifar10': densenet40_k12_cifar10,
'densenet40_k12_cifar100': densenet40_k12_cifar100,
'densenet40_k12_svhn': densenet40_k12_svhn,
'densenet40_k12_bc_cifar10': densenet40_k12_bc_cifar10,
'densenet40_k12_bc_cifar100': densenet40_k12_bc_cifar100,
'densenet40_k12_bc_svhn': densenet40_k12_bc_svhn,
'densenet40_k24_bc_cifar10': densenet40_k24_bc_cifar10,
'densenet40_k24_bc_cifar100': densenet40_k24_bc_cifar100,
'densenet40_k24_bc_svhn': densenet40_k24_bc_svhn,
'densenet40_k36_bc_cifar10': densenet40_k36_bc_cifar10,
'densenet40_k36_bc_cifar100': densenet40_k36_bc_cifar100,
'densenet40_k36_bc_svhn': densenet40_k36_bc_svhn,
'densenet100_k12_cifar10': densenet100_k12_cifar10,
'densenet100_k12_cifar100': densenet100_k12_cifar100,
'densenet100_k12_svhn': densenet100_k12_svhn,
'densenet100_k24_cifar10': densenet100_k24_cifar10,
'densenet100_k24_cifar100': densenet100_k24_cifar100,
'densenet100_k24_svhn': densenet100_k24_svhn,
'densenet100_k12_bc_cifar10': densenet100_k12_bc_cifar10,
'densenet100_k12_bc_cifar100': densenet100_k12_bc_cifar100,
'densenet100_k12_bc_svhn': densenet100_k12_bc_svhn,
'densenet190_k40_bc_cifar10': densenet190_k40_bc_cifar10,
'densenet190_k40_bc_cifar100': densenet190_k40_bc_cifar100,
'densenet190_k40_bc_svhn': densenet190_k40_bc_svhn,
'densenet250_k24_bc_cifar10': densenet250_k24_bc_cifar10,
'densenet250_k24_bc_cifar100': densenet250_k24_bc_cifar100,
'densenet250_k24_bc_svhn': densenet250_k24_bc_svhn,
'xdensenet40_2_k24_bc_cifar10': xdensenet40_2_k24_bc_cifar10,
'xdensenet40_2_k24_bc_cifar100': xdensenet40_2_k24_bc_cifar100,
'xdensenet40_2_k24_bc_svhn': xdensenet40_2_k24_bc_svhn,
'xdensenet40_2_k36_bc_cifar10': xdensenet40_2_k36_bc_cifar10,
'xdensenet40_2_k36_bc_cifar100': xdensenet40_2_k36_bc_cifar100,
'xdensenet40_2_k36_bc_svhn': xdensenet40_2_k36_bc_svhn,
'wrn16_10_cifar10': wrn16_10_cifar10,
'wrn16_10_cifar100': wrn16_10_cifar100,
'wrn16_10_svhn': wrn16_10_svhn,
'wrn28_10_cifar10': wrn28_10_cifar10,
'wrn28_10_cifar100': wrn28_10_cifar100,
'wrn28_10_svhn': wrn28_10_svhn,
'wrn40_8_cifar10': wrn40_8_cifar10,
'wrn40_8_cifar100': wrn40_8_cifar100,
'wrn40_8_svhn': wrn40_8_svhn,
'wrn20_10_1bit_cifar10': wrn20_10_1bit_cifar10,
'wrn20_10_1bit_cifar100': wrn20_10_1bit_cifar100,
'wrn20_10_1bit_svhn': wrn20_10_1bit_svhn,
'wrn20_10_32bit_cifar10': wrn20_10_32bit_cifar10,
'wrn20_10_32bit_cifar100': wrn20_10_32bit_cifar100,
'wrn20_10_32bit_svhn': wrn20_10_32bit_svhn,
'ror3_56_cifar10': ror3_56_cifar10,
'ror3_56_cifar100': ror3_56_cifar100,
'ror3_56_svhn': ror3_56_svhn,
'ror3_110_cifar10': ror3_110_cifar10,
'ror3_110_cifar100': ror3_110_cifar100,
'ror3_110_svhn': ror3_110_svhn,
'ror3_164_cifar10': ror3_164_cifar10,
'ror3_164_cifar100': ror3_164_cifar100,
'ror3_164_svhn': ror3_164_svhn,
'rir_cifar10': rir_cifar10,
'rir_cifar100': rir_cifar100,
'rir_svhn': rir_svhn,
'msdnet22_cifar10': msdnet22_cifar10,
'resdropresnet20_cifar10': resdropresnet20_cifar10,
'resdropresnet20_cifar100': resdropresnet20_cifar100,
'resdropresnet20_svhn': resdropresnet20_svhn,
'shakeshakeresnet20_2x16d_cifar10': shakeshakeresnet20_2x16d_cifar10,
'shakeshakeresnet20_2x16d_cifar100': shakeshakeresnet20_2x16d_cifar100,
'shakeshakeresnet20_2x16d_svhn': shakeshakeresnet20_2x16d_svhn,
'shakeshakeresnet26_2x32d_cifar10': shakeshakeresnet26_2x32d_cifar10,
'shakeshakeresnet26_2x32d_cifar100': shakeshakeresnet26_2x32d_cifar100,
'shakeshakeresnet26_2x32d_svhn': shakeshakeresnet26_2x32d_svhn,
'shakedropresnet20_cifar10': shakedropresnet20_cifar10,
'shakedropresnet20_cifar100': shakedropresnet20_cifar100,
'shakedropresnet20_svhn': shakedropresnet20_svhn,
'fractalnet_cifar10': fractalnet_cifar10,
'fractalnet_cifar100': fractalnet_cifar100,
'diaresnet20_cifar10': diaresnet20_cifar10,
'diaresnet20_cifar100': diaresnet20_cifar100,
'diaresnet20_svhn': diaresnet20_svhn,
'diaresnet56_cifar10': diaresnet56_cifar10,
'diaresnet56_cifar100': diaresnet56_cifar100,
'diaresnet56_svhn': diaresnet56_svhn,
'diaresnet110_cifar10': diaresnet110_cifar10,
'diaresnet110_cifar100': diaresnet110_cifar100,
'diaresnet110_svhn': diaresnet110_svhn,
'diaresnet164bn_cifar10': diaresnet164bn_cifar10,
'diaresnet164bn_cifar100': diaresnet164bn_cifar100,
'diaresnet164bn_svhn': diaresnet164bn_svhn,
'diaresnet1001_cifar10': diaresnet1001_cifar10,
'diaresnet1001_cifar100': diaresnet1001_cifar100,
'diaresnet1001_svhn': diaresnet1001_svhn,
'diaresnet1202_cifar10': diaresnet1202_cifar10,
'diaresnet1202_cifar100': diaresnet1202_cifar100,
'diaresnet1202_svhn': diaresnet1202_svhn,
'diapreresnet20_cifar10': diapreresnet20_cifar10,
'diapreresnet20_cifar100': diapreresnet20_cifar100,
'diapreresnet20_svhn': diapreresnet20_svhn,
'diapreresnet56_cifar10': diapreresnet56_cifar10,
'diapreresnet56_cifar100': diapreresnet56_cifar100,
'diapreresnet56_svhn': diapreresnet56_svhn,
'diapreresnet110_cifar10': diapreresnet110_cifar10,
'diapreresnet110_cifar100': diapreresnet110_cifar100,
'diapreresnet110_svhn': diapreresnet110_svhn,
'diapreresnet164bn_cifar10': diapreresnet164bn_cifar10,
'diapreresnet164bn_cifar100': diapreresnet164bn_cifar100,
'diapreresnet164bn_svhn': diapreresnet164bn_svhn,
'diapreresnet1001_cifar10': diapreresnet1001_cifar10,
'diapreresnet1001_cifar100': diapreresnet1001_cifar100,
'diapreresnet1001_svhn': diapreresnet1001_svhn,
'diapreresnet1202_cifar10': diapreresnet1202_cifar10,
'diapreresnet1202_cifar100': diapreresnet1202_cifar100,
'diapreresnet1202_svhn': diapreresnet1202_svhn,
'isqrtcovresnet18': isqrtcovresnet18,
'isqrtcovresnet34': isqrtcovresnet34,
'isqrtcovresnet50': isqrtcovresnet50,
'isqrtcovresnet50b': isqrtcovresnet50b,
'isqrtcovresnet101': isqrtcovresnet101,
'isqrtcovresnet101b': isqrtcovresnet101b,
'resnetd50b': resnetd50b,
'resnetd101b': resnetd101b,
'resnetd152b': resnetd152b,
'octresnet10_ad2': octresnet10_ad2,
'octresnet50b_ad2': octresnet50b_ad2,
'resnet10_cub': resnet10_cub,
'resnet12_cub': resnet12_cub,
'resnet14_cub': resnet14_cub,
'resnetbc14b_cub': resnetbc14b_cub,
'resnet16_cub': resnet16_cub,
'resnet18_cub': resnet18_cub,
'resnet26_cub': resnet26_cub,
'resnetbc26b_cub': resnetbc26b_cub,
'resnet34_cub': resnet34_cub,
'resnetbc38b_cub': resnetbc38b_cub,
'resnet50_cub': resnet50_cub,
'resnet50b_cub': resnet50b_cub,
'resnet101_cub': resnet101_cub,
'resnet101b_cub': resnet101b_cub,
'resnet152_cub': resnet152_cub,
'resnet152b_cub': resnet152b_cub,
'resnet200_cub': resnet200_cub,
'resnet200b_cub': resnet200b_cub,
'seresnet10_cub': seresnet10_cub,
'seresnet12_cub': seresnet12_cub,
'seresnet14_cub': seresnet14_cub,
'seresnetbc14b_cub': seresnetbc14b_cub,
'seresnet16_cub': seresnet16_cub,
'seresnet18_cub': seresnet18_cub,
'seresnet26_cub': seresnet26_cub,
'seresnetbc26b_cub': seresnetbc26b_cub,
'seresnet34_cub': seresnet34_cub,
'seresnetbc38b_cub': seresnetbc38b_cub,
'seresnet50_cub': seresnet50_cub,
'seresnet50b_cub': seresnet50b_cub,
'seresnet101_cub': seresnet101_cub,
'seresnet101b_cub': seresnet101b_cub,
'seresnet152_cub': seresnet152_cub,
'seresnet152b_cub': seresnet152b_cub,
'seresnet200_cub': seresnet200_cub,
'seresnet200b_cub': seresnet200b_cub,
'mobilenet_w1_cub': mobilenet_w1_cub,
'mobilenet_w3d4_cub': mobilenet_w3d4_cub,
'mobilenet_wd2_cub': mobilenet_wd2_cub,
'mobilenet_wd4_cub': mobilenet_wd4_cub,
'fdmobilenet_w1_cub': fdmobilenet_w1_cub,
'fdmobilenet_w3d4_cub': fdmobilenet_w3d4_cub,
'fdmobilenet_wd2_cub': fdmobilenet_wd2_cub,
'fdmobilenet_wd4_cub': fdmobilenet_wd4_cub,
'proxylessnas_cpu_cub': proxylessnas_cpu_cub,
'proxylessnas_gpu_cub': proxylessnas_gpu_cub,
'proxylessnas_mobile_cub': proxylessnas_mobile_cub,
'proxylessnas_mobile14_cub': proxylessnas_mobile14_cub,
'ntsnet_cub': ntsnet_cub,
'fcn8sd_resnetd50b_voc': fcn8sd_resnetd50b_voc,
'fcn8sd_resnetd101b_voc': fcn8sd_resnetd101b_voc,
'fcn8sd_resnetd50b_coco': fcn8sd_resnetd50b_coco,
'fcn8sd_resnetd101b_coco': fcn8sd_resnetd101b_coco,
'fcn8sd_resnetd50b_ade20k': fcn8sd_resnetd50b_ade20k,
'fcn8sd_resnetd101b_ade20k': fcn8sd_resnetd101b_ade20k,
'fcn8sd_resnetd50b_cityscapes': fcn8sd_resnetd50b_cityscapes,
'fcn8sd_resnetd101b_cityscapes': fcn8sd_resnetd101b_cityscapes,
'pspnet_resnetd50b_voc': pspnet_resnetd50b_voc,
'pspnet_resnetd101b_voc': pspnet_resnetd101b_voc,
'pspnet_resnetd50b_coco': pspnet_resnetd50b_coco,
'pspnet_resnetd101b_coco': pspnet_resnetd101b_coco,
'pspnet_resnetd50b_ade20k': pspnet_resnetd50b_ade20k,
'pspnet_resnetd101b_ade20k': pspnet_resnetd101b_ade20k,
'pspnet_resnetd50b_cityscapes': pspnet_resnetd50b_cityscapes,
'pspnet_resnetd101b_cityscapes': pspnet_resnetd101b_cityscapes,
'deeplabv3_resnetd50b_voc': deeplabv3_resnetd50b_voc,
'deeplabv3_resnetd101b_voc': deeplabv3_resnetd101b_voc,
'deeplabv3_resnetd152b_voc': deeplabv3_resnetd152b_voc,
'deeplabv3_resnetd50b_coco': deeplabv3_resnetd50b_coco,
'deeplabv3_resnetd101b_coco': deeplabv3_resnetd101b_coco,
'deeplabv3_resnetd152b_coco': deeplabv3_resnetd152b_coco,
'deeplabv3_resnetd50b_ade20k': deeplabv3_resnetd50b_ade20k,
'deeplabv3_resnetd101b_ade20k': deeplabv3_resnetd101b_ade20k,
'deeplabv3_resnetd50b_cityscapes': deeplabv3_resnetd50b_cityscapes,
'deeplabv3_resnetd101b_cityscapes': deeplabv3_resnetd101b_cityscapes,
'superpointnet': superpointnet,
}
trained_model_metainfo_list = (
('alexnet', 'AlexNet', '1404.5997', 224, 0.875, 200, 'pytorch'),
('alexnetb', 'AlexNet-b', '1404.5997', 224, 0.875, 200, 'pytorch'),
('zfnet', 'ZFNet', '1311.2901', 224, 0.875, 200, 'pytorch'),
('zfnetb', 'ZFNet-b', '1311.2901', 224, 0.875, 200, 'pytorch'),
('vgg11', 'VGG-11', '1409.1556', 224, 0.875, 200, 'pytorch'),
('vgg13', 'VGG-13', '1409.1556', 224, 0.875, 200, 'pytorch'),
('vgg16', 'VGG-16', '1409.1556', 224, 0.875, 200, 'pytorch'),
('vgg19', 'VGG-19', '1409.1556', 224, 0.875, 200, 'pytorch, from [dmlc/gluon-cv]'),
('bn_vgg11', 'BN-VGG-11', '1409.1556', 224, 0.875, 200, 'pytorch'),
('bn_vgg13', 'BN-VGG-13', '1409.1556', 224, 0.875, 200, 'pytorch'),
('bn_vgg16', 'BN-VGG-16', '1409.1556', 224, 0.875, 200, 'pytorch'),
('bn_vgg19', 'BN-VGG-19', '1409.1556', 224, 0.875, 200, 'pytorch'),
('bn_vgg11b', 'BN-VGG-11b', '1409.1556', 224, 0.875, 200, 'pytorch'),
('bn_vgg13b', 'BN-VGG-13b', '1409.1556', 224, 0.875, 200, 'pytorch, from [dmlc/gluon-cv]'),
('bn_vgg16b', 'BN-VGG-16b', '1409.1556', 224, 0.875, 200, 'pytorch, from [dmlc/gluon-cv]'),
('bn_vgg19b', 'BN-VGG-19b', '1409.1556', 224, 0.875, 200, 'pytorch, from [dmlc/gluon-cv]'),
('bninception', 'BN-Inception', '1502.03167', 224, 0.875, 200, 'pytorch'),
('resnet10', 'ResNet-10', '1512.03385', 224, 0.875, 200, 'pytorch'),
('resnet12', 'ResNet-12', '1512.03385', 224, 0.875, 200, 'pytorch'),
('resnet14', 'ResNet-14', '1512.03385', 224, 0.875, 200, 'pytorch'),
('resnet16', 'ResNet-16', '1512.03385', 224, 0.875, 200, 'pytorch'),
('resnet18', 'ResNet-18', '1512.03385', 224, 0.875, 200, 'pytorch'),
('resnet26', 'ResNet-26', '1512.03385', 224, 0.875, 200, 'pytorch'),
('resnetbc26b', 'ResNet-BC-26b', '1512.03385', 224, 0.875, 200, 'pytorch'),
('resnet34', 'ResNet-34', '1512.03385', 224, 0.875, 200, 'pytorch'),
('resnetbc38b', 'ResNet-BC-38b', '1512.03385', 224, 0.875, 200, 'pytorch'),
('resnet50', 'ResNet-50', '1512.03385', 224, 0.875, 200, 'pytorch'),
('resnet50b', 'ResNet-50b', '1512.03385', 224, 0.875, 200, 'pytorch'),
('resnet101', 'ResNet-101', '1512.03385', 224, 0.875, 200, 'pytorch, from [dmlc/gluon-cv]'),
('resnet101b', 'ResNet-101b', '1512.03385', 224, 0.875, 200, 'pytorch'),
('resnet152', 'ResNet-152', '1512.03385', 224, 0.875, 200, 'pytorch, from [dmlc/gluon-cv]'),
('resnet152b', 'ResNet-152b', '1512.03385', 224, 0.875, 200, 'pytorch'),
('preresnet10', 'PrepResNet-10', '1603.05027', 224, 0.875, 200, 'pytorch'),
('preresnet12', 'PreResNet-12', '1603.05027', 224, 0.875, 200, 'pytorch'),
('preresnet14', 'PreResNet-14', '1603.05027', 224, 0.875, 200, 'pytorch'),
('preresnet16', 'PreResNet-16', '1603.05027', 224, 0.875, 200, 'pytorch'),
('preresnet18', 'PreResNet-18', '1603.05027', 224, 0.875, 200, 'pytorch'),
('preresnet26', 'PreResNet-26', '1603.05027', 224, 0.875, 200, 'pytorch'),
('preresnetbc26b', 'PreResNet-BC-26b', '1603.05027', 224, 0.875, 200, 'pytorch'),
('preresnet34', 'PreResNet-34', '1603.05027', 224, 0.875, 200, 'pytorch'),
('preresnetbc38b', 'PreResNet-BC-38b', '1603.05027', 224, 0.875, 200, 'pytorch'),
('preresnet50', 'PreResNet-50', '1603.05027', 224, 0.875, 200, 'pytorch'),
('preresnet50b', 'PreResNet-50b', '1603.05027', 224, 0.875, 200, 'pytorch'),
('preresnet101', 'PreResNet-101', '1603.05027', 224, 0.875, 200, 'pytorch, from [dmlc/gluon-cv]'),
('preresnet101b', 'PreResNet-101b', '1603.05027', 224, 0.875, 200, 'pytorch'),
('preresnet152', 'PreResNet-152', '1603.05027', 224, 0.875, 200, 'pytorch, from [dmlc/gluon-cv]'),
('preresnet152b', 'PreResNet-152b', '1603.05027', 224, 0.875, 200, 'pytorch'),
('preresnet200b', 'PreResNet-200b', '1603.05027', 224, 0.875, 200, 'pytorch, from [tornadomeet/ResNet]'),
('preresnet269b', 'PreResNet-269b', '1603.05027', 224, 0.875, 200, 'pytorch, from [soeaver/mxnet-model]'),
('resnext14_16x4d', 'ResNeXt-14 (16x4d)', '1611.05431', 224, 0.875, 200, 'pytorch'),
('resnext14_32x2d', 'ResNeXt-14 (32x2d)', '1611.05431', 224, 0.875, 200, 'pytorch'),
('resnext14_32x4d', 'ResNeXt-14 (32x4d)', '1611.05431', 224, 0.875, 200, 'pytorch'),
('resnext26_32x2d', 'ResNeXt-26 (32x2d)', '1611.05431', 224, 0.875, 200, 'pytorch'),
('resnext26_32x4d', 'ResNeXt-26 (32x4d)', '1611.05431', 224, 0.875, 200, 'pytorch'),
('resnext101_32x4d', 'ResNeXt-101 (32x4d)', '1611.05431', 224, 0.875, 200,
'pytorch, from [Cadene/pretrained...pytorch]'),
('resnext101_64x4d', 'ResNeXt-101 (64x4d)', '1611.05431', 224, 0.875, 200,
'pytorch, from [Cadene/pretrained...pytorch]'),
('seresnet10', 'SE-ResNet-10', '1709.01507', 224, 0.875, 200, 'pytorch'),
('seresnet18', 'SE-ResNet-18', '1709.01507', 224, 0.875, 200, 'pytorch'),
('seresnet26', 'SE-ResNet-26', '1709.01507', 224, 0.875, 200, 'pytorch'),
('seresnetbc26b', 'SE-ResNet-BC-26b', '1709.01507', 224, 0.875, 200, 'pytorch'),
('seresnetbc38b', 'SE-ResNet-BC-38b', '1709.01507', 224, 0.875, 200, 'pytorch'),
('seresnet50', 'SE-ResNet-50', '1709.01507', 224, 0.875, 200, 'pytorch, from [Cadene/pretrained...pytorch]'),
('seresnet50b', 'SE-ResNet-50b', '1709.01507', 224, 0.875, 200, 'pytorch'),
('seresnet101', 'SE-ResNet-101', '1709.01507', 224, 0.875, 200, 'pytorch, from [Cadene/pretrained...pytorch]'),
('seresnet152', 'SE-ResNet-152', '1709.01507', 224, 0.875, 200, 'pytorch, from [Cadene/pretrained...pytorch]'),
('sepreresnet10', 'SE-PreResNet-10', '1709.01507', 224, 0.875, 200, 'pytorch'),
('sepreresnet18', 'SE-PreResNet-18', '1709.01507', 224, 0.875, 200, 'pytorch'),
('sepreresnetbc26b', 'SE-PreResNet-BC-26b', '1709.01507', 224, 0.875, 200, 'pytorch'),
('sepreresnetbc38b', 'SE-PreResNet-BC-38b', '1709.01507', 224, 0.875, 200, 'pytorch'),
('seresnext50_32x4d', 'SE-ResNeXt-50 (32x4d)', '1709.01507', 224, 0.875, 200,
'pytorch, from [Cadene/pretrained...pytorch]'),
('seresnext101_32x4d', 'SE-ResNeXt-101 (32x4d)', '1709.01507', 224, 0.875, 200,
'pytorch, from [Cadene/pretrained...pytorch]'),
('senet16', 'SENet-16', '1709.01507', 224, 0.875, 200, 'pytorch'),
('senet28', 'SENet-28', '1709.01507', 224, 0.875, 200, 'pytorch'),
('senet154', 'SENet-154', '1709.01507', 224, 0.875, 200, 'pytorch, from [Cadene/pretrained...pytorch]'),
('ibn_resnet50', 'IBN-ResNet-50', '1807.09441', 224, 0.875, 200, 'pytorch, from [XingangPan/IBN-Net]'),
('ibn_resnet101', 'IBN-ResNet-101', '1807.09441', 224, 0.875, 200, 'pytorch, from [XingangPan/IBN-Net]'),
('ibnb_resnet50', 'IBN(b)-ResNet-50', '1807.09441', 224, 0.875, 200, 'pytorch, from [XingangPan/IBN-Net]'),
('ibn_resnext101_32x4d', 'IBN-ResNeXt-101 (32x4d)', '1807.09441', 224, 0.875, 200,
'pytorch, from [XingangPan/IBN-Net]'),
('ibn_densenet121', 'IBN-DenseNet-121', '1807.09441', 224, 0.875, 200, 'pytorch, from [XingangPan/IBN-Net]'),
('ibn_densenet169', 'IBN-DenseNet-169', '1807.09441', 224, 0.875, 200, 'pytorch, from [XingangPan/IBN-Net]'),
('airnet50_1x64d_r2', 'AirNet50-1x64d (r=2)', '', 224, 0.875, 200, 'pytorch, from [soeaver/AirNet-PyTorch]'),
('airnet50_1x64d_r16', 'AirNet50-1x64d (r=16)', '', 224, 0.875, 200, 'pytorch, from [soeaver/AirNet-PyTorch]'),
('airnext50_32x4d_r2', 'AirNeXt50-32x4d (r=2)', '', 224, 0.875, 200, 'pytorch, from [soeaver/AirNet-PyTorch]'),
('bam_resnet50', 'BAM-ResNet-50', '1807.06514', 224, 0.875, 200, 'pytorch, from [Jongchan/attention-module]'),
('cbam_resnet50', 'CBAM-ResNet-50', '1807.06521', 224, 0.875, 200, 'pytorch, from [Jongchan/attention-module]'),
('pyramidnet101_a360', 'PyramidNet-101 (a=360)', '1610.02915', 224, 0.875, 200,
'pytorch, from [dyhan0920/Pyramid...PyTorch]'),
('diracnet18v2', 'DiracNetV2-18', '1706.00388', 224, 0.875, 200, 'pytorch, from [szagoruyko/diracnets]'),
('diracnet34v2', 'DiracNetV2-34', '1706.00388', 224, 0.875, 200, 'pytorch, from [szagoruyko/diracnets]'),
('densenet121', 'DenseNet-121', '1608.06993', 224, 0.875, 200, 'pytorch'),
('densenet161', 'DenseNet-161', '1608.06993', 224, 0.875, 200, 'pytorch, from [dmlc/gluon-cv]'),
('densenet169', 'DenseNet-169', '1608.06993', 224, 0.875, 200, 'pytorch'),
('densenet201', 'DenseNet-201', '1608.06993', 224, 0.875, 200, 'pytorch, from [dmlc/gluon-cv]'),
('condensenet74_c4_g4', 'CondenseNet-74 (C=G=4)', '1711.09224', 224, 0.875, 200,
'pytorch, from [ShichenLiu/CondenseNet]'),
('condensenet74_c8_g8', 'CondenseNet-74 (C=G=8)', '1711.09224', 224, 0.875, 200,
'pytorch, from [ShichenLiu/CondenseNet]'),
('peleenet', 'PeleeNet', '1804.06882', 224, 0.875, 200, 'pytorch'),
('wrn50_2', 'WRN-50-2', '1605.07146', 224, 0.875, 200, 'pytorch, from [szagoruyko/functional-zoo]'),
('drnc26', 'DRN-C-26', '1705.09914', 224, 0.875, 200, 'pytorch, from [fyu/drn]'),
('drnc42', 'DRN-C-42', '1705.09914', 224, 0.875, 200, 'pytorch, from [fyu/drn]'),
('drnc58', 'DRN-C-58', '1705.09914', 224, 0.875, 200, 'pytorch, from [fyu/drn]'),
('drnd22', 'DRN-D-22', '1705.09914', 224, 0.875, 200, 'pytorch, from [fyu/drn]'),
('drnd38', 'DRN-D-38', '1705.09914', 224, 0.875, 200, 'pytorch, from [fyu/drn]'),
('drnd54', 'DRN-D-54', '1705.09914', 224, 0.875, 200, 'pytorch, from [fyu/drn]'),
('drnd105', 'DRN-D-105', '1705.09914', 224, 0.875, 200, 'pytorch, from [fyu/drn]'),
('dpn68', 'DPN-68', '1707.01629', 224, 0.875, 200, 'pytorch'),
('dpn98', 'DPN-98', '1707.01629', 224, 0.875, 200, 'pytorch, from [Cadene/pretrained...pytorch]'),
('dpn131', 'DPN-131', '1707.01629', 224, 0.875, 200, 'pytorch, from [Cadene/pretrained...pytorch]'),
('darknet_tiny', 'DarkNet Tiny', '', 224, 0.875, 200, 'pytorch'),
('darknet_ref', 'DarkNet Ref', '', 224, 0.875, 200, 'pytorch'),
('darknet53', 'DarkNet-53', '1804.02767', 224, 0.875, 200, 'pytorch, from [dmlc/gluon-cv]'),
('irevnet301', 'i-RevNet-301', '1802.07088', 224, 0.875, 200, 'pytorch, from [jhjacobsen/pytorch-i-revnet]'),
('bagnet9', 'BagNet-9', '', 224, 0.875, 200, 'pytorch, from [wielandbrendel/bag...models]'),
('bagnet17', 'BagNet-17', '', 224, 0.875, 200, 'pytorch, from [wielandbrendel/bag...models]'),
('bagnet33', 'BagNet-33', '', 224, 0.875, 200, 'pytorch, from [wielandbrendel/bag...models]'),
('dla34', 'DLA-34', '1707.06484', 224, 0.875, 200, 'pytorch, from [ucbdrive/dla]'),
('dla46c', 'DLA-46-C', '1707.06484', 224, 0.875, 200, 'pytorch'),
('dla46xc', 'DLA-X-46-C', '1707.06484', 224, 0.875, 200, 'pytorch'),
('dla60', 'DLA-60', '1707.06484', 224, 0.875, 200, 'pytorch, from [ucbdrive/dla]'),
('dla60x', 'DLA-X-60', '1707.06484', 224, 0.875, 200, 'pytorch, from [ucbdrive/dla]'),
('dla60xc', 'DLA-X-60-C', '1707.06484', 224, 0.875, 200, 'pytorch'),
('dla102', 'DLA-102', '1707.06484', 224, 0.875, 200, 'pytorch, from [ucbdrive/dla]'),
('dla102x', 'DLA-X-102', '1707.06484', 224, 0.875, 200, 'pytorch, from [ucbdrive/dla]'),
('dla102x2', 'DLA-X2-102', '1707.06484', 224, 0.875, 200, 'pytorch, from [ucbdrive/dla]'),
('dla169', 'DLA-169', '1707.06484', 224, 0.875, 200, 'pytorch, from [ucbdrive/dla]'),
('fishnet150', 'FishNet-150', '', 224, 0.875, 200, 'pytorch, from [kevin-ssy/FishNet]'),
('espnetv2_wd2', 'ESPNetv2 x0.5', '1811.11431', 224, 0.875, 200, 'pytorch, from [sacmehta/ESPNetv2]'),
('espnetv2_w1', 'ESPNetv2 x1.0', '1811.11431', 224, 0.875, 200, 'pytorch, from [sacmehta/ESPNetv2]'),
('espnetv2_w5d4', 'ESPNetv2 x1.25', '1811.11431', 224, 0.875, 200, 'pytorch, from [sacmehta/ESPNetv2]'),
('espnetv2_w3d2', 'ESPNetv2 x1.5', '1811.11431', 224, 0.875, 200, 'pytorch, from [sacmehta/ESPNetv2]'),
('espnetv2_w2', 'ESPNetv2 x2.0', '1811.11431', 224, 0.875, 200, 'pytorch, from [sacmehta/ESPNetv2]'),
('squeezenet_v1_0', 'SqueezeNet v1.0', '1602.07360', 224, 0.875, 200, 'pytorch'),
('squeezenet_v1_1', 'SqueezeNet v1.1', '1602.07360', 224, 0.875, 200, 'pytorch'),
('squeezeresnet_v1_0', 'SqueezeResNet v1.0', '1602.07360', 224, 0.875, 200, 'pytorch'),
('squeezeresnet_v1_1', 'SqueezeResNet v1.1', '1602.07360', 224, 0.875, 200, 'pytorch'),
('sqnxt23_w1', '1.0-SqNxt-23', '1803.10615', 224, 0.875, 200, 'pytorch'),
('sqnxt23v5_w1', '1.0-SqNxt-23v5', '1803.10615', 224, 0.875, 200, 'pytorch'),
('sqnxt23_w3d2', '1.5-SqNxt-23', '1803.10615', 224, 0.875, 200, 'pytorch'),
('sqnxt23v5_w3d2', '1.5-SqNxt-23v5', '1803.10615', 224, 0.875, 200, 'pytorch'),
('sqnxt23_w2', '2.0-SqNxt-23', '1803.10615', 224, 0.875, 200, 'pytorch'),
('sqnxt23v5_w2', '2.0-SqNxt-23v5', '1803.10615', 224, 0.875, 200, 'pytorch'),
('shufflenet_g1_wd4', 'ShuffleNet x0.25 (g=1)', '1707.01083', 224, 0.875, 200, 'pytorch'),
('shufflenet_g3_wd4', 'ShuffleNet x0.25 (g=3)', '1707.01083', 224, 0.875, 200, 'pytorch'),
('shufflenet_g1_wd2', 'ShuffleNet x0.5 (g=1)', '1707.01083', 224, 0.875, 200, 'pytorch'),
('shufflenet_g3_wd2', 'ShuffleNet x0.5 (g=3)', '1707.01083', 224, 0.875, 200, 'pytorch'),
('shufflenet_g1_w3d4', 'ShuffleNet x0.75 (g=1)', '1707.01083', 224, 0.875, 200, 'pytorch'),
('shufflenet_g3_w3d4', 'ShuffleNet x0.75 (g=3)', '1707.01083', 224, 0.875, 200, 'pytorch'),
('shufflenet_g1_w1', 'ShuffleNet x1.0 (g=1)', '1707.01083', 224, 0.875, 200, 'pytorch'),
('shufflenet_g2_w1', 'ShuffleNet x1.0 (g=2)', '1707.01083', 224, 0.875, 200, 'pytorch'),
('shufflenet_g3_w1', 'ShuffleNet x1.0 (g=3)', '1707.01083', 224, 0.875, 200, 'pytorch'),
('shufflenet_g4_w1', 'ShuffleNet x1.0 (g=4)', '1707.01083', 224, 0.875, 200, 'pytorch'),
('shufflenet_g8_w1', 'ShuffleNet x1.0 (g=8)', '1707.01083', 224, 0.875, 200, 'pytorch'),
('shufflenetv2_wd2', 'ShuffleNetV2 x0.5', '1807.11164', 224, 0.875, 200, 'pytorch'),
('shufflenetv2_w1', 'ShuffleNetV2 x1.0', '1807.11164', 224, 0.875, 200, 'pytorch'),
('shufflenetv2_w3d2', 'ShuffleNetV2 x1.5', '1807.11164', 224, 0.875, 200, 'pytorch'),
('shufflenetv2_w2', 'ShuffleNetV2 x2.0', '1807.11164', 224, 0.875, 200, 'pytorch'),
('shufflenetv2b_wd2', 'ShuffleNetV2b x0.5', '1807.11164', 224, 0.875, 200, 'pytorch'),
('shufflenetv2b_w1', 'ShuffleNetV2b x1.0', '1807.11164', 224, 0.875, 200, 'pytorch'),
('shufflenetv2b_w3d2', 'ShuffleNetV2b x1.5', '1807.11164', 224, 0.875, 200, 'pytorch'),
('shufflenetv2b_w2', 'ShuffleNetV2b x2.0', '1807.11164', 224, 0.875, 200, 'pytorch'),
('menet108_8x1_g3', '108-MENet-8x1 (g=3)', '1803.09127', 224, 0.875, 200, 'pytorch'),
('menet128_8x1_g4', '128-MENet-8x1 (g=4)', '1803.09127', 224, 0.875, 200, 'pytorch'),
('menet160_8x1_g8', '160-MENet-8x1 (g=8)', '1803.09127', 224, 0.875, 200, 'pytorch'),
('menet228_12x1_g3', '228-MENet-12x1 (g=3)', '1803.09127', 224, 0.875, 200, 'pytorch'),
('menet256_12x1_g4', '256-MENet-12x1 (g=4)', '1803.09127', 224, 0.875, 200, 'pytorch'),
('menet348_12x1_g3', '348-MENet-12x1 (g=3)', '1803.09127', 224, 0.875, 200, 'pytorch'),
('menet352_12x1_g8', '352-MENet-12x1 (g=8)', '1803.09127', 224, 0.875, 200, 'pytorch'),
('menet456_24x1_g3', '456-MENet-24x1 (g=3)', '1803.09127', 224, 0.875, 200, 'pytorch'),
('mobilenet_wd4', 'MobileNet x0.25', '1704.04861', 224, 0.875, 200, 'pytorch'),
('mobilenet_wd2', 'MobileNet x0.5', '1704.04861', 224, 0.875, 200, 'pytorch'),
('mobilenet_w3d4', 'MobileNet x0.75', '1704.04861', 224, 0.875, 200, 'pytorch'),
('mobilenet_w1', 'MobileNet x1.0', '1704.04861', 224, 0.875, 200, 'pytorch'),
('fdmobilenet_wd4', 'FD-MobileNet x0.25', '1802.03750', 224, 0.875, 200, 'pytorch'),
('fdmobilenet_wd2', 'FD-MobileNet x0.5', '1802.03750', 224, 0.875, 200, 'pytorch'),
('fdmobilenet_w3d4', 'FD-MobileNet x0.75', '1802.03750', 224, 0.875, 200, 'pytorch'),
('fdmobilenet_w1', 'FD-MobileNet x1.0', '1802.03750', 224, 0.875, 200, 'pytorch'),
('mobilenetv2_wd4', 'MobileNetV2 x0.25', '1801.04381', 224, 0.875, 200, 'pytorch'),
('mobilenetv2_wd2', 'MobileNetV2 x0.5', '1801.04381', 224, 0.875, 200, 'pytorch'),
('mobilenetv2_w3d4', 'MobileNetV2 x0.75', '1801.04381', 224, 0.875, 200, 'pytorch'),
('mobilenetv2_w1', 'MobileNetV2 x1.0', '1801.04381', 224, 0.875, 200, 'pytorch'),
('mobilenetv3_large_w1', 'MobileNetV3 L/224/1.0', '1905.02244', 224, 0.875, 200, 'pytorch, from [dmlc/gluon-cv]'),
('igcv3_wd4', 'IGCV3 x0.25', '1806.00178', 224, 0.875, 200, 'pytorch'),
('igcv3_wd2', 'IGCV3 x0.5', '1806.00178', 224, 0.875, 200, 'pytorch'),
('igcv3_w3d4', 'IGCV3 x0.75', '1806.00178', 224, 0.875, 200, 'pytorch'),
('igcv3_w1', 'IGCV3 x1.0', '1806.00178', 224, 0.875, 200, 'pytorch'),
('mnasnet', 'MnasNet', '1807.11626', 224, 0.875, 200, 'pytorch, from [zeusees/Mnasnet...Model]'),
('darts', 'DARTS', '1806.09055', 224, 0.875, 200, 'pytorch, from [quark0/darts]'),
('proxylessnas_cpu', 'ProxylessNAS CPU', '1812.00332', 224, 0.875, 200, 'pytorch, from [MIT-HAN-LAB/ProxylessNAS]'),
('proxylessnas_gpu', 'ProxylessNAS GPU', '1812.00332', 224, 0.875, 200, 'pytorch'),
('proxylessnas_mobile', 'ProxylessNAS Mobile', '1812.00332', 224, 0.875, 200,
'pytorch, from [MIT-HAN-LAB/ProxylessNAS]'),
('proxylessnas_mobile14', 'ProxylessNAS Mob-14', '1812.00332', 224, 0.875, 200, 'pytorch'),
('fbnet_cb', 'FBNet-Cb', '1812.03443', 224, 0.875, 200, 'pytorch, from [rwightman/pyt...models]'),
('xception', 'Xception', '1610.02357', 299, 0.875, 200, 'pytorch, from [Cadene/pretrained...pytorch]'),
('inceptionv3', 'InceptionV3', '1512.00567', 299, 0.875, 200, 'pytorch, from [dmlc/gluon-cv]'),
('inceptionv4', 'InceptionV4', '1602.07261', 299, 0.875, 200, 'pytorch, from [Cadene/pretrained...pytorch]'),
('inceptionresnetv2', 'InceptionResNetV', '1602.07261', 299, 0.875, 200,
'pytorch, from [Cadene/pretrained...pytorch]'),
('polynet', 'PolyNet', '1611.05725', 331, 0.875, 200, 'pytorch, from [Cadene/pretrained...pytorch]'),
('nasnet_4a1056', 'NASNet-A 4@1056', '1707.07012', 224, 0.875, 200, 'pytorch, from [Cadene/pretrained...pytorch]'),
('nasnet_6a4032', 'NASNet-A 6@4032', '1707.07012', 331, 0.875, 200, 'pytorch, from [Cadene/pretrained...pytorch]'),
('pnasnet5large', 'PNASNet-5-Large', '1712.00559', 331, 0.875, 200, 'pytorch, from [Cadene/pretrained...pytorch]'),
('spnasnet', 'SPNASNet', '1904.02877', 224, 0.875, 200, 'pytorch, from [rwightman/pyt...models]'),
('efficientnet_b0', 'EfficientNet-B0', '1905.11946', 224, 0.875, 200, 'pytorch'),
('efficientnet_b1', 'EfficientNet-B1', '1905.11946', 240, 0.882, 200, 'pytorch'),
('efficientnet_b0b', 'EfficientNet-B0b', '1905.11946', 224, 0.875, 200, 'pytorch, from [rwightman/pyt...models]'),
('efficientnet_b1b', 'EfficientNet-B1b', '1905.11946', 240, 0.882, 200, 'pytorch, from [rwightman/pyt...models]'),
('efficientnet_b2b', 'EfficientNet-B2b', '1905.11946', 260, 0.890, 100, 'pytorch, from [rwightman/pyt...models]'),
('efficientnet_b3b', 'EfficientNet-B3b', '1905.11946', 300, 0.904, 90, 'pytorch, from [rwightman/pyt...models]'),
('efficientnet_b4b', 'EfficientNet-B4b', '1905.11946', 380, 0.922, 80, 'pytorch, from [rwightman/pyt...models]'),
('efficientnet_b5b', 'EfficientNet-B5b', '1905.11946', 456, 0.934, 70, 'pytorch, from [rwightman/pyt...models]'),
('efficientnet_b6b', 'EfficientNet-B6b', '1905.11946', 528, 0.942, 60, 'pytorch, from [rwightman/pyt...models]'),
('efficientnet_b7b', 'EfficientNet-B7b', '1905.11946', 600, 0.949, 50, 'pytorch, from [rwightman/pyt...models]'),
('mixnet_s', 'MixNet-S', '1907.09595', 224, 0.875, 200, 'pytorch, from [rwightman/pyt...models]'),
('mixnet_m', 'MixNet-M', '1907.09595', 224, 0.875, 200, 'pytorch, from [rwightman/pyt...models]'),
('mixnet_l', 'MixNet-L', '1907.09595', 224, 0.875, 200, 'pytorch, from [rwightman/pyt...models]'),
)
def get_model(name, **kwargs):
"""
Get supported model.
Parameters:
----------
name : str
Name of model.
Returns
-------
Module
Resulted model.
"""
name = name.lower()
if name not in _models:
raise ValueError("Unsupported model: {}".format(name))
net = _models[name](**kwargs)
return net
| 53,356 | 45.236568 | 120 | py |
null | qimera-main/pytorchcv/models/__init__.py | 0 | 0 | 0 | py | |
null | qimera-main/pytorchcv/models/airnet.py | """
AirNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'Attention Inspiring Receptive-Fields Network for Learning Invariant Representations,'
https://ieeexplore.ieee.org/document/8510896.
"""
__all__ = ['AirNet', 'airnet50_1x64d_r2', 'airnet50_1x64d_r16', 'airnet101_1x64d_r2', 'AirBlock', 'AirInitBlock']
import os
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from .common import conv1x1_block, conv3x3_block
class AirBlock(nn.Module):
"""
AirNet attention block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
groups : int, default 1
Number of groups.
ratio: int, default 2
Air compression ratio.
"""
def __init__(self,
in_channels,
out_channels,
groups=1,
ratio=2):
super(AirBlock, self).__init__()
assert (out_channels % ratio == 0)
mid_channels = out_channels // ratio
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels)
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=1)
self.conv2 = conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
groups=groups)
self.conv3 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
activation=None)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = self.conv1(x)
x = self.pool(x)
x = self.conv2(x)
x = F.interpolate(
input=x,
scale_factor=2,
mode="bilinear",
align_corners=True)
x = self.conv3(x)
x = self.sigmoid(x)
return x
class AirBottleneck(nn.Module):
"""
AirNet bottleneck block for residual path in AirNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
ratio: int
Air compression ratio.
"""
def __init__(self,
in_channels,
out_channels,
stride,
ratio):
super(AirBottleneck, self).__init__()
mid_channels = out_channels // 4
self.use_air_block = (stride == 1 and mid_channels < 512)
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels)
self.conv2 = conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride)
self.conv3 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
activation=None)
if self.use_air_block:
self.air = AirBlock(
in_channels=in_channels,
out_channels=mid_channels,
ratio=ratio)
def forward(self, x):
if self.use_air_block:
att = self.air(x)
x = self.conv1(x)
x = self.conv2(x)
if self.use_air_block:
x = x * att
x = self.conv3(x)
return x
class AirUnit(nn.Module):
"""
AirNet unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
ratio: int
Air compression ratio.
"""
def __init__(self,
in_channels,
out_channels,
stride,
ratio):
super(AirUnit, self).__init__()
self.resize_identity = (in_channels != out_channels) or (stride != 1)
self.body = AirBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
ratio=ratio)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
activation=None)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = x + identity
x = self.activ(x)
return x
class AirInitBlock(nn.Module):
"""
AirNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(AirInitBlock, self).__init__()
mid_channels = out_channels // 2
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=mid_channels,
stride=2)
self.conv2 = conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels)
self.conv3 = conv3x3_block(
in_channels=mid_channels,
out_channels=out_channels)
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=1)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.pool(x)
return x
class AirNet(nn.Module):
"""
AirNet model from 'Attention Inspiring Receptive-Fields Network for Learning Invariant Representations,'
https://ieeexplore.ieee.org/document/8510896.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
ratio: int
Air compression ratio.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
ratio,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(AirNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", AirInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), AirUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
ratio=ratio))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_airnet(blocks,
base_channels,
ratio,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create AirNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
base_channels: int
Base number of channels.
ratio: int
Air compression ratio.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
else:
raise ValueError("Unsupported AirNet with number of blocks: {}".format(blocks))
bottleneck_expansion = 4
init_block_channels = base_channels
channels_per_layers = [base_channels * (2 ** i) * bottleneck_expansion for i in range(len(layers))]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = AirNet(
channels=channels,
init_block_channels=init_block_channels,
ratio=ratio,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def airnet50_1x64d_r2(**kwargs):
"""
AirNet50-1x64d (r=2) model from 'Attention Inspiring Receptive-Fields Network for Learning Invariant
Representations,' https://ieeexplore.ieee.org/document/8510896.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_airnet(blocks=50, base_channels=64, ratio=2, model_name="airnet50_1x64d_r2", **kwargs)
def airnet50_1x64d_r16(**kwargs):
"""
AirNet50-1x64d (r=16) model from 'Attention Inspiring Receptive-Fields Network for Learning Invariant
Representations,' https://ieeexplore.ieee.org/document/8510896.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_airnet(blocks=50, base_channels=64, ratio=16, model_name="airnet50_1x64d_r16", **kwargs)
def airnet101_1x64d_r2(**kwargs):
"""
AirNet101-1x64d (r=2) model from 'Attention Inspiring Receptive-Fields Network for Learning Invariant
Representations,' https://ieeexplore.ieee.org/document/8510896.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_airnet(blocks=101, base_channels=64, ratio=2, model_name="airnet101_1x64d_r2", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
airnet50_1x64d_r2,
airnet50_1x64d_r16,
airnet101_1x64d_r2,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != airnet50_1x64d_r2 or weight_count == 27425864)
assert (model != airnet50_1x64d_r16 or weight_count == 25714952)
assert (model != airnet101_1x64d_r2 or weight_count == 51727432)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 12,525 | 28.612293 | 115 | py |
null | qimera-main/pytorchcv/models/airnext.py | """
AirNeXt for ImageNet-1K, implemented in PyTorch.
Original paper: 'Attention Inspiring Receptive-Fields Network for Learning Invariant Representations,'
https://ieeexplore.ieee.org/document/8510896.
"""
__all__ = ['AirNeXt', 'airnext50_32x4d_r2', 'airnext101_32x4d_r2', 'airnext101_32x4d_r16']
import os
import math
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, conv3x3_block
from .airnet import AirBlock, AirInitBlock
class AirNeXtBottleneck(nn.Module):
"""
AirNet bottleneck block for residual path in ResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
ratio: int
Air compression ratio.
"""
def __init__(self,
in_channels,
out_channels,
stride,
cardinality,
bottleneck_width,
ratio):
super(AirNeXtBottleneck, self).__init__()
mid_channels = out_channels // 4
D = int(math.floor(mid_channels * (bottleneck_width / 64.0)))
group_width = cardinality * D
self.use_air_block = (stride == 1 and mid_channels < 512)
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=group_width)
self.conv2 = conv3x3_block(
in_channels=group_width,
out_channels=group_width,
stride=stride,
groups=cardinality)
self.conv3 = conv1x1_block(
in_channels=group_width,
out_channels=out_channels,
activation=None)
if self.use_air_block:
self.air = AirBlock(
in_channels=in_channels,
out_channels=group_width,
groups=(cardinality // ratio),
ratio=ratio)
def forward(self, x):
if self.use_air_block:
att = self.air(x)
x = self.conv1(x)
x = self.conv2(x)
if self.use_air_block:
x = x * att
x = self.conv3(x)
return x
class AirNeXtUnit(nn.Module):
"""
AirNet unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
ratio: int
Air compression ratio.
"""
def __init__(self,
in_channels,
out_channels,
stride,
cardinality,
bottleneck_width,
ratio):
super(AirNeXtUnit, self).__init__()
self.resize_identity = (in_channels != out_channels) or (stride != 1)
self.body = AirNeXtBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
ratio=ratio)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
activation=None)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = x + identity
x = self.activ(x)
return x
class AirNeXt(nn.Module):
"""
AirNet model from 'Attention Inspiring Receptive-Fields Network for Learning Invariant Representations,'
https://ieeexplore.ieee.org/document/8510896.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
ratio: int
Air compression ratio.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
cardinality,
bottleneck_width,
ratio,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(AirNeXt, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", AirInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), AirNeXtUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
ratio=ratio))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_airnext(blocks,
cardinality,
bottleneck_width,
base_channels,
ratio,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create AirNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
base_channels: int
Base number of channels.
ratio: int
Air compression ratio.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
else:
raise ValueError("Unsupported AirNeXt with number of blocks: {}".format(blocks))
bottleneck_expansion = 4
init_block_channels = base_channels
channels_per_layers = [base_channels * (2 ** i) * bottleneck_expansion for i in range(len(layers))]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = AirNeXt(
channels=channels,
init_block_channels=init_block_channels,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
ratio=ratio,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def airnext50_32x4d_r2(**kwargs):
"""
AirNeXt50-32x4d (r=2) model from 'Attention Inspiring Receptive-Fields Network for Learning Invariant
Representations,' https://ieeexplore.ieee.org/document/8510896.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_airnext(
blocks=50,
cardinality=32,
bottleneck_width=4,
base_channels=64,
ratio=2,
model_name="airnext50_32x4d_r2",
**kwargs)
def airnext101_32x4d_r2(**kwargs):
"""
AirNeXt101-32x4d (r=2) model from 'Attention Inspiring Receptive-Fields Network for Learning Invariant
Representations,' https://ieeexplore.ieee.org/document/8510896.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_airnext(
blocks=101,
cardinality=32,
bottleneck_width=4,
base_channels=64,
ratio=2,
model_name="airnext101_32x4d_r2",
**kwargs)
def airnext101_32x4d_r16(**kwargs):
"""
AirNeXt101-32x4d (r=16) model from 'Attention Inspiring Receptive-Fields Network for Learning Invariant
Representations,' https://ieeexplore.ieee.org/document/8510896.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_airnext(
blocks=101,
cardinality=32,
bottleneck_width=4,
base_channels=64,
ratio=16,
model_name="airnext101_32x4d_r16",
**kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
airnext50_32x4d_r2,
airnext101_32x4d_r2,
airnext101_32x4d_r16,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != airnext50_32x4d_r2 or weight_count == 27604296)
assert (model != airnext101_32x4d_r2 or weight_count == 54099272)
assert (model != airnext101_32x4d_r16 or weight_count == 45456456)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 11,535 | 29.041667 | 115 | py |
null | qimera-main/pytorchcv/models/alexnet.py | """
AlexNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'One weird trick for parallelizing convolutional neural networks,'
https://arxiv.org/abs/1404.5997.
"""
__all__ = ['AlexNet', 'alexnet', 'alexnetb']
import os
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from .common import ConvBlock
class AlexConv(ConvBlock):
"""
AlexNet specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
use_lrn : bool
Whether to use LRN layer.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
use_lrn):
super(AlexConv, self).__init__(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
bias=True,
use_bn=False)
self.use_lrn = use_lrn
def forward(self, x):
x = super(AlexConv, self).forward(x)
if self.use_lrn:
x = F.local_response_norm(x, size=5, k=2.0)
return x
class AlexDense(nn.Module):
"""
AlexNet specific dense block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(AlexDense, self).__init__()
self.fc = nn.Linear(
in_features=in_channels,
out_features=out_channels)
self.activ = nn.ReLU(inplace=True)
self.dropout = nn.Dropout(p=0.5)
def forward(self, x):
x = self.fc(x)
x = self.activ(x)
x = self.dropout(x)
return x
class AlexOutputBlock(nn.Module):
"""
AlexNet specific output block.
Parameters:
----------
in_channels : int
Number of input channels.
classes : int
Number of classification classes.
"""
def __init__(self,
in_channels,
classes):
super(AlexOutputBlock, self).__init__()
mid_channels = 4096
self.fc1 = AlexDense(
in_channels=in_channels,
out_channels=mid_channels)
self.fc2 = AlexDense(
in_channels=mid_channels,
out_channels=mid_channels)
self.fc3 = nn.Linear(
in_features=mid_channels,
out_features=classes)
def forward(self, x):
x = self.fc1(x)
x = self.fc2(x)
x = self.fc3(x)
return x
class AlexNet(nn.Module):
"""
AlexNet model from 'One weird trick for parallelizing convolutional neural networks,'
https://arxiv.org/abs/1404.5997.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
kernel_sizes : list of list of int
Convolution window sizes for each unit.
strides : list of list of int or tuple/list of 2 int
Strides of the convolution for each unit.
paddings : list of list of int or tuple/list of 2 int
Padding value for convolution layer for each unit.
use_lrn : bool
Whether to use LRN layer.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
kernel_sizes,
strides,
paddings,
use_lrn,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(AlexNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
for i, channels_per_stage in enumerate(channels):
use_lrn_i = use_lrn and (i in [0, 1])
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stage.add_module("unit{}".format(j + 1), AlexConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_sizes[i][j],
stride=strides[i][j],
padding=paddings[i][j],
use_lrn=use_lrn_i))
in_channels = out_channels
stage.add_module("pool{}".format(i + 1), nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=0,
ceil_mode=True))
self.features.add_module("stage{}".format(i + 1), stage)
self.output = AlexOutputBlock(
in_channels=(in_channels * 6 * 6),
classes=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_alexnet(version="a",
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create AlexNet model with specific parameters.
Parameters:
----------
version : str, default 'a'
Version of AlexNet ('a' or 'b').
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if version == "a":
channels = [[96], [256], [384, 384, 256]]
kernel_sizes = [[11], [5], [3, 3, 3]]
strides = [[4], [1], [1, 1, 1]]
paddings = [[0], [2], [1, 1, 1]]
use_lrn = True
elif version == "b":
channels = [[64], [192], [384, 256, 256]]
kernel_sizes = [[11], [5], [3, 3, 3]]
strides = [[4], [1], [1, 1, 1]]
paddings = [[2], [2], [1, 1, 1]]
use_lrn = False
else:
raise ValueError("Unsupported AlexNet version {}".format(version))
net = AlexNet(
channels=channels,
kernel_sizes=kernel_sizes,
strides=strides,
paddings=paddings,
use_lrn=use_lrn,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def alexnet(**kwargs):
"""
AlexNet model from 'One weird trick for parallelizing convolutional neural networks,'
https://arxiv.org/abs/1404.5997.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_alexnet(model_name="alexnet", **kwargs)
def alexnetb(**kwargs):
"""
AlexNet-b model from 'One weird trick for parallelizing convolutional neural networks,'
https://arxiv.org/abs/1404.5997. Non-standard version.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_alexnet(version="b", model_name="alexnetb", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
alexnet,
alexnetb,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != alexnet or weight_count == 62378344)
assert (model != alexnetb or weight_count == 61100840)
x = torch.randn(1, 3, 224, 224)
y = net(x)
# y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 9,244 | 27.890625 | 115 | py |
null | qimera-main/pytorchcv/models/bagnet.py | """
BagNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'Approximating CNNs with Bag-of-local-Features models works surprisingly well on ImageNet,'
https://openreview.net/pdf?id=SkfMWhAqYQ.
"""
__all__ = ['BagNet', 'bagnet9', 'bagnet17', 'bagnet33']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1, conv1x1_block, conv3x3_block, ConvBlock
class BagNetBottleneck(nn.Module):
"""
BagNet bottleneck block for residual path in BagNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size of the second convolution.
stride : int or tuple/list of 2 int
Strides of the second convolution.
bottleneck_factor : int, default 4
Bottleneck factor.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
bottleneck_factor=4):
super(BagNetBottleneck, self).__init__()
mid_channels = out_channels // bottleneck_factor
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels)
self.conv2 = ConvBlock(
in_channels=mid_channels,
out_channels=mid_channels,
kernel_size=kernel_size,
stride=stride,
padding=0)
self.conv3 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
activation=None)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class BagNetUnit(nn.Module):
"""
BagNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size of the second body convolution.
stride : int or tuple/list of 2 int
Strides of the second body convolution.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride):
super(BagNetUnit, self).__init__()
self.resize_identity = (in_channels != out_channels) or (stride != 1)
self.body = BagNetBottleneck(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
activation=None)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
if x.size(-1) != identity.size(-1):
diff = identity.size(-1) - x.size(-1)
identity = identity[:, :, :-diff, :-diff]
x = x + identity
x = self.activ(x)
return x
class BagNetInitBlock(nn.Module):
"""
BagNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(BagNetInitBlock, self).__init__()
self.conv1 = conv1x1(
in_channels=in_channels,
out_channels=out_channels)
self.conv2 = conv3x3_block(
in_channels=out_channels,
out_channels=out_channels,
padding=0)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class BagNet(nn.Module):
"""
BagNet model from 'Approximating CNNs with Bag-of-local-Features models works surprisingly well on ImageNet,'
https://openreview.net/pdf?id=SkfMWhAqYQ.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
final_pool_size : int
Size of the pooling windows for final pool.
normal_kernel_sizes : list of int
Count of the first units with 3x3 convolution window size for each stage.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
final_pool_size,
normal_kernel_sizes,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(BagNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", BagNetInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != len(channels) - 1) else 1
kernel_size = 3 if j < normal_kernel_sizes[i] else 1
stage.add_module("unit{}".format(j + 1), BagNetUnit(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=final_pool_size,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_bagnet(field,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create BagNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
layers = [3, 4, 6, 3]
if field == 9:
normal_kernel_sizes = [1, 1, 0, 0]
final_pool_size = 27
elif field == 17:
normal_kernel_sizes = [1, 1, 1, 0]
final_pool_size = 26
elif field == 33:
normal_kernel_sizes = [1, 1, 1, 1]
final_pool_size = 24
else:
raise ValueError("Unsupported BagNet with field: {}".format(field))
init_block_channels = 64
channels_per_layers = [256, 512, 1024, 2048]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = BagNet(
channels=channels,
init_block_channels=init_block_channels,
final_pool_size=final_pool_size,
normal_kernel_sizes=normal_kernel_sizes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def bagnet9(**kwargs):
"""
BagNet-9 model from 'Approximating CNNs with Bag-of-local-Features models works surprisingly well on ImageNet,'
https://openreview.net/pdf?id=SkfMWhAqYQ.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_bagnet(field=9, model_name="bagnet9", **kwargs)
def bagnet17(**kwargs):
"""
BagNet-17 model from 'Approximating CNNs with Bag-of-local-Features models works surprisingly well on ImageNet,'
https://openreview.net/pdf?id=SkfMWhAqYQ.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_bagnet(field=17, model_name="bagnet17", **kwargs)
def bagnet33(**kwargs):
"""
BagNet-33 model from 'Approximating CNNs with Bag-of-local-Features models works surprisingly well on ImageNet,'
https://openreview.net/pdf?id=SkfMWhAqYQ.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_bagnet(field=33, model_name="bagnet33", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
bagnet9,
bagnet17,
bagnet33,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != bagnet9 or weight_count == 15688744)
assert (model != bagnet17 or weight_count == 16213032)
assert (model != bagnet33 or weight_count == 18310184)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 10,903 | 29.373259 | 116 | py |
null | qimera-main/pytorchcv/models/bamresnet.py | """
BAM-ResNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'BAM: Bottleneck Attention Module,' https://arxiv.org/abs/1807.06514.
"""
__all__ = ['BamResNet', 'bam_resnet18', 'bam_resnet34', 'bam_resnet50', 'bam_resnet101', 'bam_resnet152']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1, conv1x1_block, conv3x3_block
from .resnet import ResInitBlock, ResUnit
class DenseBlock(nn.Module):
"""
Standard dense block with Batch normalization and ReLU activation.
Parameters:
----------
in_features : int
Number of input features.
out_features : int
Number of output features.
"""
def __init__(self,
in_features,
out_features):
super(DenseBlock, self).__init__()
self.fc = nn.Linear(
in_features=in_features,
out_features=out_features)
self.bn = nn.BatchNorm1d(num_features=out_features)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
x = self.fc(x)
x = self.bn(x)
x = self.activ(x)
return x
class ChannelGate(nn.Module):
"""
BAM channel gate block.
Parameters:
----------
channels : int
Number of input/output channels.
reduction_ratio : int, default 16
Channel reduction ratio.
num_layers : int, default 1
Number of dense blocks.
"""
def __init__(self,
channels,
reduction_ratio=16,
num_layers=1):
super(ChannelGate, self).__init__()
mid_channels = channels // reduction_ratio
self.pool = nn.AdaptiveAvgPool2d(output_size=(1, 1))
self.init_fc = DenseBlock(
in_features=channels,
out_features=mid_channels)
self.main_fcs = nn.Sequential()
for i in range(num_layers - 1):
self.main_fcs.add_module("fc{}".format(i + 1), DenseBlock(
in_features=mid_channels,
out_features=mid_channels))
self.final_fc = nn.Linear(
in_features=mid_channels,
out_features=channels)
def forward(self, x):
input = x
x = self.pool(x)
x = x.view(x.size(0), -1)
x = self.init_fc(x)
x = self.main_fcs(x)
x = self.final_fc(x)
x = x.unsqueeze(2).unsqueeze(3).expand_as(input)
return x
class SpatialGate(nn.Module):
"""
BAM spatial gate block.
Parameters:
----------
channels : int
Number of input/output channels.
reduction_ratio : int, default 16
Channel reduction ratio.
num_dil_convs : int, default 2
Number of dilated convolutions.
dilation : int, default 4
Dilation/padding value for corresponding convolutions.
"""
def __init__(self,
channels,
reduction_ratio=16,
num_dil_convs=2,
dilation=4):
super(SpatialGate, self).__init__()
mid_channels = channels // reduction_ratio
self.init_conv = conv1x1_block(
in_channels=channels,
out_channels=mid_channels,
stride=1,
bias=True)
self.dil_convs = nn.Sequential()
for i in range(num_dil_convs):
self.dil_convs.add_module("conv{}".format(i + 1), conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
stride=1,
padding=dilation,
dilation=dilation,
bias=True))
self.final_conv = conv1x1(
in_channels=mid_channels,
out_channels=1,
stride=1,
bias=True)
def forward(self, x):
input = x
x = self.init_conv(x)
x = self.dil_convs(x)
x = self.final_conv(x)
x = x.expand_as(input)
return x
class BamBlock(nn.Module):
"""
BAM attention block for BAM-ResNet.
Parameters:
----------
channels : int
Number of input/output channels.
"""
def __init__(self,
channels):
super(BamBlock, self).__init__()
self.ch_att = ChannelGate(channels=channels)
self.sp_att = SpatialGate(channels=channels)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
att = 1 + self.sigmoid(self.ch_att(x) * self.sp_att(x))
x = x * att
return x
class BamResUnit(nn.Module):
"""
BAM-ResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
"""
def __init__(self,
in_channels,
out_channels,
stride,
bottleneck):
super(BamResUnit, self).__init__()
self.use_bam = (stride != 1)
if self.use_bam:
self.bam = BamBlock(channels=in_channels)
self.res_unit = ResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck,
conv1_stride=False)
def forward(self, x):
if self.use_bam:
x = self.bam(x)
x = self.res_unit(x)
return x
class BamResNet(nn.Module):
"""
BAM-ResNet model from 'BAM: Bottleneck Attention Module,' https://arxiv.org/abs/1807.06514.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(BamResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), BamResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_resnet(blocks,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create BAM-ResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer in units.
use_se : bool
Whether to use SE block.
width_scale : float
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 18:
layers = [2, 2, 2, 2]
elif blocks == 34:
layers = [3, 4, 6, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
else:
raise ValueError("Unsupported BAM-ResNet with number of blocks: {}".format(blocks))
init_block_channels = 64
if blocks < 50:
channels_per_layers = [64, 128, 256, 512]
bottleneck = False
else:
channels_per_layers = [256, 512, 1024, 2048]
bottleneck = True
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = BamResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def bam_resnet18(**kwargs):
"""
BAM-ResNet-18 model from 'BAM: Bottleneck Attention Module,' https://arxiv.org/abs/1807.06514.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=18, model_name="bam_resnet18", **kwargs)
def bam_resnet34(**kwargs):
"""
BAM-ResNet-34 model from 'BAM: Bottleneck Attention Module,' https://arxiv.org/abs/1807.06514.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=34, model_name="bam_resnet34", **kwargs)
def bam_resnet50(**kwargs):
"""
BAM-ResNet-50 model from 'BAM: Bottleneck Attention Module,' https://arxiv.org/abs/1807.06514.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=50, model_name="bam_resnet50", **kwargs)
def bam_resnet101(**kwargs):
"""
BAM-ResNet-101 model from 'BAM: Bottleneck Attention Module,' https://arxiv.org/abs/1807.06514.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=101, model_name="bam_resnet101", **kwargs)
def bam_resnet152(**kwargs):
"""
BAM-ResNet-152 model from 'BAM: Bottleneck Attention Module,' https://arxiv.org/abs/1807.06514.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=152, model_name="bam_resnet152", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
bam_resnet18,
bam_resnet34,
bam_resnet50,
bam_resnet101,
bam_resnet152,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != bam_resnet18 or weight_count == 11712503)
assert (model != bam_resnet34 or weight_count == 21820663)
assert (model != bam_resnet50 or weight_count == 25915099)
assert (model != bam_resnet101 or weight_count == 44907227)
assert (model != bam_resnet152 or weight_count == 60550875)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 13,297 | 28.420354 | 115 | py |
null | qimera-main/pytorchcv/models/bninception.py | """
BN-Inception for ImageNet-1K, implemented in PyTorch.
Original paper: 'Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift,'
https://arxiv.org/abs/1502.03167.
"""
__all__ = ['BNInception', 'bninception']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, conv3x3_block, conv7x7_block, Concurrent
class Inception3x3Branch(nn.Module):
"""
BN-Inception 3x3 branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
mid_channels : int
Number of intermediate channels.
stride : int or tuple/list of 2 int, default 1
Strides of the second convolution.
bias : bool, default True
Whether the convolution layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
mid_channels,
stride=1,
bias=True,
use_bn=True):
super(Inception3x3Branch, self).__init__()
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
bias=bias,
use_bn=use_bn)
self.conv2 = conv3x3_block(
in_channels=mid_channels,
out_channels=out_channels,
stride=stride,
bias=bias,
use_bn=use_bn)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class InceptionDouble3x3Branch(nn.Module):
"""
BN-Inception double 3x3 branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
mid_channels : int
Number of intermediate channels.
stride : int or tuple/list of 2 int, default 1
Strides of the second convolution.
bias : bool, default True
Whether the convolution layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
mid_channels,
stride=1,
bias=True,
use_bn=True):
super(InceptionDouble3x3Branch, self).__init__()
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
bias=bias,
use_bn=use_bn)
self.conv2 = conv3x3_block(
in_channels=mid_channels,
out_channels=out_channels,
bias=bias,
use_bn=use_bn)
self.conv3 = conv3x3_block(
in_channels=out_channels,
out_channels=out_channels,
stride=stride,
bias=bias,
use_bn=use_bn)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class InceptionPoolBranch(nn.Module):
"""
BN-Inception avg-pool branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
avg_pool : bool
Whether use average pooling or max pooling.
bias : bool
Whether the convolution layer uses a bias vector.
use_bn : bool
Whether to use BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
avg_pool,
bias,
use_bn):
super(InceptionPoolBranch, self).__init__()
if avg_pool:
self.pool = nn.AvgPool2d(
kernel_size=3,
stride=1,
padding=1,
ceil_mode=True,
count_include_pad=True)
else:
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=1,
padding=1,
ceil_mode=True)
self.conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
bias=bias,
use_bn=use_bn)
def forward(self, x):
x = self.pool(x)
x = self.conv(x)
return x
class StemBlock(nn.Module):
"""
BN-Inception stem block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
mid_channels : int
Number of intermediate channels.
bias : bool
Whether the convolution layer uses a bias vector.
use_bn : bool
Whether to use BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
mid_channels,
bias,
use_bn):
super(StemBlock, self).__init__()
self.conv1 = conv7x7_block(
in_channels=in_channels,
out_channels=mid_channels,
stride=2,
bias=bias,
use_bn=use_bn)
self.pool1 = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=0,
ceil_mode=True)
self.conv2 = Inception3x3Branch(
in_channels=mid_channels,
out_channels=out_channels,
mid_channels=mid_channels)
self.pool2 = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=0,
ceil_mode=True)
def forward(self, x):
x = self.conv1(x)
x = self.pool1(x)
x = self.conv2(x)
x = self.pool2(x)
return x
class InceptionBlock(nn.Module):
"""
BN-Inception unit.
Parameters:
----------
in_channels : int
Number of input channels.
mid1_channels_list : list of int
Number of pre-middle channels for branches.
mid2_channels_list : list of int
Number of middle channels for branches.
avg_pool : bool
Whether use average pooling or max pooling.
bias : bool
Whether the convolution layer uses a bias vector.
use_bn : bool
Whether to use BatchNorm layers.
"""
def __init__(self,
in_channels,
mid1_channels_list,
mid2_channels_list,
avg_pool,
bias,
use_bn):
super(InceptionBlock, self).__init__()
assert (len(mid1_channels_list) == 2)
assert (len(mid2_channels_list) == 4)
self.branches = Concurrent()
self.branches.add_module("branch1", conv1x1_block(
in_channels=in_channels,
out_channels=mid2_channels_list[0],
bias=bias,
use_bn=use_bn))
self.branches.add_module("branch2", Inception3x3Branch(
in_channels=in_channels,
out_channels=mid2_channels_list[1],
mid_channels=mid1_channels_list[0],
bias=bias,
use_bn=use_bn))
self.branches.add_module("branch3", InceptionDouble3x3Branch(
in_channels=in_channels,
out_channels=mid2_channels_list[2],
mid_channels=mid1_channels_list[1],
bias=bias,
use_bn=use_bn))
self.branches.add_module("branch4", InceptionPoolBranch(
in_channels=in_channels,
out_channels=mid2_channels_list[3],
avg_pool=avg_pool,
bias=bias,
use_bn=use_bn))
def forward(self, x):
x = self.branches(x)
return x
class ReductionBlock(nn.Module):
"""
BN-Inception reduction block.
Parameters:
----------
in_channels : int
Number of input channels.
mid1_channels_list : list of int
Number of pre-middle channels for branches.
mid2_channels_list : list of int
Number of middle channels for branches.
bias : bool
Whether the convolution layer uses a bias vector.
use_bn : bool
Whether to use BatchNorm layers.
"""
def __init__(self,
in_channels,
mid1_channels_list,
mid2_channels_list,
bias,
use_bn):
super(ReductionBlock, self).__init__()
assert (len(mid1_channels_list) == 2)
assert (len(mid2_channels_list) == 4)
self.branches = Concurrent()
self.branches.add_module("branch1", Inception3x3Branch(
in_channels=in_channels,
out_channels=mid2_channels_list[1],
mid_channels=mid1_channels_list[0],
stride=2,
bias=bias,
use_bn=use_bn))
self.branches.add_module("branch2", InceptionDouble3x3Branch(
in_channels=in_channels,
out_channels=mid2_channels_list[2],
mid_channels=mid1_channels_list[1],
stride=2,
bias=bias,
use_bn=use_bn))
self.branches.add_module("branch3", nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=0,
ceil_mode=True))
def forward(self, x):
x = self.branches(x)
return x
class BNInception(nn.Module):
"""
BN-Inception model from 'Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate
Shift,' https://arxiv.org/abs/1502.03167.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels_list : list of int
Number of output channels for the initial unit.
mid1_channels_list : list of list of list of int
Number of pre-middle channels for each unit.
mid2_channels_list : list of list of list of int
Number of middle channels for each unit.
bias : bool, default True
Whether the convolution layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layers.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels_list,
mid1_channels_list,
mid2_channels_list,
bias=True,
use_bn=True,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(BNInception, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", StemBlock(
in_channels=in_channels,
out_channels=init_block_channels_list[1],
mid_channels=init_block_channels_list[0],
bias=bias,
use_bn=use_bn))
in_channels = init_block_channels_list[-1]
for i, channels_per_stage in enumerate(channels):
mid1_channels_list_i = mid1_channels_list[i]
mid2_channels_list_i = mid2_channels_list[i]
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
if (j == 0) and (i != 0):
stage.add_module("unit{}".format(j + 1), ReductionBlock(
in_channels=in_channels,
mid1_channels_list=mid1_channels_list_i[j],
mid2_channels_list=mid2_channels_list_i[j],
bias=bias,
use_bn=use_bn))
else:
avg_pool = (i != len(channels) - 1) or (j != len(channels_per_stage) - 1)
stage.add_module("unit{}".format(j + 1), InceptionBlock(
in_channels=in_channels,
mid1_channels_list=mid1_channels_list_i[j],
mid2_channels_list=mid2_channels_list_i[j],
avg_pool=avg_pool,
bias=bias,
use_bn=use_bn))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_bninception(model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create BN-Inception model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
init_block_channels_list = [64, 192]
channels = [[256, 320], [576, 576, 576, 608, 608], [1056, 1024, 1024]]
mid1_channels_list = [
[[64, 64],
[64, 64]],
[[128, 64], # 3c
[64, 96], # 4a
[96, 96], # 4a
[128, 128], # 4c
[128, 160]], # 4d
[[128, 192], # 4e
[192, 160], # 5a
[192, 192]],
]
mid2_channels_list = [
[[64, 64, 96, 32],
[64, 96, 96, 64]],
[[0, 160, 96, 0], # 3c
[224, 96, 128, 128], # 4a
[192, 128, 128, 128], # 4b
[160, 160, 160, 128], # 4c
[96, 192, 192, 128]], # 4d
[[0, 192, 256, 0], # 4e
[352, 320, 224, 128], # 5a
[352, 320, 224, 128]],
]
net = BNInception(
channels=channels,
init_block_channels_list=init_block_channels_list,
mid1_channels_list=mid1_channels_list,
mid2_channels_list=mid2_channels_list,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def bninception(**kwargs):
"""
BN-Inception model from 'Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate
Shift,' https://arxiv.org/abs/1502.03167.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_bninception(model_name="bninception", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
bninception,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != bninception or weight_count == 11295240)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 16,280 | 29.488764 | 115 | py |
null | qimera-main/pytorchcv/models/cbamresnet.py | """
CBAM-ResNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521.
"""
__all__ = ['CbamResNet', 'cbam_resnet18', 'cbam_resnet34', 'cbam_resnet50', 'cbam_resnet101', 'cbam_resnet152']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, conv7x7_block
from .resnet import ResInitBlock, ResBlock, ResBottleneck
class MLP(nn.Module):
"""
Multilayer perceptron block.
Parameters:
----------
channels : int
Number of input/output channels.
reduction_ratio : int, default 16
Channel reduction ratio.
"""
def __init__(self,
channels,
reduction_ratio=16):
super(MLP, self).__init__()
mid_channels = channels // reduction_ratio
self.fc1 = nn.Linear(
in_features=channels,
out_features=mid_channels)
self.activ = nn.ReLU(inplace=True)
self.fc2 = nn.Linear(
in_features=mid_channels,
out_features=channels)
def forward(self, x):
x = x.view(x.size(0), -1)
x = self.fc1(x)
x = self.activ(x)
x = self.fc2(x)
return x
class ChannelGate(nn.Module):
"""
CBAM channel gate block.
Parameters:
----------
channels : int
Number of input/output channels.
reduction_ratio : int, default 16
Channel reduction ratio.
"""
def __init__(self,
channels,
reduction_ratio=16):
super(ChannelGate, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(output_size=(1, 1))
self.max_pool = nn.AdaptiveMaxPool2d(output_size=(1, 1))
self.mlp = MLP(
channels=channels,
reduction_ratio=reduction_ratio)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
att1 = self.avg_pool(x)
att1 = self.mlp(att1)
att2 = self.max_pool(x)
att2 = self.mlp(att2)
att = att1 + att2
att = self.sigmoid(att)
att = att.unsqueeze(2).unsqueeze(3).expand_as(x)
x = x * att
return x
class SpatialGate(nn.Module):
"""
CBAM spatial gate block.
"""
def __init__(self):
super(SpatialGate, self).__init__()
self.conv = conv7x7_block(
in_channels=2,
out_channels=1,
activation=None)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
att1 = x.max(dim=1)[0].unsqueeze(1)
att2 = x.mean(dim=1).unsqueeze(1)
att = torch.cat((att1, att2), dim=1)
att = self.conv(att)
att = self.sigmoid(att)
x = x * att
return x
class CbamBlock(nn.Module):
"""
CBAM attention block for CBAM-ResNet.
Parameters:
----------
channels : int
Number of input/output channels.
reduction_ratio : int, default 16
Channel reduction ratio.
"""
def __init__(self,
channels,
reduction_ratio=16):
super(CbamBlock, self).__init__()
self.ch_gate = ChannelGate(
channels=channels,
reduction_ratio=reduction_ratio)
self.sp_gate = SpatialGate()
def forward(self, x):
x = self.ch_gate(x)
x = self.sp_gate(x)
return x
class CbamResUnit(nn.Module):
"""
CBAM-ResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
"""
def __init__(self,
in_channels,
out_channels,
stride,
bottleneck):
super(CbamResUnit, self).__init__()
self.resize_identity = (in_channels != out_channels) or (stride != 1)
if bottleneck:
self.body = ResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
conv1_stride=False)
else:
self.body = ResBlock(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
activation=None)
self.cbam = CbamBlock(channels=out_channels)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = self.cbam(x)
x = x + identity
x = self.activ(x)
return x
class CbamResNet(nn.Module):
"""
CBAM-ResNet model from 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(CbamResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), CbamResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_resnet(blocks,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create CBAM-ResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer in units.
use_se : bool
Whether to use SE block.
width_scale : float
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 18:
layers = [2, 2, 2, 2]
elif blocks == 34:
layers = [3, 4, 6, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
else:
raise ValueError("Unsupported CBAM-ResNet with number of blocks: {}".format(blocks))
init_block_channels = 64
if blocks < 50:
channels_per_layers = [64, 128, 256, 512]
bottleneck = False
else:
channels_per_layers = [256, 512, 1024, 2048]
bottleneck = True
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = CbamResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def cbam_resnet18(**kwargs):
"""
CBAM-ResNet-18 model from 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=18, model_name="cbam_resnet18", **kwargs)
def cbam_resnet34(**kwargs):
"""
CBAM-ResNet-34 model from 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=34, model_name="cbam_resnet34", **kwargs)
def cbam_resnet50(**kwargs):
"""
CBAM-ResNet-50 model from 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=50, model_name="cbam_resnet50", **kwargs)
def cbam_resnet101(**kwargs):
"""
CBAM-ResNet-101 model from 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=101, model_name="cbam_resnet101", **kwargs)
def cbam_resnet152(**kwargs):
"""
CBAM-ResNet-152 model from 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=152, model_name="cbam_resnet152", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
cbam_resnet18,
cbam_resnet34,
cbam_resnet50,
cbam_resnet101,
cbam_resnet152,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != cbam_resnet18 or weight_count == 11779392)
assert (model != cbam_resnet34 or weight_count == 21960468)
assert (model != cbam_resnet50 or weight_count == 28089624)
assert (model != cbam_resnet101 or weight_count == 49330172)
assert (model != cbam_resnet152 or weight_count == 66826848)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 12,908 | 28.405467 | 115 | py |
null | qimera-main/pytorchcv/models/channelnet.py | """
ChannelNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'ChannelNets: Compact and Efficient Convolutional Neural Networks via Channel-Wise Convolutions,'
https://arxiv.org/abs/1809.01330.
"""
__all__ = ['ChannelNet', 'channelnet']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
def dwconv3x3(in_channels,
out_channels,
stride,
bias=False):
"""
3x3 depthwise version of the standard convolution layer.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
bias : bool, default False
Whether the layer uses a bias vector.
"""
return nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=stride,
padding=1,
groups=out_channels,
bias=bias)
class ChannetConv(nn.Module):
"""
ChannelNet specific convolution block with Batch normalization and ReLU6 activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
bias : bool, default False
Whether the layer uses a bias vector.
dropout_rate : float, default 0.0
Dropout rate.
activate : bool, default True
Whether activate the convolution block.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
dilation=1,
groups=1,
bias=False,
dropout_rate=0.0,
activate=True):
super(ChannetConv, self).__init__()
self.use_dropout = (dropout_rate > 0.0)
self.activate = activate
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
groups=groups,
bias=bias)
if self.use_dropout:
self.dropout = nn.Dropout(p=dropout_rate)
self.bn = nn.BatchNorm2d(num_features=out_channels)
if self.activate:
self.activ = nn.ReLU6(inplace=True)
def forward(self, x):
x = self.conv(x)
if self.use_dropout:
x = self.dropout(x)
x = self.bn(x)
if self.activate:
x = self.activ(x)
return x
def channet_conv1x1(in_channels,
out_channels,
stride=1,
groups=1,
bias=False,
dropout_rate=0.0,
activate=True):
"""
1x1 version of ChannelNet specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
groups : int, default 1
Number of groups.
bias : bool, default False
Whether the layer uses a bias vector.
dropout_rate : float, default 0.0
Dropout rate.
activate : bool, default True
Whether activate the convolution block.
"""
return ChannetConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
stride=stride,
padding=0,
groups=groups,
bias=bias,
dropout_rate=dropout_rate,
activate=activate)
def channet_conv3x3(in_channels,
out_channels,
stride,
padding=1,
dilation=1,
groups=1,
bias=False,
dropout_rate=0.0,
activate=True):
"""
3x3 version of the standard convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
bias : bool, default False
Whether the layer uses a bias vector.
dropout_rate : float, default 0.0
Dropout rate.
activate : bool, default True
Whether activate the convolution block.
"""
return ChannetConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=stride,
padding=padding,
dilation=dilation,
groups=groups,
bias=bias,
dropout_rate=dropout_rate,
activate=activate)
class ChannetDwsConvBlock(nn.Module):
"""
ChannelNet specific depthwise separable convolution block with BatchNorms and activations at last convolution
layers.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
groups : int, default 1
Number of groups.
dropout_rate : float, default 0.0
Dropout rate.
"""
def __init__(self,
in_channels,
out_channels,
stride,
groups=1,
dropout_rate=0.0):
super(ChannetDwsConvBlock, self).__init__()
self.dw_conv = dwconv3x3(
in_channels=in_channels,
out_channels=in_channels,
stride=stride)
self.pw_conv = channet_conv1x1(
in_channels=in_channels,
out_channels=out_channels,
groups=groups,
dropout_rate=dropout_rate)
def forward(self, x):
x = self.dw_conv(x)
x = self.pw_conv(x)
return x
class SimpleGroupBlock(nn.Module):
"""
ChannelNet specific block with a sequence of depthwise separable group convolution layers.
Parameters:
----------
channels : int
Number of input/output channels.
multi_blocks : int
Number of DWS layers in the sequence.
groups : int
Number of groups.
dropout_rate : float
Dropout rate.
"""
def __init__(self,
channels,
multi_blocks,
groups,
dropout_rate):
super(SimpleGroupBlock, self).__init__()
self.blocks = nn.Sequential()
for i in range(multi_blocks):
self.blocks.add_module("block{}".format(i + 1), ChannetDwsConvBlock(
in_channels=channels,
out_channels=channels,
stride=1,
groups=groups,
dropout_rate=dropout_rate))
def forward(self, x):
x = self.blocks(x)
return x
class ChannelwiseConv2d(nn.Module):
"""
ChannelNet specific block with channel-wise convolution.
Parameters:
----------
groups : int
Number of groups.
dropout_rate : float
Dropout rate.
"""
def __init__(self,
groups,
dropout_rate):
super(ChannelwiseConv2d, self).__init__()
self.use_dropout = (dropout_rate > 0.0)
self.conv = nn.Conv3d(
in_channels=1,
out_channels=groups,
kernel_size=(4 * groups, 1, 1),
stride=(groups, 1, 1),
padding=(2 * groups - 1, 0, 0),
bias=False)
if self.use_dropout:
self.dropout = nn.Dropout(p=dropout_rate)
def forward(self, x):
batch, channels, height, width = x.size()
x = x.unsqueeze(dim=1)
x = self.conv(x)
if self.use_dropout:
x = self.dropout(x)
x = x.view(batch, channels, height, width)
return x
class ConvGroupBlock(nn.Module):
"""
ChannelNet specific block with a combination of channel-wise convolution, depthwise separable group convolutions.
Parameters:
----------
channels : int
Number of input/output channels.
multi_blocks : int
Number of DWS layers in the sequence.
groups : int
Number of groups.
dropout_rate : float
Dropout rate.
"""
def __init__(self,
channels,
multi_blocks,
groups,
dropout_rate):
super(ConvGroupBlock, self).__init__()
self.conv = ChannelwiseConv2d(
groups=groups,
dropout_rate=dropout_rate)
self.block = SimpleGroupBlock(
channels=channels,
multi_blocks=multi_blocks,
groups=groups,
dropout_rate=dropout_rate)
def forward(self, x):
x = self.conv(x)
x = self.block(x)
return x
class ChannetUnit(nn.Module):
"""
ChannelNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels_list : tuple/list of 2 int
Number of output channels for each sub-block.
strides : int or tuple/list of 2 int
Strides of the convolution.
multi_blocks : int
Number of DWS layers in the sequence.
groups : int
Number of groups.
dropout_rate : float
Dropout rate.
block_names : tuple/list of 2 str
Sub-block names.
merge_type : str
Type of sub-block output merging.
"""
def __init__(self,
in_channels,
out_channels_list,
strides,
multi_blocks,
groups,
dropout_rate,
block_names,
merge_type):
super(ChannetUnit, self).__init__()
assert (len(block_names) == 2)
assert (merge_type in ["seq", "add", "cat"])
self.merge_type = merge_type
self.blocks = nn.Sequential()
for i, (out_channels, block_name) in enumerate(zip(out_channels_list, block_names)):
stride_i = (strides if i == 0 else 1)
if block_name == "channet_conv3x3":
self.blocks.add_module("block{}".format(i + 1), channet_conv3x3(
in_channels=in_channels,
out_channels=out_channels,
stride=stride_i,
dropout_rate=dropout_rate,
activate=False))
elif block_name == "channet_dws_conv_block":
self.blocks.add_module("block{}".format(i + 1), ChannetDwsConvBlock(
in_channels=in_channels,
out_channels=out_channels,
stride=stride_i,
dropout_rate=dropout_rate))
elif block_name == "simple_group_block":
self.blocks.add_module("block{}".format(i + 1), SimpleGroupBlock(
channels=in_channels,
multi_blocks=multi_blocks,
groups=groups,
dropout_rate=dropout_rate))
elif block_name == "conv_group_block":
self.blocks.add_module("block{}".format(i + 1), ConvGroupBlock(
channels=in_channels,
multi_blocks=multi_blocks,
groups=groups,
dropout_rate=dropout_rate))
else:
raise NotImplementedError()
in_channels = out_channels
def forward(self, x):
x_outs = []
for block in self.blocks._modules.values():
x = block(x)
x_outs.append(x)
if self.merge_type == "add":
for i in range(len(x_outs) - 1):
x = x + x_outs[i]
elif self.merge_type == "cat":
x = torch.cat(tuple(x_outs), dim=1)
return x
class ChannelNet(nn.Module):
"""
ChannelNet model from 'ChannelNets: Compact and Efficient Convolutional Neural Networks via Channel-Wise
Convolutions,' https://arxiv.org/abs/1809.01330.
Parameters:
----------
channels : list of list of list of int
Number of output channels for each unit.
block_names : list of list of list of str
Names of blocks for each unit.
block_names : list of list of str
Merge types for each unit.
dropout_rate : float, default 0.0001
Dropout rate.
multi_blocks : int, default 2
Block count architectural parameter.
groups : int, default 2
Group count architectural parameter.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
block_names,
merge_types,
dropout_rate=0.0001,
multi_blocks=2,
groups=2,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(ChannelNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) else 1
stage.add_module("unit{}".format(j + 1), ChannetUnit(
in_channels=in_channels,
out_channels_list=out_channels,
strides=strides,
multi_blocks=multi_blocks,
groups=groups,
dropout_rate=dropout_rate,
block_names=block_names[i][j],
merge_type=merge_types[i][j]))
if merge_types[i][j] == "cat":
in_channels = sum(out_channels)
else:
in_channels = out_channels[-1]
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_channelnet(model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create ChannelNet model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
channels = [[[32, 64]], [[128, 128]], [[256, 256]], [[512, 512], [512, 512]], [[1024, 1024]]]
block_names = [[["channet_conv3x3", "channet_dws_conv_block"]],
[["channet_dws_conv_block", "channet_dws_conv_block"]],
[["channet_dws_conv_block", "channet_dws_conv_block"]],
[["channet_dws_conv_block", "simple_group_block"], ["conv_group_block", "conv_group_block"]],
[["channet_dws_conv_block", "channet_dws_conv_block"]]]
merge_types = [["cat"], ["cat"], ["cat"], ["add", "add"], ["seq"]]
net = ChannelNet(
channels=channels,
block_names=block_names,
merge_types=merge_types,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def channelnet(**kwargs):
"""
ChannelNet model from 'ChannelNets: Compact and Efficient Convolutional Neural Networks via Channel-Wise
Convolutions,' https://arxiv.org/abs/1809.01330.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_channelnet(model_name="channelnet", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
channelnet,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != channelnet or weight_count == 3875112)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 18,471 | 29.633499 | 117 | py |
null | qimera-main/pytorchcv/models/common.py | """
Common routines for models in PyTorch.
"""
__all__ = ['round_channels', 'Swish', 'HSigmoid', 'HSwish', 'get_activation_layer', 'conv1x1', 'conv3x3',
'depthwise_conv3x3', 'ConvBlock', 'conv1x1_block', 'conv3x3_block', 'conv7x7_block', 'dwconv3x3_block',
'dwconv5x5_block', 'dwsconv3x3_block', 'PreConvBlock', 'pre_conv1x1_block', 'pre_conv3x3_block',
'ChannelShuffle', 'ChannelShuffle2', 'SEBlock', 'IBN', 'Identity', 'DualPathSequential', 'Concurrent',
'ParametricSequential', 'ParametricConcurrent', 'Hourglass', 'SesquialteralHourglass',
'MultiOutputSequential', 'Flatten']
import math
from inspect import isfunction
import torch
import torch.nn as nn
import torch.nn.functional as F
def round_channels(channels,
divisor=8):
"""
Round weighted channel number (make divisible operation).
Parameters:
----------
channels : int or float
Original number of channels.
divisor : int, default 8
Alignment value.
Returns
-------
int
Weighted number of channels.
"""
rounded_channels = max(int(channels + divisor / 2.0) // divisor * divisor, divisor)
if float(rounded_channels) < 0.9 * channels:
rounded_channels += divisor
return rounded_channels
class Swish(nn.Module):
"""
Swish activation function from 'Searching for Activation Functions,' https://arxiv.org/abs/1710.05941.
"""
def forward(self, x):
return x * torch.sigmoid(x)
class HSigmoid(nn.Module):
"""
Approximated sigmoid function, so-called hard-version of sigmoid from 'Searching for MobileNetV3,'
https://arxiv.org/abs/1905.02244.
"""
def forward(self, x):
return F.relu6(x + 3.0, inplace=True) / 6.0
class HSwish(nn.Module):
"""
H-Swish activation function from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
Parameters:
----------
inplace : bool
Whether to use inplace version of the module.
"""
def __init__(self, inplace=False):
super(HSwish, self).__init__()
self.inplace = inplace
def forward(self, x):
return x * F.relu6(x + 3.0, inplace=self.inplace) / 6.0
def get_activation_layer(activation):
"""
Create activation layer from string/function.
Parameters:
----------
activation : function, or str, or nn.Module
Activation function or name of activation function.
Returns
-------
nn.Module
Activation layer.
"""
assert (activation is not None)
if isfunction(activation):
return activation()
elif isinstance(activation, str):
if activation == "relu":
return nn.ReLU(inplace=True)
elif activation == "relu6":
return nn.ReLU6(inplace=True)
elif activation == "swish":
return Swish()
elif activation == "hswish":
return HSwish(inplace=True)
else:
raise NotImplementedError()
else:
assert (isinstance(activation, nn.Module))
return activation
def conv1x1(in_channels,
out_channels,
stride=1,
groups=1,
bias=False):
"""
Convolution 1x1 layer.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
groups : int, default 1
Number of groups.
bias : bool, default False
Whether the layer uses a bias vector.
"""
return nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
stride=stride,
groups=groups,
bias=bias)
def conv3x3(in_channels,
out_channels,
stride=1,
padding=1,
dilation=1,
groups=1,
bias=False):
"""
Convolution 3x3 layer.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
groups : int, default 1
Number of groups.
bias : bool, default False
Whether the layer uses a bias vector.
"""
return nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=stride,
padding=padding,
dilation=dilation,
groups=groups,
bias=bias)
def depthwise_conv3x3(channels,
stride):
"""
Depthwise convolution 3x3 layer.
Parameters:
----------
channels : int
Number of input/output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
"""
return nn.Conv2d(
in_channels=channels,
out_channels=channels,
kernel_size=3,
stride=stride,
padding=1,
groups=channels,
bias=False)
class ConvBlock(nn.Module):
"""
Standard convolution block with Batch normalization and activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
bias : bool, default False
Whether the layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layer.
bn_eps : float, default 1e-5
Small float added to variance in Batch norm.
activation : function or str or None, default nn.ReLU(inplace=True)
Activation function or name of activation function.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
dilation=1,
groups=1,
bias=False,
use_bn=True,
bn_eps=1e-5,
activation=(lambda: nn.ReLU(inplace=True))):
super(ConvBlock, self).__init__()
self.activate = (activation is not None)
self.use_bn = use_bn
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
groups=groups,
bias=bias)
if self.use_bn:
self.bn = nn.BatchNorm2d(
num_features=out_channels,
eps=bn_eps)
if self.activate:
self.activ = get_activation_layer(activation)
def forward(self, x):
x = self.conv(x)
if self.use_bn:
x = self.bn(x)
if self.activate:
x = self.activ(x)
return x
def conv1x1_block(in_channels,
out_channels,
stride=1,
padding=0,
groups=1,
bias=False,
use_bn=True,
bn_eps=1e-5,
activation=(lambda: nn.ReLU(inplace=True))):
"""
1x1 version of the standard convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 0
Padding value for convolution layer.
groups : int, default 1
Number of groups.
bias : bool, default False
Whether the layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layer.
bn_eps : float, default 1e-5
Small float added to variance in Batch norm.
activation : function or str or None, default nn.ReLU(inplace=True)
Activation function or name of activation function.
"""
return ConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
stride=stride,
padding=padding,
groups=groups,
bias=bias,
use_bn=use_bn,
bn_eps=bn_eps,
activation=activation)
def conv3x3_block(in_channels,
out_channels,
stride=1,
padding=1,
dilation=1,
groups=1,
bias=False,
use_bn=True,
bn_eps=1e-5,
activation=(lambda: nn.ReLU(inplace=True))):
"""
3x3 version of the standard convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
bias : bool, default False
Whether the layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layer.
bn_eps : float, default 1e-5
Small float added to variance in Batch norm.
activation : function or str or None, default nn.ReLU(inplace=True)
Activation function or name of activation function.
"""
return ConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=stride,
padding=padding,
dilation=dilation,
groups=groups,
bias=bias,
use_bn=use_bn,
bn_eps=bn_eps,
activation=activation)
def conv5x5_block(in_channels,
out_channels,
stride=1,
padding=2,
dilation=1,
groups=1,
bias=False,
bn_eps=1e-5,
activation=(lambda: nn.ReLU(inplace=True))):
"""
5x5 version of the standard convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 2
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
bias : bool, default False
Whether the layer uses a bias vector.
bn_eps : float, default 1e-5
Small float added to variance in Batch norm.
activation : function or str or None, default nn.ReLU(inplace=True)
Activation function or name of activation function.
"""
return ConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=5,
stride=stride,
padding=padding,
dilation=dilation,
groups=groups,
bias=bias,
bn_eps=bn_eps,
activation=activation)
def conv7x7_block(in_channels,
out_channels,
stride=1,
padding=3,
bias=False,
use_bn=True,
activation=(lambda: nn.ReLU(inplace=True))):
"""
7x7 version of the standard convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 3
Padding value for convolution layer.
bias : bool, default False
Whether the layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layer.
activation : function or str or None, default nn.ReLU(inplace=True)
Activation function or name of activation function.
"""
return ConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=7,
stride=stride,
padding=padding,
bias=bias,
use_bn=use_bn,
activation=activation)
def dwconv_block(in_channels,
out_channels,
kernel_size,
stride=1,
padding=1,
dilation=1,
bias=False,
use_bn=True,
bn_eps=1e-5,
activation=(lambda: nn.ReLU(inplace=True))):
"""
Depthwise version of the standard convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
bias : bool, default False
Whether the layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layer.
bn_eps : float, default 1e-5
Small float added to variance in Batch norm.
activation : function or str or None, default nn.ReLU(inplace=True)
Activation function or name of activation function.
"""
return ConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
groups=out_channels,
bias=bias,
use_bn=use_bn,
bn_eps=bn_eps,
activation=activation)
def dwconv3x3_block(in_channels,
out_channels,
stride=1,
padding=1,
dilation=1,
bias=False,
bn_eps=1e-5,
activation=(lambda: nn.ReLU(inplace=True))):
"""
3x3 depthwise version of the standard convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
bias : bool, default False
Whether the layer uses a bias vector.
bn_eps : float, default 1e-5
Small float added to variance in Batch norm.
activation : function or str or None, default nn.ReLU(inplace=True)
Activation function or name of activation function.
"""
return dwconv_block(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=stride,
padding=padding,
dilation=dilation,
bias=bias,
bn_eps=bn_eps,
activation=activation)
def dwconv5x5_block(in_channels,
out_channels,
stride=1,
padding=2,
dilation=1,
bias=False,
bn_eps=1e-5,
activation=(lambda: nn.ReLU(inplace=True))):
"""
5x5 depthwise version of the standard convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 2
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
bias : bool, default False
Whether the layer uses a bias vector.
bn_eps : float, default 1e-5
Small float added to variance in Batch norm.
activation : function or str or None, default nn.ReLU(inplace=True)
Activation function or name of activation function.
"""
return dwconv_block(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=5,
stride=stride,
padding=padding,
dilation=dilation,
bias=bias,
bn_eps=bn_eps,
activation=activation)
class DwsConvBlock(nn.Module):
"""
Depthwise separable convolution block with BatchNorms and activations at each convolution layers.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
bias : bool, default False
Whether the layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layer.
bn_eps : float, default 1e-5
Small float added to variance in Batch norm.
activation : function or str or None, default nn.ReLU(inplace=True)
Activation function or name of activation function.
activate : bool, default True
Whether activate the convolution block.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
dilation=1,
bias=False,
use_bn=True,
bn_eps=1e-5,
activation=(lambda: nn.ReLU(inplace=True))):
super(DwsConvBlock, self).__init__()
self.dw_conv = dwconv_block(
in_channels=in_channels,
out_channels=in_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
bias=bias,
use_bn=use_bn,
bn_eps=bn_eps,
activation=activation)
self.pw_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
bias=bias,
use_bn=use_bn,
bn_eps=bn_eps,
activation=activation)
def forward(self, x):
x = self.dw_conv(x)
x = self.pw_conv(x)
return x
def dwsconv3x3_block(in_channels,
out_channels,
stride=1,
padding=1,
dilation=1,
bias=False,
bn_eps=1e-5,
activation=(lambda: nn.ReLU(inplace=True))):
"""
3x3 depthwise separable version of the standard convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
bias : bool, default False
Whether the layer uses a bias vector.
bn_eps : float, default 1e-5
Small float added to variance in Batch norm.
activation : function or str or None, default nn.ReLU(inplace=True)
Activation function or name of activation function.
"""
return DwsConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=stride,
padding=padding,
dilation=dilation,
bias=bias,
bn_eps=bn_eps,
activation=activation)
class PreConvBlock(nn.Module):
"""
Convolution block with Batch normalization and ReLU pre-activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
bias : bool, default False
Whether the layer uses a bias vector.
return_preact : bool, default False
Whether return pre-activation. It's used by PreResNet.
activate : bool, default True
Whether activate the convolution block.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
dilation=1,
bias=False,
return_preact=False,
activate=True):
super(PreConvBlock, self).__init__()
self.return_preact = return_preact
self.activate = activate
self.bn = nn.BatchNorm2d(num_features=in_channels)
if self.activate:
self.activ = nn.ReLU(inplace=True)
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
bias=bias)
def forward(self, x):
x = self.bn(x)
if self.activate:
x = self.activ(x)
if self.return_preact:
x_pre_activ = x
x = self.conv(x)
if self.return_preact:
return x, x_pre_activ
else:
return x
def pre_conv1x1_block(in_channels,
out_channels,
stride=1,
bias=False,
return_preact=False,
activate=True):
"""
1x1 version of the pre-activated convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
bias : bool, default False
Whether the layer uses a bias vector.
return_preact : bool, default False
Whether return pre-activation.
activate : bool, default True
Whether activate the convolution block.
"""
return PreConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
stride=stride,
padding=0,
bias=bias,
return_preact=return_preact,
activate=activate)
def pre_conv3x3_block(in_channels,
out_channels,
stride=1,
padding=1,
dilation=1,
return_preact=False,
activate=True):
"""
3x3 version of the pre-activated convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
return_preact : bool, default False
Whether return pre-activation.
activate : bool, default True
Whether activate the convolution block.
"""
return PreConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=stride,
padding=padding,
dilation=dilation,
return_preact=return_preact,
activate=activate)
def channel_shuffle(x,
groups):
"""
Channel shuffle operation from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,'
https://arxiv.org/abs/1707.01083.
Parameters:
----------
x : Tensor
Input tensor.
groups : int
Number of groups.
Returns
-------
Tensor
Resulted tensor.
"""
batch, channels, height, width = x.size()
# assert (channels % groups == 0)
channels_per_group = channels // groups
x = x.view(batch, groups, channels_per_group, height, width)
x = torch.transpose(x, 1, 2).contiguous()
x = x.view(batch, channels, height, width)
return x
class ChannelShuffle(nn.Module):
"""
Channel shuffle layer. This is a wrapper over the same operation. It is designed to save the number of groups.
Parameters:
----------
channels : int
Number of channels.
groups : int
Number of groups.
"""
def __init__(self,
channels,
groups):
super(ChannelShuffle, self).__init__()
# assert (channels % groups == 0)
if channels % groups != 0:
raise ValueError('channels must be divisible by groups')
self.groups = groups
def forward(self, x):
return channel_shuffle(x, self.groups)
def channel_shuffle2(x,
groups):
"""
Channel shuffle operation from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,'
https://arxiv.org/abs/1707.01083. The alternative version.
Parameters:
----------
x : Tensor
Input tensor.
groups : int
Number of groups.
Returns
-------
Tensor
Resulted tensor.
"""
batch, channels, height, width = x.size()
# assert (channels % groups == 0)
channels_per_group = channels // groups
x = x.view(batch, channels_per_group, groups, height, width)
x = torch.transpose(x, 1, 2).contiguous()
x = x.view(batch, channels, height, width)
return x
class ChannelShuffle2(nn.Module):
"""
Channel shuffle layer. This is a wrapper over the same operation. It is designed to save the number of groups.
The alternative version.
Parameters:
----------
channels : int
Number of channels.
groups : int
Number of groups.
"""
def __init__(self,
channels,
groups):
super(ChannelShuffle2, self).__init__()
# assert (channels % groups == 0)
if channels % groups != 0:
raise ValueError('channels must be divisible by groups')
self.groups = groups
def forward(self, x):
return channel_shuffle2(x, self.groups)
class SEBlock(nn.Module):
"""
Squeeze-and-Excitation block from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
channels : int
Number of channels.
reduction : int, default 16
Squeeze reduction value.
approx_sigmoid : bool, default False
Whether to use approximated sigmoid function.
round_mid : bool, default False
Whether to round middle channel number (make divisible by 8).
activation : function, or str, or nn.Module
Activation function or name of activation function.
"""
def __init__(self,
channels,
reduction=16,
approx_sigmoid=False,
round_mid=False,
activation=(lambda: nn.ReLU(inplace=True))):
super(SEBlock, self).__init__()
mid_channels = channels // reduction if not round_mid else round_channels(float(channels) / reduction)
self.pool = nn.AdaptiveAvgPool2d(output_size=1)
self.conv1 = conv1x1(
in_channels=channels,
out_channels=mid_channels,
bias=True)
self.activ = get_activation_layer(activation)
self.conv2 = conv1x1(
in_channels=mid_channels,
out_channels=channels,
bias=True)
self.sigmoid = HSigmoid() if approx_sigmoid else nn.Sigmoid()
def forward(self, x):
w = self.pool(x)
w = self.conv1(w)
w = self.activ(w)
w = self.conv2(w)
w = self.sigmoid(w)
x = x * w
return x
class IBN(nn.Module):
"""
Instance-Batch Normalization block from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
Parameters:
----------
channels : int
Number of channels.
inst_fraction : float, default 0.5
The first fraction of channels for normalization.
inst_first : bool, default True
Whether instance normalization be on the first part of channels.
"""
def __init__(self,
channels,
first_fraction=0.5,
inst_first=True):
super(IBN, self).__init__()
self.inst_first = inst_first
h1_channels = int(math.floor(channels * first_fraction))
h2_channels = channels - h1_channels
self.split_sections = [h1_channels, h2_channels]
if self.inst_first:
self.inst_norm = nn.InstanceNorm2d(
num_features=h1_channels,
affine=True)
self.batch_norm = nn.BatchNorm2d(num_features=h2_channels)
else:
self.batch_norm = nn.BatchNorm2d(num_features=h1_channels)
self.inst_norm = nn.InstanceNorm2d(
num_features=h2_channels,
affine=True)
def forward(self, x):
x1, x2 = torch.split(x, split_size_or_sections=self.split_sections, dim=1)
if self.inst_first:
x1 = self.inst_norm(x1.contiguous())
x2 = self.batch_norm(x2.contiguous())
else:
x1 = self.batch_norm(x1.contiguous())
x2 = self.inst_norm(x2.contiguous())
x = torch.cat((x1, x2), dim=1)
return x
class Identity(nn.Module):
"""
Identity block.
"""
def __init__(self):
super(Identity, self).__init__()
def forward(self, x):
return x
class DualPathSequential(nn.Sequential):
"""
A sequential container for modules with dual inputs/outputs.
Modules will be executed in the order they are added.
Parameters:
----------
return_two : bool, default True
Whether to return two output after execution.
first_ordinals : int, default 0
Number of the first modules with single input/output.
last_ordinals : int, default 0
Number of the final modules with single input/output.
dual_path_scheme : function
Scheme of dual path response for a module.
dual_path_scheme_ordinal : function
Scheme of dual path response for an ordinal module.
"""
def __init__(self,
return_two=True,
first_ordinals=0,
last_ordinals=0,
dual_path_scheme=(lambda module, x1, x2: module(x1, x2)),
dual_path_scheme_ordinal=(lambda module, x1, x2: (module(x1), x2))):
super(DualPathSequential, self).__init__()
self.return_two = return_two
self.first_ordinals = first_ordinals
self.last_ordinals = last_ordinals
self.dual_path_scheme = dual_path_scheme
self.dual_path_scheme_ordinal = dual_path_scheme_ordinal
def forward(self, x1, x2=None):
length = len(self._modules.values())
for i, module in enumerate(self._modules.values()):
if (i < self.first_ordinals) or (i >= length - self.last_ordinals):
x1, x2 = self.dual_path_scheme_ordinal(module, x1, x2)
else:
x1, x2 = self.dual_path_scheme(module, x1, x2)
if self.return_two:
return x1, x2
else:
return x1
class Concurrent(nn.Sequential):
"""
A container for concatenation of modules on the base of the sequential container.
Parameters:
----------
axis : int, default 1
The axis on which to concatenate the outputs.
stack : bool, default False
Whether to concatenate tensors along a new dimension.
"""
def __init__(self,
axis=1,
stack=False):
super(Concurrent, self).__init__()
self.axis = axis
self.stack = stack
def forward(self, x):
out = []
for module in self._modules.values():
out.append(module(x))
if self.stack:
out = torch.stack(tuple(out), dim=self.axis)
else:
out = torch.cat(tuple(out), dim=self.axis)
return out
class ParametricSequential(nn.Sequential):
"""
A sequential container for modules with parameters.
Modules will be executed in the order they are added.
"""
def __init__(self, *args):
super(ParametricSequential, self).__init__(*args)
def forward(self, x, **kwargs):
for module in self._modules.values():
x = module(x, **kwargs)
return x
class ParametricConcurrent(nn.Sequential):
"""
A container for concatenation of modules with parameters.
Parameters:
----------
axis : int, default 1
The axis on which to concatenate the outputs.
"""
def __init__(self, axis=1):
super(ParametricConcurrent, self).__init__()
self.axis = axis
def forward(self, x, **kwargs):
out = []
for module in self._modules.values():
out.append(module(x, **kwargs))
out = torch.cat(tuple(out), dim=self.axis)
return out
class Hourglass(nn.Module):
"""
A hourglass block.
Parameters:
----------
down_seq : nn.Sequential
Down modules as sequential.
up_seq : nn.Sequential
Up modules as sequential.
skip_seq : nn.Sequential
Skip connection modules as sequential.
merge_type : str, default 'add'
Type of concatenation of up and skip outputs.
return_first_skip : bool, default False
Whether return the first skip connection output. Used in ResAttNet.
"""
def __init__(self,
down_seq,
up_seq,
skip_seq,
merge_type="add",
return_first_skip=False):
super(Hourglass, self).__init__()
assert (len(up_seq) == len(down_seq))
assert (len(skip_seq) == len(down_seq))
assert (merge_type in ["add"])
self.merge_type = merge_type
self.return_first_skip = return_first_skip
self.depth = len(down_seq)
self.down_seq = down_seq
self.up_seq = up_seq
self.skip_seq = skip_seq
def forward(self, x, **kwargs):
y = None
down_outs = [x]
for down_module in self.down_seq._modules.values():
x = down_module(x)
down_outs.append(x)
for i in range(len(down_outs)):
if i != 0:
y = down_outs[self.depth - i]
skip_module = self.skip_seq[self.depth - i]
y = skip_module(y)
if (y is not None) and (self.merge_type == "add"):
x = x + y
if i != len(down_outs) - 1:
up_module = self.up_seq[self.depth - 1 - i]
x = up_module(x)
if self.return_first_skip:
return x, y
else:
return x
class SesquialteralHourglass(nn.Module):
"""
A sesquialteral hourglass block.
Parameters:
----------
down1_seq : nn.Sequential
The first down modules as sequential.
skip1_seq : nn.Sequential
The first skip connection modules as sequential.
up_seq : nn.Sequential
Up modules as sequential.
skip2_seq : nn.Sequential
The second skip connection modules as sequential.
down2_seq : nn.Sequential
The second down modules as sequential.
merge_type : str, default 'con'
Type of concatenation of up and skip outputs.
"""
def __init__(self,
down1_seq,
skip1_seq,
up_seq,
skip2_seq,
down2_seq,
merge_type="cat"):
super(SesquialteralHourglass, self).__init__()
assert (len(down1_seq) == len(up_seq))
assert (len(down1_seq) == len(down2_seq))
assert (len(skip1_seq) == len(skip2_seq))
assert (len(down1_seq) == len(skip1_seq) - 1)
assert (merge_type in ["cat", "add"])
self.merge_type = merge_type
self.depth = len(down1_seq)
self.down1_seq = down1_seq
self.skip1_seq = skip1_seq
self.up_seq = up_seq
self.skip2_seq = skip2_seq
self.down2_seq = down2_seq
def _merge(self, x, y):
if y is not None:
if self.merge_type == "cat":
x = torch.cat((x, y), dim=1)
elif self.merge_type == "add":
x = x + y
return x
def forward(self, x, **kwargs):
y = self.skip1_seq[0](x)
skip1_outs = [y]
for i in range(self.depth):
x = self.down1_seq[i](x)
y = self.skip1_seq[i + 1](x)
skip1_outs.append(y)
x = skip1_outs[self.depth]
y = self.skip2_seq[0](x)
skip2_outs = [y]
for i in range(self.depth):
x = self.up_seq[i](x)
y = skip1_outs[self.depth - 1 - i]
x = self._merge(x, y)
y = self.skip2_seq[i + 1](x)
skip2_outs.append(y)
x = self.skip2_seq[self.depth](x)
for i in range(self.depth):
x = self.down2_seq[i](x)
y = skip2_outs[self.depth - 1 - i]
x = self._merge(x, y)
return x
class MultiOutputSequential(nn.Sequential):
"""
A sequential container with multiple outputs.
Modules will be executed in the order they are added.
"""
def __init__(self):
super(MultiOutputSequential, self).__init__()
def forward(self, x):
outs = []
for module in self._modules.values():
x = module(x)
if hasattr(module, "do_output") and module.do_output:
outs.append(x)
return [x] + outs
class Flatten(nn.Module):
"""
Simple flatten module.
"""
def forward(self, x):
return x.view(x.size(0), -1)
| 39,422 | 29.395528 | 120 | py |
null | qimera-main/pytorchcv/models/condensenet.py | """
CondenseNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'CondenseNet: An Efficient DenseNet using Learned Group Convolutions,'
https://arxiv.org/abs/1711.09224.
"""
__all__ = ['CondenseNet', 'condensenet74_c4_g4', 'condensenet74_c8_g8']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from torch.autograd import Variable
from .common import ChannelShuffle
class CondenseSimpleConv(nn.Module):
"""
CondenseNet specific simple convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
groups : int
Number of groups.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
groups):
super(CondenseSimpleConv, self).__init__()
self.bn = nn.BatchNorm2d(num_features=in_channels)
self.activ = nn.ReLU(inplace=True)
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
groups=groups,
bias=False)
def forward(self, x):
x = self.bn(x)
x = self.activ(x)
x = self.conv(x)
return x
def condense_simple_conv3x3(in_channels,
out_channels,
groups):
"""
3x3 version of the CondenseNet specific simple convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
groups : int
Number of groups.
"""
return CondenseSimpleConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=1,
padding=1,
groups=groups)
class CondenseComplexConv(nn.Module):
"""
CondenseNet specific complex convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
groups : int
Number of groups.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
groups):
super(CondenseComplexConv, self).__init__()
self.bn = nn.BatchNorm2d(num_features=in_channels)
self.activ = nn.ReLU(inplace=True)
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
groups=groups,
bias=False)
self.c_shuffle = ChannelShuffle(
channels=out_channels,
groups=groups)
self.register_buffer('index', torch.LongTensor(in_channels))
self.index.fill_(0)
def forward(self, x):
x = torch.index_select(x, dim=1, index=Variable(self.index))
x = self.bn(x)
x = self.activ(x)
x = self.conv(x)
x = self.c_shuffle(x)
return x
def condense_complex_conv1x1(in_channels,
out_channels,
groups):
"""
1x1 version of the CondenseNet specific complex convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
groups : int
Number of groups.
"""
return CondenseComplexConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
stride=1,
padding=0,
groups=groups)
class CondenseUnit(nn.Module):
"""
CondenseNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
groups : int
Number of groups.
"""
def __init__(self,
in_channels,
out_channels,
groups):
super(CondenseUnit, self).__init__()
bottleneck_size = 4
inc_channels = out_channels - in_channels
mid_channels = inc_channels * bottleneck_size
self.conv1 = condense_complex_conv1x1(
in_channels=in_channels,
out_channels=mid_channels,
groups=groups)
self.conv2 = condense_simple_conv3x3(
in_channels=mid_channels,
out_channels=inc_channels,
groups=groups)
def forward(self, x):
identity = x
x = self.conv1(x)
x = self.conv2(x)
x = torch.cat((identity, x), dim=1)
return x
class TransitionBlock(nn.Module):
"""
CondenseNet's auxiliary block, which can be treated as the initial part of the DenseNet unit, triggered only in the
first unit of each stage.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self):
super(TransitionBlock, self).__init__()
self.pool = nn.AvgPool2d(
kernel_size=2,
stride=2,
padding=0)
def forward(self, x):
x = self.pool(x)
return x
class CondenseInitBlock(nn.Module):
"""
CondenseNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(CondenseInitBlock, self).__init__()
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=2,
padding=1,
bias=False)
def forward(self, x):
x = self.conv(x)
return x
class PostActivation(nn.Module):
"""
CondenseNet final block, which performs the same function of postactivation as in PreResNet.
Parameters:
----------
in_channels : int
Number of input channels.
"""
def __init__(self,
in_channels):
super(PostActivation, self).__init__()
self.bn = nn.BatchNorm2d(num_features=in_channels)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
x = self.bn(x)
x = self.activ(x)
return x
class CondenseLinear(nn.Module):
"""
CondenseNet specific linear block.
Parameters:
----------
in_features : int
Number of input channels.
out_features : int
Number of output channels.
drop_rate : float
Fraction of input channels for drop.
"""
def __init__(self,
in_features,
out_features,
drop_rate=0.5):
super(CondenseLinear, self).__init__()
drop_in_features = int(in_features * drop_rate)
self.linear = nn.Linear(
in_features=drop_in_features,
out_features=out_features)
self.register_buffer('index', torch.LongTensor(drop_in_features))
self.index.fill_(0)
def forward(self, x):
x = torch.index_select(x, dim=1, index=Variable(self.index))
x = self.linear(x)
return x
class CondenseNet(nn.Module):
"""
CondenseNet model (converted) from 'CondenseNet: An Efficient DenseNet using Learned Group Convolutions,'
https://arxiv.org/abs/1711.09224.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
groups : int
Number of groups in convolution layers.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
groups,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(CondenseNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", CondenseInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
if i != 0:
stage.add_module("trans{}".format(i + 1), TransitionBlock())
for j, out_channels in enumerate(channels_per_stage):
stage.add_module("unit{}".format(j + 1), CondenseUnit(
in_channels=in_channels,
out_channels=out_channels,
groups=groups))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('post_activ', PostActivation(in_channels=in_channels))
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = CondenseLinear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
elif isinstance(module, nn.BatchNorm2d):
init.constant_(module.weight, 1)
init.constant_(module.bias, 0)
elif isinstance(module, nn.Linear):
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_condensenet(num_layers,
groups=4,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create CondenseNet (converted) model with specific parameters.
Parameters:
----------
num_layers : int
Number of layers.
groups : int
Number of groups in convolution layers.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if num_layers == 74:
init_block_channels = 16
layers = [4, 6, 8, 10, 8]
growth_rates = [8, 16, 32, 64, 128]
else:
raise ValueError("Unsupported CondenseNet version with number of layers {}".format(num_layers))
from functools import reduce
channels = reduce(lambda xi, yi:
xi + [reduce(lambda xj, yj:
xj + [xj[-1] + yj],
[yi[1]] * yi[0],
[xi[-1][-1]])[1:]],
zip(layers, growth_rates),
[[init_block_channels]])[1:]
net = CondenseNet(
channels=channels,
init_block_channels=init_block_channels,
groups=groups,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def condensenet74_c4_g4(**kwargs):
"""
CondenseNet-74 (C=G=4) model (converted) from 'CondenseNet: An Efficient DenseNet using Learned Group Convolutions,'
https://arxiv.org/abs/1711.09224.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_condensenet(num_layers=74, groups=4, model_name="condensenet74_c4_g4", **kwargs)
def condensenet74_c8_g8(**kwargs):
"""
CondenseNet-74 (C=G=8) model (converted) from 'CondenseNet: An Efficient DenseNet using Learned Group Convolutions,'
https://arxiv.org/abs/1711.09224.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_condensenet(num_layers=74, groups=8, model_name="condensenet74_c8_g8", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
condensenet74_c4_g4,
condensenet74_c8_g8,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != condensenet74_c4_g4 or weight_count == 4773944)
assert (model != condensenet74_c8_g8 or weight_count == 2935416)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 14,732 | 28.059172 | 120 | py |
null | qimera-main/pytorchcv/models/darknet.py | """
DarkNet for ImageNet-1K, implemented in PyTorch.
Original source: 'Darknet: Open source neural networks in c,' https://github.com/pjreddie/darknet.
"""
__all__ = ['DarkNet', 'darknet_ref', 'darknet_tiny', 'darknet19']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, conv3x3_block
def dark_convYxY(in_channels,
out_channels,
alpha,
pointwise):
"""
DarkNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
alpha : float
Slope coefficient for Leaky ReLU activation.
pointwise : bool
Whether use 1x1 (pointwise) convolution or 3x3 convolution.
"""
if pointwise:
return conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
activation=nn.LeakyReLU(
negative_slope=alpha,
inplace=True))
else:
return conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
activation=nn.LeakyReLU(
negative_slope=alpha,
inplace=True))
class DarkNet(nn.Module):
"""
DarkNet model from 'Darknet: Open source neural networks in c,' https://github.com/pjreddie/darknet.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
odd_pointwise : bool
Whether pointwise convolution layer is used for each odd unit.
avg_pool_size : int
Window size of the final average pooling.
cls_activ : bool
Whether classification convolution layer uses an activation.
alpha : float, default 0.1
Slope coefficient for Leaky ReLU activation.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
odd_pointwise,
avg_pool_size,
cls_activ,
alpha=0.1,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(DarkNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stage.add_module("unit{}".format(j + 1), dark_convYxY(
in_channels=in_channels,
out_channels=out_channels,
alpha=alpha,
pointwise=(len(channels_per_stage) > 1) and not (((j + 1) % 2 == 1) ^ odd_pointwise)))
in_channels = out_channels
if i != len(channels) - 1:
stage.add_module("pool{}".format(i + 1), nn.MaxPool2d(
kernel_size=2,
stride=2))
self.features.add_module("stage{}".format(i + 1), stage)
self.output = nn.Sequential()
self.output.add_module("final_conv", nn.Conv2d(
in_channels=in_channels,
out_channels=num_classes,
kernel_size=1))
if cls_activ:
self.output.add_module("final_activ", nn.LeakyReLU(
negative_slope=alpha,
inplace=True))
self.output.add_module("final_pool", nn.AvgPool2d(
kernel_size=avg_pool_size,
stride=1))
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
if "final_conv" in name:
init.normal_(module.weight, mean=0.0, std=0.01)
else:
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = self.output(x)
x = x.view(x.size(0), -1)
return x
def get_darknet(version,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create DarkNet model with specific parameters.
Parameters:
----------
version : str
Version of SqueezeNet ('ref', 'tiny' or '19').
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if version == 'ref':
channels = [[16], [32], [64], [128], [256], [512], [1024]]
odd_pointwise = False
avg_pool_size = 3
cls_activ = True
elif version == 'tiny':
channels = [[16], [32], [16, 128, 16, 128], [32, 256, 32, 256], [64, 512, 64, 512, 128]]
odd_pointwise = True
avg_pool_size = 14
cls_activ = False
elif version == '19':
channels = [[32], [64], [128, 64, 128], [256, 128, 256], [512, 256, 512, 256, 512],
[1024, 512, 1024, 512, 1024]]
odd_pointwise = False
avg_pool_size = 7
cls_activ = False
else:
raise ValueError("Unsupported DarkNet version {}".format(version))
net = DarkNet(
channels=channels,
odd_pointwise=odd_pointwise,
avg_pool_size=avg_pool_size,
cls_activ=cls_activ,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def darknet_ref(**kwargs):
"""
DarkNet 'Reference' model from 'Darknet: Open source neural networks in c,' https://github.com/pjreddie/darknet.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_darknet(version="ref", model_name="darknet_ref", **kwargs)
def darknet_tiny(**kwargs):
"""
DarkNet Tiny model from 'Darknet: Open source neural networks in c,' https://github.com/pjreddie/darknet.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_darknet(version="tiny", model_name="darknet_tiny", **kwargs)
def darknet19(**kwargs):
"""
DarkNet-19 model from 'Darknet: Open source neural networks in c,' https://github.com/pjreddie/darknet.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_darknet(version="19", model_name="darknet19", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
pretrained = False
models = [
darknet_ref,
darknet_tiny,
darknet19,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != darknet_ref or weight_count == 7319416)
assert (model != darknet_tiny or weight_count == 1042104)
assert (model != darknet19 or weight_count == 20842376)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 8,529 | 30.360294 | 116 | py |
null | qimera-main/pytorchcv/models/darknet53.py | """
DarkNet-53 for ImageNet-1K, implemented in PyTorch.
Original source: 'YOLOv3: An Incremental Improvement,' https://arxiv.org/abs/1804.02767.
"""
__all__ = ['DarkNet53', 'darknet53']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, conv3x3_block
class DarkUnit(nn.Module):
"""
DarkNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
alpha : float
Slope coefficient for Leaky ReLU activation.
"""
def __init__(self,
in_channels,
out_channels,
alpha):
super(DarkUnit, self).__init__()
assert (out_channels % 2 == 0)
mid_channels = out_channels // 2
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
activation=nn.LeakyReLU(
negative_slope=alpha,
inplace=True))
self.conv2 = conv3x3_block(
in_channels=mid_channels,
out_channels=out_channels,
activation=nn.LeakyReLU(
negative_slope=alpha,
inplace=True))
def forward(self, x):
identity = x
x = self.conv1(x)
x = self.conv2(x)
return x + identity
class DarkNet53(nn.Module):
"""
DarkNet-53 model from 'YOLOv3: An Incremental Improvement,' https://arxiv.org/abs/1804.02767.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
alpha : float, default 0.1
Slope coefficient for Leaky ReLU activation.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
alpha=0.1,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(DarkNet53, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels,
activation=nn.LeakyReLU(
negative_slope=alpha,
inplace=True)))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
if j == 0:
stage.add_module("unit{}".format(j + 1), conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
stride=2,
activation=nn.LeakyReLU(
negative_slope=alpha,
inplace=True)))
else:
stage.add_module("unit{}".format(j + 1), DarkUnit(
in_channels=in_channels,
out_channels=out_channels,
alpha=alpha))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_darknet53(model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create DarkNet model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
init_block_channels = 32
layers = [2, 3, 9, 9, 5]
channels_per_layers = [64, 128, 256, 512, 1024]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = DarkNet53(
channels=channels,
init_block_channels=init_block_channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def darknet53(**kwargs):
"""
DarkNet-53 'Reference' model from 'YOLOv3: An Incremental Improvement,' https://arxiv.org/abs/1804.02767.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_darknet53(model_name="darknet53", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
darknet53,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != darknet53 or weight_count == 41609928)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 6,707 | 29.080717 | 115 | py |
null | qimera-main/pytorchcv/models/darts.py | """
DARTS for ImageNet-1K, implemented in PyTorch.
Original paper: 'DARTS: Differentiable Architecture Search,' https://arxiv.org/abs/1806.09055.
"""
__all__ = ['DARTS', 'darts']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1, Identity
from .nasnet import nasnet_dual_path_sequential
class DwsConv(nn.Module):
"""
Standard dilated depthwise separable convolution block with.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
dilation : int or tuple/list of 2 int
Dilation value for convolution layer.
bias : bool, default False
Whether the layers use a bias vector.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
dilation,
bias=False):
super(DwsConv, self).__init__()
self.dw_conv = nn.Conv2d(
in_channels=in_channels,
out_channels=in_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
groups=in_channels,
bias=bias)
self.pw_conv = conv1x1(
in_channels=in_channels,
out_channels=out_channels,
bias=bias)
def forward(self, x):
x = self.dw_conv(x)
x = self.pw_conv(x)
return x
class DartsConv(nn.Module):
"""
DARTS specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
activate : bool, default True
Whether activate the convolution block.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
activate=True):
super(DartsConv, self).__init__()
self.activate = activate
if self.activate:
self.activ = nn.ReLU(inplace=False)
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
bias=False)
self.bn = nn.BatchNorm2d(num_features=out_channels)
def forward(self, x):
if self.activate:
x = self.activ(x)
x = self.conv(x)
x = self.bn(x)
return x
def darts_conv1x1(in_channels,
out_channels,
activate=True):
"""
1x1 version of the DARTS specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
activate : bool, default True
Whether activate the convolution block.
"""
return DartsConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
stride=1,
padding=0,
activate=activate)
def darts_conv3x3_s2(in_channels,
out_channels,
activate=True):
"""
3x3 version of the DARTS specific convolution block with stride 2.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
activate : bool, default True
Whether activate the convolution block.
"""
return DartsConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=2,
padding=1,
activate=activate)
class DartsDwsConv(nn.Module):
"""
DARTS specific dilated convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
dilation : int or tuple/list of 2 int
Dilation value for convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
dilation):
super(DartsDwsConv, self).__init__()
self.activ = nn.ReLU(inplace=False)
self.conv = DwsConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
bias=False)
self.bn = nn.BatchNorm2d(num_features=out_channels)
def forward(self, x):
x = self.activ(x)
x = self.conv(x)
x = self.bn(x)
return x
class DartsDwsBranch(nn.Module):
"""
DARTS specific block with depthwise separable convolution layers.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding):
super(DartsDwsBranch, self).__init__()
mid_channels = in_channels
self.conv1 = DartsDwsConv(
in_channels=in_channels,
out_channels=mid_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=1)
self.conv2 = DartsDwsConv(
in_channels=mid_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=1,
padding=padding,
dilation=1)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class DartsReduceBranch(nn.Module):
"""
DARTS specific factorized reduce block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 2
Strides of the convolution.
"""
def __init__(self,
in_channels,
out_channels,
stride=2):
super(DartsReduceBranch, self).__init__()
assert (out_channels % 2 == 0)
mid_channels = out_channels // 2
self.activ = nn.ReLU(inplace=False)
self.conv1 = conv1x1(
in_channels=in_channels,
out_channels=mid_channels,
stride=stride)
self.conv2 = conv1x1(
in_channels=in_channels,
out_channels=mid_channels,
stride=stride)
self.bn = nn.BatchNorm2d(num_features=out_channels)
def forward(self, x):
x = self.activ(x)
x1 = self.conv1(x)
x = x[:, :, 1:, 1:].contiguous()
x2 = self.conv2(x)
x = torch.cat((x1, x2), dim=1)
x = self.bn(x)
return x
class Stem1Unit(nn.Module):
"""
DARTS Stem1 unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(Stem1Unit, self).__init__()
mid_channels = out_channels // 2
self.conv1 = darts_conv3x3_s2(
in_channels=in_channels,
out_channels=mid_channels,
activate=False)
self.conv2 = darts_conv3x3_s2(
in_channels=mid_channels,
out_channels=out_channels,
activate=True)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
return x
def stem2_unit(in_channels,
out_channels):
"""
DARTS Stem2 unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
return darts_conv3x3_s2(
in_channels=in_channels,
out_channels=out_channels,
activate=True)
def darts_maxpool3x3(channels,
stride):
"""
DARTS specific 3x3 Max pooling layer.
Parameters:
----------
channels : int
Number of input/output channels. Unused parameter.
stride : int or tuple/list of 2 int
Strides of the convolution.
"""
assert (channels > 0)
return nn.MaxPool2d(
kernel_size=3,
stride=stride,
padding=1)
def darts_skip_connection(channels,
stride):
"""
DARTS specific skip connection layer.
Parameters:
----------
channels : int
Number of input/output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
"""
assert (channels > 0)
if stride == 1:
return Identity()
else:
assert (stride == 2)
return DartsReduceBranch(
in_channels=channels,
out_channels=channels,
stride=stride)
def darts_dws_conv3x3(channels,
stride):
"""
3x3 version of DARTS specific dilated convolution block.
Parameters:
----------
channels : int
Number of input/output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
"""
return DartsDwsConv(
in_channels=channels,
out_channels=channels,
kernel_size=3,
stride=stride,
padding=2,
dilation=2)
def darts_dws_branch3x3(channels,
stride):
"""
3x3 version of DARTS specific dilated convolution branch.
Parameters:
----------
channels : int
Number of input/output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
"""
return DartsDwsBranch(
in_channels=channels,
out_channels=channels,
kernel_size=3,
stride=stride,
padding=1)
# Set of operations in genotype.
GENOTYPE_OPS = {
'max_pool_3x3': darts_maxpool3x3,
'skip_connect': darts_skip_connection,
'dil_conv_3x3': darts_dws_conv3x3,
'sep_conv_3x3': darts_dws_branch3x3,
}
class DartsMainBlock(nn.Module):
"""
DARTS main block, described by genotype.
Parameters:
----------
genotype : list of tuples (str, int)
List of genotype elements (operations and linked indices).
channels : int
Number of input/output channels.
reduction : bool
Whether use reduction.
"""
def __init__(self,
genotype,
channels,
reduction):
super(DartsMainBlock, self).__init__()
self.concat = [2, 3, 4, 5]
op_names, indices = zip(*genotype)
self.indices = indices
self.steps = len(op_names) // 2
self.ops = nn.ModuleList()
for name, index in zip(op_names, indices):
stride = 2 if reduction and index < 2 else 1
op = GENOTYPE_OPS[name](channels, stride)
self.ops += [op]
def forward(self, x, x_prev):
s0 = x_prev
s1 = x
states = [s0, s1]
for i in range(self.steps):
j1 = 2 * i
j2 = 2 * i + 1
op1 = self.ops[j1]
op2 = self.ops[j2]
y1 = states[self.indices[j1]]
y2 = states[self.indices[j2]]
y1 = op1(y1)
y2 = op2(y2)
s = y1 + y2
states += [s]
x_out = torch.cat([states[i] for i in self.concat], dim=1)
return x_out
class DartsUnit(nn.Module):
"""
DARTS unit.
Parameters:
----------
in_channels : int
Number of input channels.
prev_in_channels : int
Number of input channels in previous input.
out_channels : int
Number of output channels.
genotype : list of tuples (str, int)
List of genotype elements (operations and linked indices).
reduction : bool
Whether use reduction.
"""
def __init__(self,
in_channels,
prev_in_channels,
out_channels,
genotype,
reduction,
prev_reduction):
super(DartsUnit, self).__init__()
mid_channels = out_channels // 4
if prev_reduction:
self.preprocess_prev = DartsReduceBranch(
in_channels=prev_in_channels,
out_channels=mid_channels)
else:
self.preprocess_prev = darts_conv1x1(
in_channels=prev_in_channels,
out_channels=mid_channels)
self.preprocess = darts_conv1x1(
in_channels=in_channels,
out_channels=mid_channels)
self.body = DartsMainBlock(
genotype=genotype,
channels=mid_channels,
reduction=reduction)
def forward(self, x, x_prev):
x = self.preprocess(x)
x_prev = self.preprocess_prev(x_prev)
x_out = self.body(x, x_prev)
return x_out
class DARTS(nn.Module):
"""
DARTS model from 'DARTS: Differentiable Architecture Search,' https://arxiv.org/abs/1806.09055.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
stem_blocks_channels : int
Number of output channels for the Stem units.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
stem_blocks_channels,
normal_genotype,
reduce_genotype,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(DARTS, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nasnet_dual_path_sequential(
return_two=False,
first_ordinals=2,
last_ordinals=1)
self.features.add_module("stem1_unit", Stem1Unit(
in_channels=in_channels,
out_channels=stem_blocks_channels))
in_channels = stem_blocks_channels
self.features.add_module("stem2_unit", stem2_unit(
in_channels=in_channels,
out_channels=stem_blocks_channels))
prev_in_channels = in_channels
in_channels = stem_blocks_channels
for i, channels_per_stage in enumerate(channels):
stage = nasnet_dual_path_sequential()
for j, out_channels in enumerate(channels_per_stage):
reduction = (i != 0) and (j == 0)
prev_reduction = ((i == 0) and (j == 0)) or ((i != 0) and (j == 1))
genotype = reduce_genotype if reduction else normal_genotype
stage.add_module("unit{}".format(j + 1), DartsUnit(
in_channels=in_channels,
prev_in_channels=prev_in_channels,
out_channels=out_channels,
genotype=genotype,
reduction=reduction,
prev_reduction=prev_reduction))
prev_in_channels = in_channels
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_darts(model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create DARTS model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
stem_blocks_channels = 48
layers = [4, 5, 5]
channels_per_layers = [192, 384, 768]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
normal_genotype = [
('sep_conv_3x3', 0),
('sep_conv_3x3', 1),
('sep_conv_3x3', 0),
('sep_conv_3x3', 1),
('sep_conv_3x3', 1),
('skip_connect', 0),
('skip_connect', 0),
('dil_conv_3x3', 2)]
reduce_genotype = [
('max_pool_3x3', 0),
('max_pool_3x3', 1),
('skip_connect', 2),
('max_pool_3x3', 1),
('max_pool_3x3', 0),
('skip_connect', 2),
('skip_connect', 2),
('max_pool_3x3', 1)]
net = DARTS(
channels=channels,
stem_blocks_channels=stem_blocks_channels,
normal_genotype=normal_genotype,
reduce_genotype=reduce_genotype,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def darts(**kwargs):
"""
DARTS model from 'DARTS: Differentiable Architecture Search,' https://arxiv.org/abs/1806.09055.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_darts(model_name="darts", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
darts,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != darts or weight_count == 4718752)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 20,225 | 26.668947 | 115 | py |
null | qimera-main/pytorchcv/models/deeplabv3.py | """
DeepLabv3 for image segmentation, implemented in PyTorch.
Original paper: 'Rethinking Atrous Convolution for Semantic Image Segmentation,' https://arxiv.org/abs/1706.05587.
"""
__all__ = ['DeepLabv3', 'deeplabv3_resnetd50b_voc', 'deeplabv3_resnetd101b_voc', 'deeplabv3_resnetd152b_voc',
'deeplabv3_resnetd50b_coco', 'deeplabv3_resnetd101b_coco', 'deeplabv3_resnetd152b_coco',
'deeplabv3_resnetd50b_ade20k', 'deeplabv3_resnetd101b_ade20k', 'deeplabv3_resnetd50b_cityscapes',
'deeplabv3_resnetd101b_cityscapes']
import os
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from .common import conv1x1, conv1x1_block, conv3x3_block, Concurrent
from .resnetd import resnetd50b, resnetd101b, resnetd152b
class DeepLabv3FinalBlock(nn.Module):
"""
DeepLabv3 final block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bottleneck_factor : int, default 4
Bottleneck factor.
"""
def __init__(self,
in_channels,
out_channels,
bottleneck_factor=4):
super(DeepLabv3FinalBlock, self).__init__()
assert (in_channels % bottleneck_factor == 0)
mid_channels = in_channels // bottleneck_factor
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=mid_channels)
self.dropout = nn.Dropout(p=0.1, inplace=False)
self.conv2 = conv1x1(
in_channels=mid_channels,
out_channels=out_channels,
bias=True)
def forward(self, x, out_size):
x = self.conv1(x)
x = self.dropout(x)
x = self.conv2(x)
x = F.interpolate(x, size=out_size, mode="bilinear", align_corners=True)
return x
class ASPPAvgBranch(nn.Module):
"""
ASPP branch with average pooling.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
upscale_out_size : tuple of 2 int
Spatial size of output image for the bilinear upsampling operation.
"""
def __init__(self,
in_channels,
out_channels,
upscale_out_size):
super(ASPPAvgBranch, self).__init__()
self.upscale_out_size = upscale_out_size
self.pool = nn.AdaptiveAvgPool2d(1)
self.conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels)
def forward(self, x):
in_size = self.upscale_out_size if self.upscale_out_size is not None else x.shape[2:]
x = self.pool(x)
x = self.conv(x)
x = F.interpolate(x, size=in_size, mode="bilinear", align_corners=True)
return x
class AtrousSpatialPyramidPooling(nn.Module):
"""
Atrous Spatial Pyramid Pooling (ASPP) module.
Parameters:
----------
in_channels : int
Number of input channels.
upscale_out_size : tuple of 2 int
Spatial size of the input tensor for the bilinear upsampling operation.
"""
def __init__(self,
in_channels,
upscale_out_size):
super(AtrousSpatialPyramidPooling, self).__init__()
atrous_rates = [12, 24, 36]
assert (in_channels % 8 == 0)
mid_channels = in_channels // 8
project_in_channels = 5 * mid_channels
self.branches = Concurrent()
self.branches.add_module("branch1", conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels))
for i, atrous_rate in enumerate(atrous_rates):
self.branches.add_module("branch{}".format(i + 2), conv3x3_block(
in_channels=in_channels,
out_channels=mid_channels,
padding=atrous_rate,
dilation=atrous_rate))
self.branches.add_module("branch5", ASPPAvgBranch(
in_channels=in_channels,
out_channels=mid_channels,
upscale_out_size=upscale_out_size))
self.conv = conv1x1_block(
in_channels=project_in_channels,
out_channels=mid_channels)
self.dropout = nn.Dropout(p=0.5, inplace=False)
def forward(self, x):
x = self.branches(x)
x = self.conv(x)
x = self.dropout(x)
return x
class DeepLabv3(nn.Module):
"""
DeepLabv3 model from 'Rethinking Atrous Convolution for Semantic Image Segmentation,'
https://arxiv.org/abs/1706.05587.
Parameters:
----------
backbone : nn.Sequential
Feature extractor.
backbone_out_channels : int, default 2048
Number of output channels form feature extractor.
aux : bool, default False
Whether to output an auxiliary result.
fixed_size : bool, default True
Whether to expect fixed spatial size of input image.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (480, 480)
Spatial size of the expected input image.
num_classes : int, default 21
Number of segmentation classes.
"""
def __init__(self,
backbone,
backbone_out_channels=2048,
aux=False,
fixed_size=True,
in_channels=3,
in_size=(480, 480),
num_classes=21):
super(DeepLabv3, self).__init__()
assert (in_channels > 0)
self.in_size = in_size
self.num_classes = num_classes
self.aux = aux
self.fixed_size = fixed_size
self.backbone = backbone
pool_out_size = (self.in_size[0] // 8, self.in_size[1] // 8) if fixed_size else None
self.pool = AtrousSpatialPyramidPooling(
in_channels=backbone_out_channels,
upscale_out_size=pool_out_size)
pool_out_channels = backbone_out_channels // 8
self.final_block = DeepLabv3FinalBlock(
in_channels=pool_out_channels,
out_channels=num_classes,
bottleneck_factor=1)
if self.aux:
aux_out_channels = backbone_out_channels // 2
self.aux_block = DeepLabv3FinalBlock(
in_channels=aux_out_channels,
out_channels=num_classes,
bottleneck_factor=4)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
in_size = self.in_size if self.fixed_size else x.shape[2:]
x, y = self.backbone(x)
x = self.pool(x)
x = self.final_block(x, in_size)
if self.aux:
y = self.aux_block(y, in_size)
return x, y
else:
return x
def get_deeplabv3(backbone,
num_classes,
aux=False,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create DeepLabv3 model with specific parameters.
Parameters:
----------
backbone : nn.Sequential
Feature extractor.
num_classes : int
Number of segmentation classes.
aux : bool, default False
Whether to output an auxiliary result.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
net = DeepLabv3(
backbone=backbone,
num_classes=num_classes,
aux=aux,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def deeplabv3_resnetd50b_voc(pretrained_backbone=False, num_classes=21, aux=True, **kwargs):
"""
DeepLabv3 model on the base of ResNet(D)-50b for Pascal VOC from 'Rethinking Atrous Convolution for Semantic Image
Segmentation,' https://arxiv.org/abs/1706.05587.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 21
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_deeplabv3(backbone=backbone, num_classes=num_classes, aux=aux, model_name="deeplabv3_resnetd50b_voc",
**kwargs)
def deeplabv3_resnetd101b_voc(pretrained_backbone=False, num_classes=21, aux=True, **kwargs):
"""
DeepLabv3 model on the base of ResNet(D)-101b for Pascal VOC from 'Rethinking Atrous Convolution for Semantic Image
Segmentation,' https://arxiv.org/abs/1706.05587.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 21
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_deeplabv3(backbone=backbone, num_classes=num_classes, aux=aux, model_name="deeplabv3_resnetd101b_voc",
**kwargs)
def deeplabv3_resnetd152b_voc(pretrained_backbone=False, num_classes=21, aux=True, **kwargs):
"""
DeepLabv3 model on the base of ResNet(D)-152b for Pascal VOC from 'Rethinking Atrous Convolution for Semantic Image
Segmentation,' https://arxiv.org/abs/1706.05587.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 21
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd152b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_deeplabv3(backbone=backbone, num_classes=num_classes, aux=aux, model_name="deeplabv3_resnetd152b_voc",
**kwargs)
def deeplabv3_resnetd50b_coco(pretrained_backbone=False, num_classes=21, aux=True, **kwargs):
"""
DeepLabv3 model on the base of ResNet(D)-50b for COCO from 'Rethinking Atrous Convolution for Semantic Image
Segmentation,' https://arxiv.org/abs/1706.05587.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 21
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_deeplabv3(backbone=backbone, num_classes=num_classes, aux=aux, model_name="deeplabv3_resnetd50b_coco",
**kwargs)
def deeplabv3_resnetd101b_coco(pretrained_backbone=False, num_classes=21, aux=True, **kwargs):
"""
DeepLabv3 model on the base of ResNet(D)-101b for COCO from 'Rethinking Atrous Convolution for Semantic Image
Segmentation,' https://arxiv.org/abs/1706.05587.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 21
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_deeplabv3(backbone=backbone, num_classes=num_classes, aux=aux, model_name="deeplabv3_resnetd101b_coco",
**kwargs)
def deeplabv3_resnetd152b_coco(pretrained_backbone=False, num_classes=21, aux=True, **kwargs):
"""
DeepLabv3 model on the base of ResNet(D)-152b for COCO from 'Rethinking Atrous Convolution for Semantic Image
Segmentation,' https://arxiv.org/abs/1706.05587.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 21
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd152b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_deeplabv3(backbone=backbone, num_classes=num_classes, aux=aux, model_name="deeplabv3_resnetd152b_coco",
**kwargs)
def deeplabv3_resnetd50b_ade20k(pretrained_backbone=False, num_classes=150, aux=True, **kwargs):
"""
DeepLabv3 model on the base of ResNet(D)-50b for ADE20K from 'Rethinking Atrous Convolution for Semantic Image
Segmentation,' https://arxiv.org/abs/1706.05587.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 150
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_deeplabv3(backbone=backbone, num_classes=num_classes, aux=aux, model_name="deeplabv3_resnetd50b_ade20k",
**kwargs)
def deeplabv3_resnetd101b_ade20k(pretrained_backbone=False, num_classes=150, aux=True, **kwargs):
"""
DeepLabv3 model on the base of ResNet(D)-101b for ADE20K from 'Rethinking Atrous Convolution for Semantic Image
Segmentation,' https://arxiv.org/abs/1706.05587.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 150
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_deeplabv3(backbone=backbone, num_classes=num_classes, aux=aux, model_name="deeplabv3_resnetd101b_ade20k",
**kwargs)
def deeplabv3_resnetd50b_cityscapes(pretrained_backbone=False, num_classes=19, aux=True, **kwargs):
"""
DeepLabv3 model on the base of ResNet(D)-50b for Cityscapes from 'Rethinking Atrous Convolution for Semantic Image
Segmentation,' https://arxiv.org/abs/1706.05587.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 19
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_deeplabv3(backbone=backbone, num_classes=num_classes, aux=aux,
model_name="deeplabv3_resnetd50b_cityscapes", **kwargs)
def deeplabv3_resnetd101b_cityscapes(pretrained_backbone=False, num_classes=19, aux=True, **kwargs):
"""
DeepLabv3 model on the base of ResNet(D)-101b for Cityscapes from 'Rethinking Atrous Convolution for Semantic Image
Segmentation,' https://arxiv.org/abs/1706.05587.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 19
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_deeplabv3(backbone=backbone, num_classes=num_classes, aux=aux,
model_name="deeplabv3_resnetd101b_cityscapes", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
in_size = (480, 480)
aux = True
pretrained = False
models = [
(deeplabv3_resnetd50b_voc, 21),
(deeplabv3_resnetd101b_voc, 21),
(deeplabv3_resnetd152b_voc, 21),
(deeplabv3_resnetd50b_coco, 21),
(deeplabv3_resnetd101b_coco, 21),
(deeplabv3_resnetd152b_coco, 21),
(deeplabv3_resnetd50b_ade20k, 150),
(deeplabv3_resnetd101b_ade20k, 150),
(deeplabv3_resnetd50b_cityscapes, 19),
(deeplabv3_resnetd101b_cityscapes, 19),
]
for model, num_classes in models:
net = model(pretrained=pretrained, in_size=in_size, aux=aux)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
if aux:
assert (model != deeplabv3_resnetd50b_voc or weight_count == 42127850)
assert (model != deeplabv3_resnetd101b_voc or weight_count == 61119978)
assert (model != deeplabv3_resnetd152b_voc or weight_count == 76763626)
assert (model != deeplabv3_resnetd50b_coco or weight_count == 42127850)
assert (model != deeplabv3_resnetd101b_coco or weight_count == 61119978)
assert (model != deeplabv3_resnetd152b_coco or weight_count == 76763626)
assert (model != deeplabv3_resnetd50b_ade20k or weight_count == 42194156)
assert (model != deeplabv3_resnetd101b_ade20k or weight_count == 61186284)
assert (model != deeplabv3_resnetd50b_cityscapes or weight_count == 42126822)
assert (model != deeplabv3_resnetd101b_cityscapes or weight_count == 61118950)
else:
assert (model != deeplabv3_resnetd50b_voc or weight_count == 39762645)
assert (model != deeplabv3_resnetd101b_voc or weight_count == 58754773)
assert (model != deeplabv3_resnetd152b_voc or weight_count == 74398421)
assert (model != deeplabv3_resnetd50b_coco or weight_count == 39762645)
assert (model != deeplabv3_resnetd101b_coco or weight_count == 58754773)
assert (model != deeplabv3_resnetd152b_coco or weight_count == 74398421)
assert (model != deeplabv3_resnetd50b_ade20k or weight_count == 39795798)
assert (model != deeplabv3_resnetd101b_ade20k or weight_count == 58787926)
assert (model != deeplabv3_resnetd50b_cityscapes or weight_count == 39762131)
assert (model != deeplabv3_resnetd101b_cityscapes or weight_count == 58754259)
x = torch.randn(1, 3, in_size[0], in_size[1])
ys = net(x)
y = ys[0] if aux else ys
y.sum().backward()
assert ((y.size(0) == x.size(0)) and (y.size(1) == num_classes) and (y.size(2) == x.size(2)) and
(y.size(3) == x.size(3)))
if __name__ == "__main__":
_test()
| 22,014 | 37.964602 | 120 | py |
null | qimera-main/pytorchcv/models/densenet.py | """
DenseNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'Densely Connected Convolutional Networks,' https://arxiv.org/abs/1608.06993.
"""
__all__ = ['DenseNet', 'densenet121', 'densenet161', 'densenet169', 'densenet201', 'DenseUnit', 'TransitionBlock']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import pre_conv1x1_block, pre_conv3x3_block
from .preresnet import PreResInitBlock, PreResActivation
class DenseUnit(nn.Module):
"""
DenseNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
dropout_rate : float
Parameter of Dropout layer. Faction of the input units to drop.
"""
def __init__(self,
in_channels,
out_channels,
dropout_rate):
super(DenseUnit, self).__init__()
self.use_dropout = (dropout_rate != 0.0)
bn_size = 4
inc_channels = out_channels - in_channels
mid_channels = inc_channels * bn_size
self.conv1 = pre_conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels)
self.conv2 = pre_conv3x3_block(
in_channels=mid_channels,
out_channels=inc_channels)
if self.use_dropout:
self.dropout = nn.Dropout(p=dropout_rate)
def forward(self, x):
identity = x
x = self.conv1(x)
x = self.conv2(x)
if self.use_dropout:
x = self.dropout(x)
x = torch.cat((identity, x), dim=1)
return x
class TransitionBlock(nn.Module):
"""
DenseNet's auxiliary block, which can be treated as the initial part of the DenseNet unit, triggered only in the
first unit of each stage.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(TransitionBlock, self).__init__()
self.conv = pre_conv1x1_block(
in_channels=in_channels,
out_channels=out_channels)
self.pool = nn.AvgPool2d(
kernel_size=2,
stride=2,
padding=0)
def forward(self, x):
x = self.conv(x)
x = self.pool(x)
return x
class DenseNet(nn.Module):
"""
DenseNet model from 'Densely Connected Convolutional Networks,' https://arxiv.org/abs/1608.06993.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
dropout_rate : float, default 0.0
Parameter of Dropout layer. Faction of the input units to drop.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
dropout_rate=0.0,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(DenseNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", PreResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
if i != 0:
stage.add_module("trans{}".format(i + 1), TransitionBlock(
in_channels=in_channels,
out_channels=(in_channels // 2)))
in_channels = in_channels // 2
for j, out_channels in enumerate(channels_per_stage):
stage.add_module("unit{}".format(j + 1), DenseUnit(
in_channels=in_channels,
out_channels=out_channels,
dropout_rate=dropout_rate))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("post_activ", PreResActivation(in_channels=in_channels))
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_densenet(blocks,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create DenseNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 121:
init_block_channels = 64
growth_rate = 32
layers = [6, 12, 24, 16]
elif blocks == 161:
init_block_channels = 96
growth_rate = 48
layers = [6, 12, 36, 24]
elif blocks == 169:
init_block_channels = 64
growth_rate = 32
layers = [6, 12, 32, 32]
elif blocks == 201:
init_block_channels = 64
growth_rate = 32
layers = [6, 12, 48, 32]
else:
raise ValueError("Unsupported DenseNet version with number of layers {}".format(blocks))
from functools import reduce
channels = reduce(
lambda xi, yi: xi + [reduce(
lambda xj, yj: xj + [xj[-1] + yj],
[growth_rate] * yi,
[xi[-1][-1] // 2])[1:]],
layers,
[[init_block_channels * 2]])[1:]
net = DenseNet(
channels=channels,
init_block_channels=init_block_channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def densenet121(**kwargs):
"""
DenseNet-121 model from 'Densely Connected Convolutional Networks,' https://arxiv.org/abs/1608.06993.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet(blocks=121, model_name="densenet121", **kwargs)
def densenet161(**kwargs):
"""
DenseNet-161 model from 'Densely Connected Convolutional Networks,' https://arxiv.org/abs/1608.06993.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet(blocks=161, model_name="densenet161", **kwargs)
def densenet169(**kwargs):
"""
DenseNet-169 model from 'Densely Connected Convolutional Networks,' https://arxiv.org/abs/1608.06993.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet(blocks=169, model_name="densenet169", **kwargs)
def densenet201(**kwargs):
"""
DenseNet-201 model from 'Densely Connected Convolutional Networks,' https://arxiv.org/abs/1608.06993.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet(blocks=201, model_name="densenet201", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
densenet121,
densenet161,
densenet169,
densenet201,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != densenet121 or weight_count == 7978856)
assert (model != densenet161 or weight_count == 28681000)
assert (model != densenet169 or weight_count == 14149480)
assert (model != densenet201 or weight_count == 20013928)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 9,930 | 29.556923 | 116 | py |
null | qimera-main/pytorchcv/models/densenet_cifar.py | """
DenseNet for CIFAR/SVHN, implemented in PyTorch.
Original paper: 'Densely Connected Convolutional Networks,' https://arxiv.org/abs/1608.06993.
"""
__all__ = ['CIFARDenseNet', 'densenet40_k12_cifar10', 'densenet40_k12_cifar100', 'densenet40_k12_svhn',
'densenet40_k12_bc_cifar10', 'densenet40_k12_bc_cifar100', 'densenet40_k12_bc_svhn',
'densenet40_k24_bc_cifar10', 'densenet40_k24_bc_cifar100', 'densenet40_k24_bc_svhn',
'densenet40_k36_bc_cifar10', 'densenet40_k36_bc_cifar100', 'densenet40_k36_bc_svhn',
'densenet100_k12_cifar10', 'densenet100_k12_cifar100', 'densenet100_k12_svhn',
'densenet100_k24_cifar10', 'densenet100_k24_cifar100', 'densenet100_k24_svhn',
'densenet100_k12_bc_cifar10', 'densenet100_k12_bc_cifar100', 'densenet100_k12_bc_svhn',
'densenet190_k40_bc_cifar10', 'densenet190_k40_bc_cifar100', 'densenet190_k40_bc_svhn',
'densenet250_k24_bc_cifar10', 'densenet250_k24_bc_cifar100', 'densenet250_k24_bc_svhn']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv3x3, pre_conv3x3_block
from .preresnet import PreResActivation
from .densenet import DenseUnit, TransitionBlock
class DenseSimpleUnit(nn.Module):
"""
DenseNet simple unit for CIFAR.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
dropout_rate : float
Parameter of Dropout layer. Faction of the input units to drop.
"""
def __init__(self,
in_channels,
out_channels,
dropout_rate):
super(DenseSimpleUnit, self).__init__()
self.use_dropout = (dropout_rate != 0.0)
inc_channels = out_channels - in_channels
self.conv = pre_conv3x3_block(
in_channels=in_channels,
out_channels=inc_channels)
if self.use_dropout:
self.dropout = nn.Dropout(p=dropout_rate)
def forward(self, x):
identity = x
x = self.conv(x)
if self.use_dropout:
x = self.dropout(x)
x = torch.cat((identity, x), dim=1)
return x
class CIFARDenseNet(nn.Module):
"""
DenseNet model for CIFAR from 'Densely Connected Convolutional Networks,' https://arxiv.org/abs/1608.06993.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
dropout_rate : float, default 0.0
Parameter of Dropout layer. Faction of the input units to drop.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
num_classes : int, default 10
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
dropout_rate=0.0,
in_channels=3,
in_size=(32, 32),
num_classes=10):
super(CIFARDenseNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
unit_class = DenseUnit if bottleneck else DenseSimpleUnit
self.features = nn.Sequential()
self.features.add_module("init_block", conv3x3(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
if i != 0:
stage.add_module("trans{}".format(i + 1), TransitionBlock(
in_channels=in_channels,
out_channels=(in_channels // 2)))
in_channels = in_channels // 2
for j, out_channels in enumerate(channels_per_stage):
stage.add_module("unit{}".format(j + 1), unit_class(
in_channels=in_channels,
out_channels=out_channels,
dropout_rate=dropout_rate))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("post_activ", PreResActivation(in_channels=in_channels))
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=8,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_densenet_cifar(num_classes,
blocks,
growth_rate,
bottleneck,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create DenseNet model for CIFAR with specific parameters.
Parameters:
----------
num_classes : int
Number of classification classes.
blocks : int
Number of blocks.
growth_rate : int
Growth rate.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
assert (num_classes in [10, 100])
if bottleneck:
assert ((blocks - 4) % 6 == 0)
layers = [(blocks - 4) // 6] * 3
else:
assert ((blocks - 4) % 3 == 0)
layers = [(blocks - 4) // 3] * 3
init_block_channels = 2 * growth_rate
from functools import reduce
channels = reduce(
lambda xi, yi: xi + [reduce(
lambda xj, yj: xj + [xj[-1] + yj],
[growth_rate] * yi,
[xi[-1][-1] // 2])[1:]],
layers,
[[init_block_channels * 2]])[1:]
net = CIFARDenseNet(
channels=channels,
init_block_channels=init_block_channels,
num_classes=num_classes,
bottleneck=bottleneck,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def densenet40_k12_cifar10(num_classes=10, **kwargs):
"""
DenseNet-40 (k=12) model for CIFAR-10 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=40, growth_rate=12, bottleneck=False,
model_name="densenet40_k12_cifar10", **kwargs)
def densenet40_k12_cifar100(num_classes=100, **kwargs):
"""
DenseNet-40 (k=12) model for CIFAR-100 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=40, growth_rate=12, bottleneck=False,
model_name="densenet40_k12_cifar100", **kwargs)
def densenet40_k12_svhn(num_classes=10, **kwargs):
"""
DenseNet-40 (k=12) model for SVHN from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=40, growth_rate=12, bottleneck=False,
model_name="densenet40_k12_svhn", **kwargs)
def densenet40_k12_bc_cifar10(num_classes=10, **kwargs):
"""
DenseNet-BC-40 (k=12) model for CIFAR-10 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=40, growth_rate=12, bottleneck=True,
model_name="densenet40_k12_bc_cifar10", **kwargs)
def densenet40_k12_bc_cifar100(num_classes=100, **kwargs):
"""
DenseNet-BC-40 (k=12) model for CIFAR-100 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=40, growth_rate=12, bottleneck=True,
model_name="densenet40_k12_bc_cifar100", **kwargs)
def densenet40_k12_bc_svhn(num_classes=10, **kwargs):
"""
DenseNet-BC-40 (k=12) model for SVHN from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=40, growth_rate=12, bottleneck=True,
model_name="densenet40_k12_bc_svhn", **kwargs)
def densenet40_k24_bc_cifar10(num_classes=10, **kwargs):
"""
DenseNet-BC-40 (k=24) model for CIFAR-10 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=40, growth_rate=24, bottleneck=True,
model_name="densenet40_k24_bc_cifar10", **kwargs)
def densenet40_k24_bc_cifar100(num_classes=100, **kwargs):
"""
DenseNet-BC-40 (k=24) model for CIFAR-100 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=40, growth_rate=24, bottleneck=True,
model_name="densenet40_k24_bc_cifar100", **kwargs)
def densenet40_k24_bc_svhn(num_classes=10, **kwargs):
"""
DenseNet-BC-40 (k=24) model for SVHN from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=40, growth_rate=24, bottleneck=True,
model_name="densenet40_k24_bc_svhn", **kwargs)
def densenet40_k36_bc_cifar10(num_classes=10, **kwargs):
"""
DenseNet-BC-40 (k=36) model for CIFAR-10 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=40, growth_rate=36, bottleneck=True,
model_name="densenet40_k36_bc_cifar10", **kwargs)
def densenet40_k36_bc_cifar100(num_classes=100, **kwargs):
"""
DenseNet-BC-40 (k=36) model for CIFAR-100 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=40, growth_rate=36, bottleneck=True,
model_name="densenet40_k36_bc_cifar100", **kwargs)
def densenet40_k36_bc_svhn(num_classes=10, **kwargs):
"""
DenseNet-BC-40 (k=36) model for SVHN from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=40, growth_rate=36, bottleneck=True,
model_name="densenet40_k36_bc_svhn", **kwargs)
def densenet100_k12_cifar10(num_classes=10, **kwargs):
"""
DenseNet-100 (k=12) model for CIFAR-10 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=100, growth_rate=12, bottleneck=False,
model_name="densenet100_k12_cifar10", **kwargs)
def densenet100_k12_cifar100(num_classes=100, **kwargs):
"""
DenseNet-100 (k=12) model for CIFAR-100 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=100, growth_rate=12, bottleneck=False,
model_name="densenet100_k12_cifar100", **kwargs)
def densenet100_k12_svhn(num_classes=10, **kwargs):
"""
DenseNet-100 (k=12) model for SVHN from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=100, growth_rate=12, bottleneck=False,
model_name="densenet100_k12_svhn", **kwargs)
def densenet100_k24_cifar10(num_classes=10, **kwargs):
"""
DenseNet-100 (k=24) model for CIFAR-10 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=100, growth_rate=24, bottleneck=False,
model_name="densenet100_k24_cifar10", **kwargs)
def densenet100_k24_cifar100(num_classes=100, **kwargs):
"""
DenseNet-100 (k=24) model for CIFAR-100 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=100, growth_rate=24, bottleneck=False,
model_name="densenet100_k24_cifar100", **kwargs)
def densenet100_k24_svhn(num_classes=10, **kwargs):
"""
DenseNet-100 (k=24) model for SVHN from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=100, growth_rate=24, bottleneck=False,
model_name="densenet100_k24_svhn", **kwargs)
def densenet100_k12_bc_cifar10(num_classes=10, **kwargs):
"""
DenseNet-BC-100 (k=12) model for CIFAR-10 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=100, growth_rate=12, bottleneck=True,
model_name="densenet100_k12_bc_cifar10", **kwargs)
def densenet100_k12_bc_cifar100(num_classes=100, **kwargs):
"""
DenseNet-BC-100 (k=12) model for CIFAR-100 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=100, growth_rate=12, bottleneck=True,
model_name="densenet100_k12_bc_cifar100", **kwargs)
def densenet100_k12_bc_svhn(num_classes=10, **kwargs):
"""
DenseNet-BC-100 (k=12) model for SVHN from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=100, growth_rate=12, bottleneck=True,
model_name="densenet100_k12_bc_svhn", **kwargs)
def densenet190_k40_bc_cifar10(num_classes=10, **kwargs):
"""
DenseNet-BC-190 (k=40) model for CIFAR-10 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=190, growth_rate=40, bottleneck=True,
model_name="densenet190_k40_bc_cifar10", **kwargs)
def densenet190_k40_bc_cifar100(num_classes=100, **kwargs):
"""
DenseNet-BC-190 (k=40) model for CIFAR-100 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=190, growth_rate=40, bottleneck=True,
model_name="densenet190_k40_bc_cifar100", **kwargs)
def densenet190_k40_bc_svhn(num_classes=10, **kwargs):
"""
DenseNet-BC-190 (k=40) model for SVHN from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=190, growth_rate=40, bottleneck=True,
model_name="densenet190_k40_bc_svhn", **kwargs)
def densenet250_k24_bc_cifar10(num_classes=10, **kwargs):
"""
DenseNet-BC-250 (k=24) model for CIFAR-10 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=250, growth_rate=24, bottleneck=True,
model_name="densenet250_k24_bc_cifar10", **kwargs)
def densenet250_k24_bc_cifar100(num_classes=100, **kwargs):
"""
DenseNet-BC-250 (k=24) model for CIFAR-100 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=250, growth_rate=24, bottleneck=True,
model_name="densenet250_k24_bc_cifar100", **kwargs)
def densenet250_k24_bc_svhn(num_classes=10, **kwargs):
"""
DenseNet-BC-250 (k=24) model for SVHN from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(num_classes=num_classes, blocks=250, growth_rate=24, bottleneck=True,
model_name="densenet250_k24_bc_svhn", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
(densenet40_k12_cifar10, 10),
(densenet40_k12_cifar100, 100),
(densenet40_k12_svhn, 10),
(densenet40_k12_bc_cifar10, 10),
(densenet40_k12_bc_cifar100, 100),
(densenet40_k12_bc_svhn, 10),
(densenet40_k24_bc_cifar10, 10),
(densenet40_k24_bc_cifar100, 100),
(densenet40_k24_bc_svhn, 10),
(densenet40_k36_bc_cifar10, 10),
(densenet40_k36_bc_cifar100, 100),
(densenet40_k36_bc_svhn, 10),
(densenet100_k12_cifar10, 10),
(densenet100_k12_cifar100, 100),
(densenet100_k12_svhn, 10),
(densenet100_k24_cifar10, 10),
(densenet100_k24_cifar100, 100),
(densenet100_k24_svhn, 10),
(densenet100_k12_bc_cifar10, 10),
(densenet100_k12_bc_cifar100, 100),
(densenet100_k12_bc_svhn, 10),
(densenet190_k40_bc_cifar10, 10),
(densenet190_k40_bc_cifar100, 100),
(densenet190_k40_bc_svhn, 10),
(densenet250_k24_bc_cifar10, 10),
(densenet250_k24_bc_cifar100, 100),
(densenet250_k24_bc_svhn, 10),
]
for model, num_classes in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != densenet40_k12_cifar10 or weight_count == 599050)
assert (model != densenet40_k12_cifar100 or weight_count == 622360)
assert (model != densenet40_k12_svhn or weight_count == 599050)
assert (model != densenet40_k12_bc_cifar10 or weight_count == 176122)
assert (model != densenet40_k12_bc_cifar100 or weight_count == 188092)
assert (model != densenet40_k12_bc_svhn or weight_count == 176122)
assert (model != densenet40_k24_bc_cifar10 or weight_count == 690346)
assert (model != densenet40_k24_bc_cifar100 or weight_count == 714196)
assert (model != densenet40_k24_bc_svhn or weight_count == 690346)
assert (model != densenet40_k36_bc_cifar10 or weight_count == 1542682)
assert (model != densenet40_k36_bc_cifar100 or weight_count == 1578412)
assert (model != densenet40_k36_bc_svhn or weight_count == 1542682)
assert (model != densenet100_k12_cifar10 or weight_count == 4068490)
assert (model != densenet100_k12_cifar100 or weight_count == 4129600)
assert (model != densenet100_k12_svhn or weight_count == 4068490)
assert (model != densenet100_k24_cifar10 or weight_count == 16114138)
assert (model != densenet100_k24_cifar100 or weight_count == 16236268)
assert (model != densenet100_k24_svhn or weight_count == 16114138)
assert (model != densenet100_k12_bc_cifar10 or weight_count == 769162)
assert (model != densenet100_k12_bc_cifar100 or weight_count == 800032)
assert (model != densenet100_k12_bc_svhn or weight_count == 769162)
assert (model != densenet190_k40_bc_cifar10 or weight_count == 25624430)
assert (model != densenet190_k40_bc_cifar100 or weight_count == 25821620)
assert (model != densenet190_k40_bc_svhn or weight_count == 25624430)
assert (model != densenet250_k24_bc_cifar10 or weight_count == 15324406)
assert (model != densenet250_k24_bc_cifar100 or weight_count == 15480556)
assert (model != densenet250_k24_bc_svhn or weight_count == 15324406)
x = torch.randn(1, 3, 32, 32)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, num_classes))
if __name__ == "__main__":
_test()
| 29,468 | 36.780769 | 115 | py |
null | qimera-main/pytorchcv/models/diapreresnet.py | """
DIA-PreResNet for ImageNet-1K, implemented in PyTorch.
Original papers: 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
"""
__all__ = ['DIAPreResNet', 'diapreresnet10', 'diapreresnet12', 'diapreresnet14', 'diapreresnetbc14b', 'diapreresnet16',
'diapreresnet18', 'diapreresnet26', 'diapreresnetbc26b', 'diapreresnet34', 'diapreresnetbc38b',
'diapreresnet50', 'diapreresnet50b', 'diapreresnet101', 'diapreresnet101b', 'diapreresnet152',
'diapreresnet152b', 'diapreresnet200', 'diapreresnet200b', 'diapreresnet269b', 'DIAPreResUnit']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1, DualPathSequential
from .preresnet import PreResBlock, PreResBottleneck, PreResInitBlock, PreResActivation
from .diaresnet import DIAAttention
class DIAPreResUnit(nn.Module):
"""
DIA-PreResNet unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer of the block.
attention : nn.Module, default None
Attention module.
"""
def __init__(self,
in_channels,
out_channels,
stride,
bottleneck,
conv1_stride,
attention=None):
super(DIAPreResUnit, self).__init__()
self.resize_identity = (in_channels != out_channels) or (stride != 1)
if bottleneck:
self.body = PreResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
conv1_stride=conv1_stride)
else:
self.body = PreResBlock(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
if self.resize_identity:
self.identity_conv = conv1x1(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
self.attention = attention
def forward(self, x, hc=None):
identity = x
x, x_pre_activ = self.body(x)
if self.resize_identity:
identity = self.identity_conv(x_pre_activ)
x, hc = self.attention(x, hc)
x = x + identity
return x, hc
class DIAPreResNet(nn.Module):
"""
DIA-PreResNet model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer in units.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
conv1_stride,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(DIAPreResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", PreResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = DualPathSequential(return_two=False)
attention = DIAAttention(
in_x_features=channels_per_stage[0],
in_h_features=channels_per_stage[0])
for j, out_channels in enumerate(channels_per_stage):
stride = 1 if (i == 0) or (j != 0) else 2
stage.add_module("unit{}".format(j + 1), DIAPreResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
attention=attention))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("post_activ", PreResActivation(in_channels=in_channels))
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_diapreresnet(blocks,
bottleneck=None,
conv1_stride=True,
width_scale=1.0,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create DIA-PreResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
bottleneck : bool, default None
Whether to use a bottleneck or simple block in units.
conv1_stride : bool, default True
Whether to use stride in the first or the second convolution layer in units.
width_scale : float, default 1.0
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if bottleneck is None:
bottleneck = (blocks >= 50)
if blocks == 10:
layers = [1, 1, 1, 1]
elif blocks == 12:
layers = [2, 1, 1, 1]
elif blocks == 14 and not bottleneck:
layers = [2, 2, 1, 1]
elif (blocks == 14) and bottleneck:
layers = [1, 1, 1, 1]
elif blocks == 16:
layers = [2, 2, 2, 1]
elif blocks == 18:
layers = [2, 2, 2, 2]
elif (blocks == 26) and not bottleneck:
layers = [3, 3, 3, 3]
elif (blocks == 26) and bottleneck:
layers = [2, 2, 2, 2]
elif blocks == 34:
layers = [3, 4, 6, 3]
elif (blocks == 38) and bottleneck:
layers = [3, 3, 3, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
elif blocks == 200:
layers = [3, 24, 36, 3]
elif blocks == 269:
layers = [3, 30, 48, 8]
else:
raise ValueError("Unsupported DIA-PreResNet with number of blocks: {}".format(blocks))
if bottleneck:
assert (sum(layers) * 3 + 2 == blocks)
else:
assert (sum(layers) * 2 + 2 == blocks)
init_block_channels = 64
channels_per_layers = [64, 128, 256, 512]
if bottleneck:
bottleneck_factor = 4
channels_per_layers = [ci * bottleneck_factor for ci in channels_per_layers]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if width_scale != 1.0:
channels = [[int(cij * width_scale) if (i != len(channels) - 1) or (j != len(ci) - 1) else cij
for j, cij in enumerate(ci)] for i, ci in enumerate(channels)]
init_block_channels = int(init_block_channels * width_scale)
net = DIAPreResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def diapreresnet10(**kwargs):
"""
DIA-PreResNet-10 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=10, model_name="diapreresnet10", **kwargs)
def diapreresnet12(**kwargs):
"""
DIA-PreResNet-12 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=12, model_name="diapreresnet12", **kwargs)
def diapreresnet14(**kwargs):
"""
DIA-PreResNet-14 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=14, model_name="diapreresnet14", **kwargs)
def diapreresnetbc14b(**kwargs):
"""
DIA-PreResNet-BC-14b model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model (bottleneck compressed).
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=14, bottleneck=True, conv1_stride=False, model_name="diapreresnetbc14b", **kwargs)
def diapreresnet16(**kwargs):
"""
DIA-PreResNet-16 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=16, model_name="diapreresnet16", **kwargs)
def diapreresnet18(**kwargs):
"""
DIA-PreResNet-18 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=18, model_name="diapreresnet18", **kwargs)
def diapreresnet26(**kwargs):
"""
DIA-PreResNet-26 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=26, bottleneck=False, model_name="diapreresnet26", **kwargs)
def diapreresnetbc26b(**kwargs):
"""
DIA-PreResNet-BC-26b model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model (bottleneck compressed).
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=26, bottleneck=True, conv1_stride=False, model_name="diapreresnetbc26b", **kwargs)
def diapreresnet34(**kwargs):
"""
DIA-PreResNet-34 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=34, model_name="diapreresnet34", **kwargs)
def diapreresnetbc38b(**kwargs):
"""
DIA-PreResNet-BC-38b model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model (bottleneck compressed).
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=38, bottleneck=True, conv1_stride=False, model_name="diapreresnetbc38b", **kwargs)
def diapreresnet50(**kwargs):
"""
DIA-PreResNet-50 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=50, model_name="diapreresnet50", **kwargs)
def diapreresnet50b(**kwargs):
"""
DIA-PreResNet-50 model with stride at the second convolution in bottleneck block from 'DIANet: Dense-and-Implicit
Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=50, conv1_stride=False, model_name="diapreresnet50b", **kwargs)
def diapreresnet101(**kwargs):
"""
DIA-PreResNet-101 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=101, model_name="diapreresnet101", **kwargs)
def diapreresnet101b(**kwargs):
"""
DIA-PreResNet-101 model with stride at the second convolution in bottleneck block from 'DIANet: Dense-and-Implicit
Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=101, conv1_stride=False, model_name="diapreresnet101b", **kwargs)
def diapreresnet152(**kwargs):
"""
DIA-PreResNet-152 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=152, model_name="diapreresnet152", **kwargs)
def diapreresnet152b(**kwargs):
"""
DIA-PreResNet-152 model with stride at the second convolution in bottleneck block from 'DIANet: Dense-and-Implicit
Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=152, conv1_stride=False, model_name="diapreresnet152b", **kwargs)
def diapreresnet200(**kwargs):
"""
DIA-PreResNet-200 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=200, model_name="diapreresnet200", **kwargs)
def diapreresnet200b(**kwargs):
"""
DIA-PreResNet-200 model with stride at the second convolution in bottleneck block from 'DIANet: Dense-and-Implicit
Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=200, conv1_stride=False, model_name="diapreresnet200b", **kwargs)
def diapreresnet269b(**kwargs):
"""
DIA-PreResNet-269 model with stride at the second convolution in bottleneck block from 'DIANet: Dense-and-Implicit
Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=269, conv1_stride=False, model_name="diapreresnet269b", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
diapreresnet10,
diapreresnet12,
diapreresnet14,
diapreresnetbc14b,
diapreresnet16,
diapreresnet18,
diapreresnet26,
diapreresnetbc26b,
diapreresnet34,
diapreresnetbc38b,
diapreresnet50,
diapreresnet50b,
diapreresnet101,
diapreresnet101b,
diapreresnet152,
diapreresnet152b,
diapreresnet200,
diapreresnet200b,
diapreresnet269b,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != diapreresnet10 or weight_count == 6295688)
assert (model != diapreresnet12 or weight_count == 6369672)
assert (model != diapreresnet14 or weight_count == 6665096)
assert (model != diapreresnetbc14b or weight_count == 24016424)
assert (model != diapreresnet16 or weight_count == 7845768)
assert (model != diapreresnet18 or weight_count == 12566408)
assert (model != diapreresnet26 or weight_count == 18837128)
assert (model != diapreresnetbc26b or weight_count == 29946664)
assert (model != diapreresnet34 or weight_count == 22674568)
assert (model != diapreresnetbc38b or weight_count == 35876904)
assert (model != diapreresnet50 or weight_count == 39508520)
assert (model != diapreresnet50b or weight_count == 39508520)
assert (model != diapreresnet101 or weight_count == 58500648)
assert (model != diapreresnet101b or weight_count == 58500648)
assert (model != diapreresnet152 or weight_count == 74144296)
assert (model != diapreresnet152b or weight_count == 74144296)
assert (model != diapreresnet200 or weight_count == 78625320)
assert (model != diapreresnet200b or weight_count == 78625320)
assert (model != diapreresnet269b or weight_count == 116024872)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 21,166 | 33.814145 | 119 | py |
null | qimera-main/pytorchcv/models/diapreresnet_cifar.py | """
DIA-PreResNet for CIFAR/SVHN, implemented in PyTorch.
Original papers: 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
"""
__all__ = ['CIFARDIAPreResNet', 'diapreresnet20_cifar10', 'diapreresnet20_cifar100', 'diapreresnet20_svhn',
'diapreresnet56_cifar10', 'diapreresnet56_cifar100', 'diapreresnet56_svhn', 'diapreresnet110_cifar10',
'diapreresnet110_cifar100', 'diapreresnet110_svhn', 'diapreresnet164bn_cifar10',
'diapreresnet164bn_cifar100', 'diapreresnet164bn_svhn', 'diapreresnet1001_cifar10',
'diapreresnet1001_cifar100', 'diapreresnet1001_svhn', 'diapreresnet1202_cifar10',
'diapreresnet1202_cifar100', 'diapreresnet1202_svhn']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv3x3, DualPathSequential
from .preresnet import PreResActivation
from .diaresnet import DIAAttention
from .diapreresnet import DIAPreResUnit
class CIFARDIAPreResNet(nn.Module):
"""
DIA-PreResNet model for CIFAR from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
num_classes : int, default 10
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
in_channels=3,
in_size=(32, 32),
num_classes=10):
super(CIFARDIAPreResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", conv3x3(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = DualPathSequential(return_two=False)
attention = DIAAttention(
in_x_features=channels_per_stage[0],
in_h_features=channels_per_stage[0])
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), DIAPreResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck,
conv1_stride=False,
attention=attention))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("post_activ", PreResActivation(in_channels=in_channels))
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=8,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_diapreresnet_cifar(num_classes,
blocks,
bottleneck,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create DIA-PreResNet model for CIFAR with specific parameters.
Parameters:
----------
num_classes : int
Number of classification classes.
blocks : int
Number of blocks.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
assert (num_classes in [10, 100])
if bottleneck:
assert ((blocks - 2) % 9 == 0)
layers = [(blocks - 2) // 9] * 3
else:
assert ((blocks - 2) % 6 == 0)
layers = [(blocks - 2) // 6] * 3
channels_per_layers = [16, 32, 64]
init_block_channels = 16
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if bottleneck:
channels = [[cij * 4 for cij in ci] for ci in channels]
net = CIFARDIAPreResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
num_classes=num_classes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def diapreresnet20_cifar10(num_classes=10, **kwargs):
"""
DIA-PreResNet-20 model for CIFAR-10 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(num_classes=num_classes, blocks=20, bottleneck=False,
model_name="diapreresnet20_cifar10", **kwargs)
def diapreresnet20_cifar100(num_classes=100, **kwargs):
"""
DIA-PreResNet-20 model for CIFAR-100 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(num_classes=num_classes, blocks=20, bottleneck=False,
model_name="diapreresnet20_cifar100", **kwargs)
def diapreresnet20_svhn(num_classes=10, **kwargs):
"""
DIA-PreResNet-20 model for SVHN from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(num_classes=num_classes, blocks=20, bottleneck=False,
model_name="diapreresnet20_svhn", **kwargs)
def diapreresnet56_cifar10(num_classes=10, **kwargs):
"""
DIA-PreResNet-56 model for CIFAR-10 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(num_classes=num_classes, blocks=56, bottleneck=False,
model_name="diapreresnet56_cifar10", **kwargs)
def diapreresnet56_cifar100(num_classes=100, **kwargs):
"""
DIA-PreResNet-56 model for CIFAR-100 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(num_classes=num_classes, blocks=56, bottleneck=False,
model_name="diapreresnet56_cifar100", **kwargs)
def diapreresnet56_svhn(num_classes=10, **kwargs):
"""
DIA-PreResNet-56 model for SVHN from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(num_classes=num_classes, blocks=56, bottleneck=False,
model_name="diapreresnet56_svhn", **kwargs)
def diapreresnet110_cifar10(num_classes=10, **kwargs):
"""
DIA-PreResNet-110 model for CIFAR-10 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(num_classes=num_classes, blocks=110, bottleneck=False,
model_name="diapreresnet110_cifar10", **kwargs)
def diapreresnet110_cifar100(num_classes=100, **kwargs):
"""
DIA-PreResNet-110 model for CIFAR-100 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(num_classes=num_classes, blocks=110, bottleneck=False,
model_name="diapreresnet110_cifar100", **kwargs)
def diapreresnet110_svhn(num_classes=10, **kwargs):
"""
DIA-PreResNet-110 model for SVHN from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(num_classes=num_classes, blocks=110, bottleneck=False,
model_name="diapreresnet110_svhn", **kwargs)
def diapreresnet164bn_cifar10(num_classes=10, **kwargs):
"""
DIA-PreResNet-164(BN) model for CIFAR-10 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(num_classes=num_classes, blocks=164, bottleneck=True,
model_name="diapreresnet164bn_cifar10", **kwargs)
def diapreresnet164bn_cifar100(num_classes=100, **kwargs):
"""
DIA-PreResNet-164(BN) model for CIFAR-100 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(num_classes=num_classes, blocks=164, bottleneck=True,
model_name="diapreresnet164bn_cifar100", **kwargs)
def diapreresnet164bn_svhn(num_classes=10, **kwargs):
"""
DIA-PreResNet-164(BN) model for SVHN from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(num_classes=num_classes, blocks=164, bottleneck=True,
model_name="diapreresnet164bn_svhn", **kwargs)
def diapreresnet1001_cifar10(num_classes=10, **kwargs):
"""
DIA-PreResNet-1001 model for CIFAR-10 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(num_classes=num_classes, blocks=1001, bottleneck=True,
model_name="diapreresnet1001_cifar10", **kwargs)
def diapreresnet1001_cifar100(num_classes=100, **kwargs):
"""
DIA-PreResNet-1001 model for CIFAR-100 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(num_classes=num_classes, blocks=1001, bottleneck=True,
model_name="diapreresnet1001_cifar100", **kwargs)
def diapreresnet1001_svhn(num_classes=10, **kwargs):
"""
DIA-PreResNet-1001 model for SVHN from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(num_classes=num_classes, blocks=1001, bottleneck=True,
model_name="diapreresnet1001_svhn", **kwargs)
def diapreresnet1202_cifar10(num_classes=10, **kwargs):
"""
DIA-PreResNet-1202 model for CIFAR-10 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(num_classes=num_classes, blocks=1202, bottleneck=False,
model_name="diapreresnet1202_cifar10", **kwargs)
def diapreresnet1202_cifar100(num_classes=100, **kwargs):
"""
DIA-PreResNet-1202 model for CIFAR-100 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(num_classes=num_classes, blocks=1202, bottleneck=False,
model_name="diapreresnet1202_cifar100", **kwargs)
def diapreresnet1202_svhn(num_classes=10, **kwargs):
"""
DIA-PreResNet-1202 model for SVHN from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(num_classes=num_classes, blocks=1202, bottleneck=False,
model_name="diapreresnet1202_svhn", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
(diapreresnet20_cifar10, 10),
(diapreresnet20_cifar100, 100),
(diapreresnet20_svhn, 10),
(diapreresnet56_cifar10, 10),
(diapreresnet56_cifar100, 100),
(diapreresnet56_svhn, 10),
(diapreresnet110_cifar10, 10),
(diapreresnet110_cifar100, 100),
(diapreresnet110_svhn, 10),
(diapreresnet164bn_cifar10, 10),
(diapreresnet164bn_cifar100, 100),
(diapreresnet164bn_svhn, 10),
(diapreresnet1001_cifar10, 10),
(diapreresnet1001_cifar100, 100),
(diapreresnet1001_svhn, 10),
(diapreresnet1202_cifar10, 10),
(diapreresnet1202_cifar100, 100),
(diapreresnet1202_svhn, 10),
]
for model, num_classes in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != diapreresnet20_cifar10 or weight_count == 286674)
assert (model != diapreresnet20_cifar100 or weight_count == 292524)
assert (model != diapreresnet20_svhn or weight_count == 286674)
assert (model != diapreresnet56_cifar10 or weight_count == 869970)
assert (model != diapreresnet56_cifar100 or weight_count == 875820)
assert (model != diapreresnet56_svhn or weight_count == 869970)
assert (model != diapreresnet110_cifar10 or weight_count == 1744914)
assert (model != diapreresnet110_cifar100 or weight_count == 1750764)
assert (model != diapreresnet110_svhn or weight_count == 1744914)
assert (model != diapreresnet164bn_cifar10 or weight_count == 1922106)
assert (model != diapreresnet164bn_cifar100 or weight_count == 1945236)
assert (model != diapreresnet164bn_svhn or weight_count == 1922106)
assert (model != diapreresnet1001_cifar10 or weight_count == 10546554)
assert (model != diapreresnet1001_cifar100 or weight_count == 10569684)
assert (model != diapreresnet1001_svhn or weight_count == 10546554)
assert (model != diapreresnet1202_cifar10 or weight_count == 19438226)
assert (model != diapreresnet1202_cifar100 or weight_count == 19444076)
assert (model != diapreresnet1202_svhn or weight_count == 19438226)
x = torch.randn(1, 3, 32, 32)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, num_classes))
if __name__ == "__main__":
_test()
| 20,604 | 36.327899 | 120 | py |
null | qimera-main/pytorchcv/models/diaresnet.py | """
DIA-ResNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
"""
__all__ = ['DIAResNet', 'diaresnet10', 'diaresnet12', 'diaresnet14', 'diaresnetbc14b', 'diaresnet16', 'diaresnet18',
'diaresnet26', 'diaresnetbc26b', 'diaresnet34', 'diaresnetbc38b', 'diaresnet50', 'diaresnet50b',
'diaresnet101', 'diaresnet101b', 'diaresnet152', 'diaresnet152b', 'diaresnet200', 'diaresnet200b',
'DIAAttention', 'DIAResUnit']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, DualPathSequential
from .resnet import ResBlock, ResBottleneck, ResInitBlock
class FirstLSTMAmp(nn.Module):
"""
First LSTM amplifier branch.
Parameters:
----------
in_features : int
Number of input channels.
out_features : int
Number of output channels.
"""
def __init__(self,
in_features,
out_features):
super(FirstLSTMAmp, self).__init__()
mid_features = in_features // 4
self.fc1 = nn.Linear(
in_features=in_features,
out_features=mid_features)
self.activ = nn.ReLU(inplace=True)
self.fc2 = nn.Linear(
in_features=mid_features,
out_features=out_features)
def forward(self, x):
x = self.fc1(x)
x = self.activ(x)
x = self.fc2(x)
return x
class DIALSTMCell(nn.Module):
"""
DIA-LSTM cell.
Parameters:
----------
in_x_features : int
Number of x input channels.
in_h_features : int
Number of h input channels.
num_layers : int
Number of amplifiers.
dropout_rate : float, default 0.1
Parameter of Dropout layer. Faction of the input units to drop.
"""
def __init__(self,
in_x_features,
in_h_features,
num_layers,
dropout_rate=0.1):
super(DIALSTMCell, self).__init__()
self.num_layers = num_layers
out_features = 4 * in_h_features
self.x_amps = nn.Sequential()
self.h_amps = nn.Sequential()
for i in range(num_layers):
amp_class = FirstLSTMAmp if i == 0 else nn.Linear
self.x_amps.add_module("amp{}".format(i + 1), amp_class(
in_features=in_x_features,
out_features=out_features))
self.h_amps.add_module("amp{}".format(i + 1), amp_class(
in_features=in_h_features,
out_features=out_features))
in_x_features = in_h_features
self.dropout = nn.Dropout(p=dropout_rate)
def forward(self, x, h, c):
hy = []
cy = []
for i in range(self.num_layers):
hx_i = h[i]
cx_i = c[i]
gates = self.x_amps[i](x) + self.h_amps[i](hx_i)
i_gate, f_gate, c_gate, o_gate = gates.chunk(chunks=4, dim=1)
i_gate = torch.sigmoid(i_gate)
f_gate = torch.sigmoid(f_gate)
c_gate = torch.tanh(c_gate)
o_gate = torch.sigmoid(o_gate)
cy_i = (f_gate * cx_i) + (i_gate * c_gate)
hy_i = o_gate * torch.sigmoid(cy_i)
cy.append(cy_i)
hy.append(hy_i)
x = self.dropout(hy_i)
return hy, cy
class DIAAttention(nn.Module):
"""
DIA-Net attention module.
Parameters:
----------
in_x_features : int
Number of x input channels.
in_h_features : int
Number of h input channels.
num_layers : int, default 1
Number of amplifiers.
"""
def __init__(self,
in_x_features,
in_h_features,
num_layers=1):
super(DIAAttention, self).__init__()
self.num_layers = num_layers
self.pool = nn.AdaptiveAvgPool2d(output_size=1)
self.lstm = DIALSTMCell(
in_x_features=in_x_features,
in_h_features=in_h_features,
num_layers=num_layers)
def forward(self, x, hc=None):
w = self.pool(x)
w = w.view(w.size(0), -1)
if hc is None:
h = [torch.zeros_like(w)] * self.num_layers
c = [torch.zeros_like(w)] * self.num_layers
else:
h, c = hc
h, c = self.lstm(w, h, c)
w = h[-1].unsqueeze(dim=-1).unsqueeze(dim=-1)
x = x * w
return x, (h, c)
class DIAResUnit(nn.Module):
"""
DIA-ResNet unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for the second convolution layer in bottleneck.
dilation : int or tuple/list of 2 int, default 1
Dilation value for the second convolution layer in bottleneck.
bottleneck : bool, default True
Whether to use a bottleneck or simple block in units.
conv1_stride : bool, default False
Whether to use stride in the first or the second convolution layer of the block.
attention : nn.Module, default None
Attention module.
"""
def __init__(self,
in_channels,
out_channels,
stride,
padding=1,
dilation=1,
bottleneck=True,
conv1_stride=False,
attention=None):
super(DIAResUnit, self).__init__()
self.resize_identity = (in_channels != out_channels) or (stride != 1)
if bottleneck:
self.body = ResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
padding=padding,
dilation=dilation,
conv1_stride=conv1_stride)
else:
self.body = ResBlock(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
activation=None)
self.activ = nn.ReLU(inplace=True)
self.attention = attention
def forward(self, x, hc=None):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x, hc = self.attention(x, hc)
x = x + identity
x = self.activ(x)
return x, hc
class DIAResNet(nn.Module):
"""
DIA-ResNet model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer in units.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
conv1_stride,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(DIAResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = DualPathSequential(return_two=False)
attention = DIAAttention(
in_x_features=channels_per_stage[0],
in_h_features=channels_per_stage[0])
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), DIAResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
attention=attention))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_diaresnet(blocks,
bottleneck=None,
conv1_stride=True,
width_scale=1.0,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create DIA-ResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
bottleneck : bool, default None
Whether to use a bottleneck or simple block in units.
conv1_stride : bool, default True
Whether to use stride in the first or the second convolution layer in units.
width_scale : float, default 1.0
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if bottleneck is None:
bottleneck = (blocks >= 50)
if blocks == 10:
layers = [1, 1, 1, 1]
elif blocks == 12:
layers = [2, 1, 1, 1]
elif blocks == 14 and not bottleneck:
layers = [2, 2, 1, 1]
elif (blocks == 14) and bottleneck:
layers = [1, 1, 1, 1]
elif blocks == 16:
layers = [2, 2, 2, 1]
elif blocks == 18:
layers = [2, 2, 2, 2]
elif (blocks == 26) and not bottleneck:
layers = [3, 3, 3, 3]
elif (blocks == 26) and bottleneck:
layers = [2, 2, 2, 2]
elif blocks == 34:
layers = [3, 4, 6, 3]
elif (blocks == 38) and bottleneck:
layers = [3, 3, 3, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
elif blocks == 200:
layers = [3, 24, 36, 3]
else:
raise ValueError("Unsupported DIA-ResNet with number of blocks: {}".format(blocks))
if bottleneck:
assert (sum(layers) * 3 + 2 == blocks)
else:
assert (sum(layers) * 2 + 2 == blocks)
init_block_channels = 64
channels_per_layers = [64, 128, 256, 512]
if bottleneck:
bottleneck_factor = 4
channels_per_layers = [ci * bottleneck_factor for ci in channels_per_layers]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if width_scale != 1.0:
channels = [[int(cij * width_scale) if (i != len(channels) - 1) or (j != len(ci) - 1) else cij
for j, cij in enumerate(ci)] for i, ci in enumerate(channels)]
init_block_channels = int(init_block_channels * width_scale)
net = DIAResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def diaresnet10(**kwargs):
"""
DIA-ResNet-10 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=10, model_name="diaresnet10", **kwargs)
def diaresnet12(**kwargs):
"""
DIA-ResNet-12 model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=12, model_name="diaresnet12", **kwargs)
def diaresnet14(**kwargs):
"""
DIA-ResNet-14 model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=14, model_name="diaresnet14", **kwargs)
def diaresnetbc14b(**kwargs):
"""
DIA-ResNet-BC-14b model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model (bottleneck compressed).
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=14, bottleneck=True, conv1_stride=False, model_name="diaresnetbc14b", **kwargs)
def diaresnet16(**kwargs):
"""
DIA-ResNet-16 model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=16, model_name="diaresnet16", **kwargs)
def diaresnet18(**kwargs):
"""
DIA-ResNet-18 model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=18, model_name="diaresnet18", **kwargs)
def diaresnet26(**kwargs):
"""
DIA-ResNet-26 model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=26, bottleneck=False, model_name="diaresnet26", **kwargs)
def diaresnetbc26b(**kwargs):
"""
DIA-ResNet-BC-26b model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model (bottleneck compressed).
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=26, bottleneck=True, conv1_stride=False, model_name="diaresnetbc26b", **kwargs)
def diaresnet34(**kwargs):
"""
DIA-ResNet-34 model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=34, model_name="diaresnet34", **kwargs)
def diaresnetbc38b(**kwargs):
"""
DIA-ResNet-BC-38b model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model (bottleneck compressed).
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=38, bottleneck=True, conv1_stride=False, model_name="diaresnetbc38b", **kwargs)
def diaresnet50(**kwargs):
"""
DIA-ResNet-50 model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=50, model_name="diaresnet50", **kwargs)
def diaresnet50b(**kwargs):
"""
DIA-ResNet-50 model with stride at the second convolution in bottleneck block from 'DIANet: Dense-and-Implicit
Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=50, conv1_stride=False, model_name="diaresnet50b", **kwargs)
def diaresnet101(**kwargs):
"""
DIA-ResNet-101 model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=101, model_name="diaresnet101", **kwargs)
def diaresnet101b(**kwargs):
"""
DIA-ResNet-101 model with stride at the second convolution in bottleneck block from 'DIANet: Dense-and-Implicit
Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=101, conv1_stride=False, model_name="diaresnet101b", **kwargs)
def diaresnet152(**kwargs):
"""
DIA-ResNet-152 model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=152, model_name="diaresnet152", **kwargs)
def diaresnet152b(**kwargs):
"""
DIA-ResNet-152 model with stride at the second convolution in bottleneck block from 'DIANet: Dense-and-Implicit
Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=152, conv1_stride=False, model_name="diaresnet152b", **kwargs)
def diaresnet200(**kwargs):
"""
DIA-ResNet-200 model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=200, model_name="diaresnet200", **kwargs)
def diaresnet200b(**kwargs):
"""
DIA-ResNet-200 model with stride at the second convolution in bottleneck block from 'DIANet: Dense-and-Implicit
Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=200, conv1_stride=False, model_name="diaresnet200b", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
diaresnet10,
diaresnet12,
diaresnet14,
diaresnetbc14b,
diaresnet16,
diaresnet18,
diaresnet26,
diaresnetbc26b,
diaresnet34,
diaresnetbc38b,
diaresnet50,
diaresnet50b,
diaresnet101,
diaresnet101b,
diaresnet152,
diaresnet152b,
diaresnet200,
diaresnet200b,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != diaresnet10 or weight_count == 6297352)
assert (model != diaresnet12 or weight_count == 6371336)
assert (model != diaresnet14 or weight_count == 6666760)
assert (model != diaresnetbc14b or weight_count == 24023976)
assert (model != diaresnet16 or weight_count == 7847432)
assert (model != diaresnet18 or weight_count == 12568072)
assert (model != diaresnet26 or weight_count == 18838792)
assert (model != diaresnetbc26b or weight_count == 29954216)
assert (model != diaresnet34 or weight_count == 22676232)
assert (model != diaresnetbc38b or weight_count == 35884456)
assert (model != diaresnet50 or weight_count == 39516072)
assert (model != diaresnet50b or weight_count == 39516072)
assert (model != diaresnet101 or weight_count == 58508200)
assert (model != diaresnet101b or weight_count == 58508200)
assert (model != diaresnet152 or weight_count == 74151848)
assert (model != diaresnet152b or weight_count == 74151848)
assert (model != diaresnet200 or weight_count == 78632872)
assert (model != diaresnet200b or weight_count == 78632872)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 24,132 | 32.058904 | 116 | py |
null | qimera-main/pytorchcv/models/diaresnet_cifar.py | """
DIA-ResNet for CIFAR/SVHN, implemented in PyTorch.
Original paper: 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
"""
__all__ = ['CIFARDIAResNet', 'diaresnet20_cifar10', 'diaresnet20_cifar100', 'diaresnet20_svhn', 'diaresnet56_cifar10',
'diaresnet56_cifar100', 'diaresnet56_svhn', 'diaresnet110_cifar10', 'diaresnet110_cifar100',
'diaresnet110_svhn', 'diaresnet164bn_cifar10', 'diaresnet164bn_cifar100', 'diaresnet164bn_svhn',
'diaresnet1001_cifar10', 'diaresnet1001_cifar100', 'diaresnet1001_svhn', 'diaresnet1202_cifar10',
'diaresnet1202_cifar100', 'diaresnet1202_svhn']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv3x3_block, DualPathSequential
from .diaresnet import DIAAttention, DIAResUnit
class CIFARDIAResNet(nn.Module):
"""
DIA-ResNet model for CIFAR from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
num_classes : int, default 10
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
in_channels=3,
in_size=(32, 32),
num_classes=10):
super(CIFARDIAResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = DualPathSequential(return_two=False)
attention = DIAAttention(
in_x_features=channels_per_stage[0],
in_h_features=channels_per_stage[0])
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), DIAResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck,
conv1_stride=False,
attention=attention))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=8,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_diaresnet_cifar(num_classes,
blocks,
bottleneck,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create DIA-ResNet model for CIFAR with specific parameters.
Parameters:
----------
num_classes : int
Number of classification classes.
blocks : int
Number of blocks.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
assert (num_classes in [10, 100])
if bottleneck:
assert ((blocks - 2) % 9 == 0)
layers = [(blocks - 2) // 9] * 3
else:
assert ((blocks - 2) % 6 == 0)
layers = [(blocks - 2) // 6] * 3
channels_per_layers = [16, 32, 64]
init_block_channels = 16
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if bottleneck:
channels = [[cij * 4 for cij in ci] for ci in channels]
net = CIFARDIAResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
num_classes=num_classes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def diaresnet20_cifar10(num_classes=10, **kwargs):
"""
DIA-ResNet-20 model for CIFAR-10 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet_cifar(num_classes=num_classes, blocks=20, bottleneck=False, model_name="diaresnet20_cifar10",
**kwargs)
def diaresnet20_cifar100(num_classes=100, **kwargs):
"""
DIA-ResNet-20 model for CIFAR-100 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet_cifar(num_classes=num_classes, blocks=20, bottleneck=False, model_name="diaresnet20_cifar100",
**kwargs)
def diaresnet20_svhn(num_classes=10, **kwargs):
"""
DIA-ResNet-20 model for SVHN from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet_cifar(num_classes=num_classes, blocks=20, bottleneck=False, model_name="diaresnet20_svhn",
**kwargs)
def diaresnet56_cifar10(num_classes=10, **kwargs):
"""
DIA-ResNet-56 model for CIFAR-10 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet_cifar(num_classes=num_classes, blocks=56, bottleneck=False, model_name="diaresnet56_cifar10",
**kwargs)
def diaresnet56_cifar100(num_classes=100, **kwargs):
"""
DIA-ResNet-56 model for CIFAR-100 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet_cifar(num_classes=num_classes, blocks=56, bottleneck=False, model_name="diaresnet56_cifar100",
**kwargs)
def diaresnet56_svhn(num_classes=10, **kwargs):
"""
DIA-ResNet-56 model for SVHN from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet_cifar(num_classes=num_classes, blocks=56, bottleneck=False, model_name="diaresnet56_svhn",
**kwargs)
def diaresnet110_cifar10(num_classes=10, **kwargs):
"""
DIA-ResNet-110 model for CIFAR-10 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet_cifar(num_classes=num_classes, blocks=110, bottleneck=False, model_name="diaresnet110_cifar10",
**kwargs)
def diaresnet110_cifar100(num_classes=100, **kwargs):
"""
DIA-ResNet-110 model for CIFAR-100 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet_cifar(num_classes=num_classes, blocks=110, bottleneck=False,
model_name="diaresnet110_cifar100", **kwargs)
def diaresnet110_svhn(num_classes=10, **kwargs):
"""
DIA-ResNet-110 model for SVHN from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet_cifar(num_classes=num_classes, blocks=110, bottleneck=False, model_name="diaresnet110_svhn",
**kwargs)
def diaresnet164bn_cifar10(num_classes=10, **kwargs):
"""
DIA-ResNet-164(BN) model for CIFAR-10 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet_cifar(num_classes=num_classes, blocks=164, bottleneck=True,
model_name="diaresnet164bn_cifar10", **kwargs)
def diaresnet164bn_cifar100(num_classes=100, **kwargs):
"""
DIA-ResNet-164(BN) model for CIFAR-100 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet_cifar(num_classes=num_classes, blocks=164, bottleneck=True,
model_name="diaresnet164bn_cifar100", **kwargs)
def diaresnet164bn_svhn(num_classes=10, **kwargs):
"""
DIA-ResNet-164(BN) model for SVHN from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet_cifar(num_classes=num_classes, blocks=164, bottleneck=True, model_name="diaresnet164bn_svhn",
**kwargs)
def diaresnet1001_cifar10(num_classes=10, **kwargs):
"""
DIA-ResNet-1001 model for CIFAR-10 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet_cifar(num_classes=num_classes, blocks=1001, bottleneck=True,
model_name="diaresnet1001_cifar10", **kwargs)
def diaresnet1001_cifar100(num_classes=100, **kwargs):
"""
DIA-ResNet-1001 model for CIFAR-100 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet_cifar(num_classes=num_classes, blocks=1001, bottleneck=True,
model_name="diaresnet1001_cifar100", **kwargs)
def diaresnet1001_svhn(num_classes=10, **kwargs):
"""
DIA-ResNet-1001 model for SVHN from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet_cifar(num_classes=num_classes, blocks=1001, bottleneck=True, model_name="diaresnet1001_svhn",
**kwargs)
def diaresnet1202_cifar10(num_classes=10, **kwargs):
"""
DIA-ResNet-1202 model for CIFAR-10 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet_cifar(num_classes=num_classes, blocks=1202, bottleneck=False,
model_name="diaresnet1202_cifar10", **kwargs)
def diaresnet1202_cifar100(num_classes=100, **kwargs):
"""
DIA-ResNet-1202 model for CIFAR-100 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet_cifar(num_classes=num_classes, blocks=1202, bottleneck=False,
model_name="diaresnet1202_cifar100", **kwargs)
def diaresnet1202_svhn(num_classes=10, **kwargs):
"""
DIA-ResNet-1202 model for SVHN from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diaresnet_cifar(num_classes=num_classes, blocks=1202, bottleneck=False, model_name="diaresnet1202_svhn",
**kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
(diaresnet20_cifar10, 10),
(diaresnet20_cifar100, 100),
(diaresnet20_svhn, 10),
(diaresnet56_cifar10, 10),
(diaresnet56_cifar100, 100),
(diaresnet56_svhn, 10),
(diaresnet110_cifar10, 10),
(diaresnet110_cifar100, 100),
(diaresnet110_svhn, 10),
(diaresnet164bn_cifar10, 10),
(diaresnet164bn_cifar100, 100),
(diaresnet164bn_svhn, 10),
(diaresnet1001_cifar10, 10),
(diaresnet1001_cifar100, 100),
(diaresnet1001_svhn, 10),
(diaresnet1202_cifar10, 10),
(diaresnet1202_cifar100, 100),
(diaresnet1202_svhn, 10),
]
for model, num_classes in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != diaresnet20_cifar10 or weight_count == 286866)
assert (model != diaresnet20_cifar100 or weight_count == 292716)
assert (model != diaresnet20_svhn or weight_count == 286866)
assert (model != diaresnet56_cifar10 or weight_count == 870162)
assert (model != diaresnet56_cifar100 or weight_count == 876012)
assert (model != diaresnet56_svhn or weight_count == 870162)
assert (model != diaresnet110_cifar10 or weight_count == 1745106)
assert (model != diaresnet110_cifar100 or weight_count == 1750956)
assert (model != diaresnet110_svhn or weight_count == 1745106)
assert (model != diaresnet164bn_cifar10 or weight_count == 1923002)
assert (model != diaresnet164bn_cifar100 or weight_count == 1946132)
assert (model != diaresnet164bn_svhn or weight_count == 1923002)
assert (model != diaresnet1001_cifar10 or weight_count == 10547450)
assert (model != diaresnet1001_cifar100 or weight_count == 10570580)
assert (model != diaresnet1001_svhn or weight_count == 10547450)
assert (model != diaresnet1202_cifar10 or weight_count == 19438418)
assert (model != diaresnet1202_cifar100 or weight_count == 19444268)
assert (model != diaresnet1202_svhn or weight_count == 19438418)
x = torch.randn(1, 3, 32, 32)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, num_classes))
if __name__ == "__main__":
_test()
| 19,959 | 35.489945 | 120 | py |
null | qimera-main/pytorchcv/models/diracnetv2.py | """
DiracNetV2 for ImageNet-1K, implemented in PyTorch.
Original paper: 'DiracNets: Training Very Deep Neural Networks Without Skip-Connections,'
https://arxiv.org/abs/1706.00388.
"""
__all__ = ['DiracNetV2', 'diracnet18v2', 'diracnet34v2']
import os
import torch.nn as nn
import torch.nn.init as init
class DiracConv(nn.Module):
"""
DiracNetV2 specific convolution block with pre-activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding):
super(DiracConv, self).__init__()
self.activ = nn.ReLU(inplace=True)
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
bias=True)
def forward(self, x):
x = self.activ(x)
x = self.conv(x)
return x
def dirac_conv3x3(in_channels,
out_channels):
"""
3x3 version of the DiracNetV2 specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
return DiracConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=1,
padding=1)
class DiracInitBlock(nn.Module):
"""
DiracNetV2 specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(DiracInitBlock, self).__init__()
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=7,
stride=2,
padding=3,
bias=True)
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=1)
def forward(self, x):
x = self.conv(x)
x = self.pool(x)
return x
class DiracNetV2(nn.Module):
"""
DiracNetV2 model from 'DiracNets: Training Very Deep Neural Networks Without Skip-Connections,'
https://arxiv.org/abs/1706.00388.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(DiracNetV2, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", DiracInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stage.add_module("unit{}".format(j + 1), dirac_conv3x3(
in_channels=in_channels,
out_channels=out_channels))
in_channels = out_channels
if i != len(channels) - 1:
stage.add_module("pool{}".format(i + 1), nn.MaxPool2d(
kernel_size=2,
stride=2,
padding=0))
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_activ', nn.ReLU(inplace=True))
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_diracnetv2(blocks,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create DiracNetV2 model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 18:
layers = [4, 4, 4, 4]
elif blocks == 34:
layers = [6, 8, 12, 6]
else:
raise ValueError("Unsupported DiracNetV2 with number of blocks: {}".format(blocks))
channels_per_layers = [64, 128, 256, 512]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
init_block_channels = 64
net = DiracNetV2(
channels=channels,
init_block_channels=init_block_channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def diracnet18v2(**kwargs):
"""
DiracNetV2 model from 'DiracNets: Training Very Deep Neural Networks Without Skip-Connections,'
https://arxiv.org/abs/1706.00388.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diracnetv2(blocks=18, model_name="diracnet18v2", **kwargs)
def diracnet34v2(**kwargs):
"""
DiracNetV2 model from 'DiracNets: Training Very Deep Neural Networks Without Skip-Connections,'
https://arxiv.org/abs/1706.00388.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_diracnetv2(blocks=34, model_name="diracnet34v2", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
diracnet18v2,
diracnet34v2,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != diracnet18v2 or weight_count == 11511784)
assert (model != diracnet34v2 or weight_count == 21616232)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 8,444 | 27.72449 | 115 | py |
null | qimera-main/pytorchcv/models/dla.py | """
DLA for ImageNet-1K, implemented in PyTorch.
Original paper: 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484.
"""
__all__ = ['DLA', 'dla34', 'dla46c', 'dla46xc', 'dla60', 'dla60x', 'dla60xc', 'dla102', 'dla102x', 'dla102x2', 'dla169']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1, conv1x1_block, conv3x3_block, conv7x7_block
from .resnet import ResBlock, ResBottleneck
from .resnext import ResNeXtBottleneck
class DLABottleneck(ResBottleneck):
"""
DLA bottleneck block for residual path in residual block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
bottleneck_factor : int, default 2
Bottleneck factor.
"""
def __init__(self,
in_channels,
out_channels,
stride,
bottleneck_factor=2):
super(DLABottleneck, self).__init__(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck_factor=bottleneck_factor)
class DLABottleneckX(ResNeXtBottleneck):
"""
DLA ResNeXt-like bottleneck block for residual path in residual block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
cardinality: int, default 32
Number of groups.
bottleneck_width: int, default 8
Width of bottleneck block.
"""
def __init__(self,
in_channels,
out_channels,
stride,
cardinality=32,
bottleneck_width=8):
super(DLABottleneckX, self).__init__(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
cardinality=cardinality,
bottleneck_width=bottleneck_width)
class DLAResBlock(nn.Module):
"""
DLA residual block with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
body_class : nn.Module, default ResBlock
Residual block body class.
return_down : bool, default False
Whether return downsample result.
"""
def __init__(self,
in_channels,
out_channels,
stride,
body_class=ResBlock,
return_down=False):
super(DLAResBlock, self).__init__()
self.return_down = return_down
self.downsample = (stride > 1)
self.project = (in_channels != out_channels)
self.body = body_class(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
self.activ = nn.ReLU(inplace=True)
if self.downsample:
self.downsample_pool = nn.MaxPool2d(
kernel_size=stride,
stride=stride)
if self.project:
self.project_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
activation=None)
def forward(self, x):
down = self.downsample_pool(x) if self.downsample else x
identity = self.project_conv(down) if self.project else down
if identity is None:
identity = x
x = self.body(x)
x += identity
x = self.activ(x)
if self.return_down:
return x, down
else:
return x
class DLARoot(nn.Module):
"""
DLA root block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
residual : bool
Whether use residual connection.
"""
def __init__(self,
in_channels,
out_channels,
residual):
super(DLARoot, self).__init__()
self.residual = residual
self.conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
activation=None)
self.activ = nn.ReLU(inplace=True)
def forward(self, x2, x1, extra):
last_branch = x2
x = torch.cat((x2, x1) + tuple(extra), dim=1)
x = self.conv(x)
if self.residual:
x += last_branch
x = self.activ(x)
return x
class DLATree(nn.Module):
"""
DLA tree unit. It's like iterative stage.
Parameters:
----------
levels : int
Number of levels in the stage.
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
res_body_class : nn.Module
Residual block body class.
stride : int or tuple/list of 2 int
Strides of the convolution in a residual block.
root_residual : bool
Whether use residual connection in the root.
root_dim : int
Number of input channels in the root block.
first_tree : bool, default False
Is this tree stage the first stage in the net.
input_level : bool, default True
Is this tree unit the first unit in the stage.
return_down : bool, default False
Whether return downsample result.
"""
def __init__(self,
levels,
in_channels,
out_channels,
res_body_class,
stride,
root_residual,
root_dim=0,
first_tree=False,
input_level=True,
return_down=False):
super(DLATree, self).__init__()
self.return_down = return_down
self.add_down = (input_level and not first_tree)
self.root_level = (levels == 1)
if root_dim == 0:
root_dim = 2 * out_channels
if self.add_down:
root_dim += in_channels
if self.root_level:
self.tree1 = DLAResBlock(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
body_class=res_body_class,
return_down=True)
self.tree2 = DLAResBlock(
in_channels=out_channels,
out_channels=out_channels,
stride=1,
body_class=res_body_class,
return_down=False)
else:
self.tree1 = DLATree(
levels=levels - 1,
in_channels=in_channels,
out_channels=out_channels,
res_body_class=res_body_class,
stride=stride,
root_residual=root_residual,
root_dim=0,
input_level=False,
return_down=True)
self.tree2 = DLATree(
levels=levels - 1,
in_channels=out_channels,
out_channels=out_channels,
res_body_class=res_body_class,
stride=1,
root_residual=root_residual,
root_dim=root_dim + out_channels,
input_level=False,
return_down=False)
if self.root_level:
self.root = DLARoot(
in_channels=root_dim,
out_channels=out_channels,
residual=root_residual)
def forward(self, x, extra=None):
extra = [] if extra is None else extra
x1, down = self.tree1(x)
if self.add_down:
extra.append(down)
if self.root_level:
x2 = self.tree2(x1)
x = self.root(x2, x1, extra)
else:
extra.append(x1)
x = self.tree2(x1, extra)
if self.return_down:
return x, down
else:
return x
class DLAInitBlock(nn.Module):
"""
DLA specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(DLAInitBlock, self).__init__()
mid_channels = out_channels // 2
self.conv1 = conv7x7_block(
in_channels=in_channels,
out_channels=mid_channels)
self.conv2 = conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels)
self.conv3 = conv3x3_block(
in_channels=mid_channels,
out_channels=out_channels,
stride=2)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class DLA(nn.Module):
"""
DLA model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484.
Parameters:
----------
levels : int
Number of levels in each stage.
channels : list of int
Number of output channels for each stage.
init_block_channels : int
Number of output channels for the initial unit.
res_body_class : nn.Module
Residual block body class.
residual_root : bool
Whether use residual connection in the root blocks.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
levels,
channels,
init_block_channels,
res_body_class,
residual_root,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(DLA, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", DLAInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i in range(len(levels)):
levels_i = levels[i]
out_channels = channels[i]
first_tree = (i == 0)
self.features.add_module("stage{}".format(i + 1), DLATree(
levels=levels_i,
in_channels=in_channels,
out_channels=out_channels,
res_body_class=res_body_class,
stride=2,
root_residual=residual_root,
first_tree=first_tree))
in_channels = out_channels
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = conv1x1(
in_channels=in_channels,
out_channels=num_classes,
bias=True)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = self.output(x)
x = x.view(x.size(0), -1)
return x
def get_dla(levels,
channels,
res_body_class,
residual_root=False,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create DLA model with specific parameters.
Parameters:
----------
levels : int
Number of levels in each stage.
channels : list of int
Number of output channels for each stage.
res_body_class : nn.Module
Residual block body class.
residual_root : bool, default False
Whether use residual connection in the root blocks.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
init_block_channels = 32
net = DLA(
levels=levels,
channels=channels,
init_block_channels=init_block_channels,
res_body_class=res_body_class,
residual_root=residual_root,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def dla34(**kwargs):
"""
DLA-34 model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_dla(levels=[1, 2, 2, 1], channels=[64, 128, 256, 512], res_body_class=ResBlock, model_name="dla34",
**kwargs)
def dla46c(**kwargs):
"""
DLA-46-C model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_dla(levels=[1, 2, 2, 1], channels=[64, 64, 128, 256], res_body_class=DLABottleneck, model_name="dla46c",
**kwargs)
def dla46xc(**kwargs):
"""
DLA-X-46-C model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_dla(levels=[1, 2, 2, 1], channels=[64, 64, 128, 256], res_body_class=DLABottleneckX,
model_name="dla46xc", **kwargs)
def dla60(**kwargs):
"""
DLA-60 model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_dla(levels=[1, 2, 3, 1], channels=[128, 256, 512, 1024], res_body_class=DLABottleneck,
model_name="dla60", **kwargs)
def dla60x(**kwargs):
"""
DLA-X-60 model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_dla(levels=[1, 2, 3, 1], channels=[128, 256, 512, 1024], res_body_class=DLABottleneckX,
model_name="dla60x", **kwargs)
def dla60xc(**kwargs):
"""
DLA-X-60-C model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_dla(levels=[1, 2, 3, 1], channels=[64, 64, 128, 256], res_body_class=DLABottleneckX,
model_name="dla60xc", **kwargs)
def dla102(**kwargs):
"""
DLA-102 model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_dla(levels=[1, 3, 4, 1], channels=[128, 256, 512, 1024], res_body_class=DLABottleneck,
residual_root=True, model_name="dla102", **kwargs)
def dla102x(**kwargs):
"""
DLA-X-102 model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_dla(levels=[1, 3, 4, 1], channels=[128, 256, 512, 1024], res_body_class=DLABottleneckX,
residual_root=True, model_name="dla102x", **kwargs)
def dla102x2(**kwargs):
"""
DLA-X2-102 model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
class DLABottleneckX64(DLABottleneckX):
def __init__(self, in_channels, out_channels, stride):
super(DLABottleneckX64, self).__init__(in_channels, out_channels, stride, cardinality=64)
return get_dla(levels=[1, 3, 4, 1], channels=[128, 256, 512, 1024], res_body_class=DLABottleneckX64,
residual_root=True, model_name="dla102x2", **kwargs)
def dla169(**kwargs):
"""
DLA-169 model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_dla(levels=[2, 3, 5, 1], channels=[128, 256, 512, 1024], res_body_class=DLABottleneck,
residual_root=True, model_name="dla169", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
dla34,
dla46c,
dla46xc,
dla60,
dla60x,
dla60xc,
dla102,
dla102x,
dla102x2,
dla169,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != dla34 or weight_count == 15742104)
assert (model != dla46c or weight_count == 1301400)
assert (model != dla46xc or weight_count == 1068440)
assert (model != dla60 or weight_count == 22036632)
assert (model != dla60x or weight_count == 17352344)
assert (model != dla60xc or weight_count == 1319832)
assert (model != dla102 or weight_count == 33268888)
assert (model != dla102x or weight_count == 26309272)
assert (model != dla102x2 or weight_count == 41282200)
assert (model != dla169 or weight_count == 53389720)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 19,884 | 29.734158 | 120 | py |
null | qimera-main/pytorchcv/models/dpn.py | """
DPN for ImageNet-1K, implemented in PyTorch.
Original paper: 'Dual Path Networks,' https://arxiv.org/abs/1707.01629.
"""
__all__ = ['DPN', 'dpn68', 'dpn68b', 'dpn98', 'dpn107', 'dpn131']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1, DualPathSequential
class GlobalAvgMaxPool2D(nn.Module):
"""
Global average+max pooling operation for spatial data.
Parameters:
----------
output_size : int, default 1
The target output size.
"""
def __init__(self,
output_size=1):
super(GlobalAvgMaxPool2D, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(output_size=output_size)
self.max_pool = nn.AdaptiveMaxPool2d(output_size=output_size)
def forward(self, x):
x_avg = self.avg_pool(x)
x_max = self.max_pool(x)
x = 0.5 * (x_avg + x_max)
return x
def dpn_batch_norm(channels):
"""
DPN specific Batch normalization layer.
Parameters:
----------
channels : int
Number of channels in input data.
"""
return nn.BatchNorm2d(
num_features=channels,
eps=0.001)
class PreActivation(nn.Module):
"""
DPN specific block, which performs the preactivation like in RreResNet.
Parameters:
----------
channels : int
Number of channels.
"""
def __init__(self,
channels):
super(PreActivation, self).__init__()
self.bn = dpn_batch_norm(channels=channels)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
x = self.bn(x)
x = self.activ(x)
return x
class DPNConv(nn.Module):
"""
DPN specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
groups : int
Number of groups.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
groups):
super(DPNConv, self).__init__()
self.bn = dpn_batch_norm(channels=in_channels)
self.activ = nn.ReLU(inplace=True)
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
groups=groups,
bias=False)
def forward(self, x):
x = self.bn(x)
x = self.activ(x)
x = self.conv(x)
return x
def dpn_conv1x1(in_channels,
out_channels,
stride=1):
"""
1x1 version of the DPN specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
"""
return DPNConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
stride=stride,
padding=0,
groups=1)
def dpn_conv3x3(in_channels,
out_channels,
stride,
groups):
"""
3x3 version of the DPN specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
groups : int
Number of groups.
"""
return DPNConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=stride,
padding=1,
groups=groups)
class DPNUnit(nn.Module):
"""
DPN unit.
Parameters:
----------
in_channels : int
Number of input channels.
mid_channels : int
Number of intermediate channels.
bw : int
Number of residual channels.
inc : int
Incrementing step for channels.
groups : int
Number of groups in the units.
has_proj : bool
Whether to use projection.
key_stride : int
Key strides of the convolutions.
b_case : bool, default False
Whether to use B-case model.
"""
def __init__(self,
in_channels,
mid_channels,
bw,
inc,
groups,
has_proj,
key_stride,
b_case=False):
super(DPNUnit, self).__init__()
self.bw = bw
self.has_proj = has_proj
self.b_case = b_case
if self.has_proj:
self.conv_proj = dpn_conv1x1(
in_channels=in_channels,
out_channels=bw + 2 * inc,
stride=key_stride)
self.conv1 = dpn_conv1x1(
in_channels=in_channels,
out_channels=mid_channels)
self.conv2 = dpn_conv3x3(
in_channels=mid_channels,
out_channels=mid_channels,
stride=key_stride,
groups=groups)
if b_case:
self.preactiv = PreActivation(channels=mid_channels)
self.conv3a = conv1x1(
in_channels=mid_channels,
out_channels=bw)
self.conv3b = conv1x1(
in_channels=mid_channels,
out_channels=inc)
else:
self.conv3 = dpn_conv1x1(
in_channels=mid_channels,
out_channels=bw + inc)
def forward(self, x1, x2=None):
x_in = torch.cat((x1, x2), dim=1) if x2 is not None else x1
if self.has_proj:
x_s = self.conv_proj(x_in)
x_s1 = x_s[:, :self.bw, :, :]
x_s2 = x_s[:, self.bw:, :, :]
else:
assert (x2 is not None)
x_s1 = x1
x_s2 = x2
x_in = self.conv1(x_in)
x_in = self.conv2(x_in)
if self.b_case:
x_in = self.preactiv(x_in)
y1 = self.conv3a(x_in)
y2 = self.conv3b(x_in)
else:
x_in = self.conv3(x_in)
y1 = x_in[:, :self.bw, :, :]
y2 = x_in[:, self.bw:, :, :]
residual = x_s1 + y1
dense = torch.cat((x_s2, y2), dim=1)
return residual, dense
class DPNInitBlock(nn.Module):
"""
DPN specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
padding):
super(DPNInitBlock, self).__init__()
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=2,
padding=padding,
bias=False)
self.bn = dpn_batch_norm(channels=out_channels)
self.activ = nn.ReLU(inplace=True)
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=1)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
x = self.activ(x)
x = self.pool(x)
return x
class DPNFinalBlock(nn.Module):
"""
DPN final block, which performs the preactivation with cutting.
Parameters:
----------
channels : int
Number of channels.
"""
def __init__(self,
channels):
super(DPNFinalBlock, self).__init__()
self.activ = PreActivation(channels=channels)
def forward(self, x1, x2):
assert (x2 is not None)
x = torch.cat((x1, x2), dim=1)
x = self.activ(x)
return x, None
class DPN(nn.Module):
"""
DPN model from 'Dual Path Networks,' https://arxiv.org/abs/1707.01629.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
init_block_kernel_size : int or tuple/list of 2 int
Convolution window size for the initial unit.
init_block_padding : int or tuple/list of 2 int
Padding value for convolution layer in the initial unit.
rs : list f int
Number of intermediate channels for each unit.
bws : list f int
Number of residual channels for each unit.
incs : list f int
Incrementing step for channels for each unit.
groups : int
Number of groups in the units.
b_case : bool
Whether to use B-case model.
for_training : bool
Whether to use model for training.
test_time_pool : bool
Whether to use the avg-max pooling in the inference mode.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
init_block_kernel_size,
init_block_padding,
rs,
bws,
incs,
groups,
b_case,
for_training,
test_time_pool,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(DPN, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = DualPathSequential(
return_two=False,
first_ordinals=1,
last_ordinals=0)
self.features.add_module("init_block", DPNInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
kernel_size=init_block_kernel_size,
padding=init_block_padding))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = DualPathSequential()
r = rs[i]
bw = bws[i]
inc = incs[i]
for j, out_channels in enumerate(channels_per_stage):
has_proj = (j == 0)
key_stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), DPNUnit(
in_channels=in_channels,
mid_channels=r,
bw=bw,
inc=inc,
groups=groups,
has_proj=has_proj,
key_stride=key_stride,
b_case=b_case))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_block', DPNFinalBlock(channels=in_channels))
self.output = nn.Sequential()
if for_training or not test_time_pool:
self.output.add_module('final_pool', nn.AdaptiveAvgPool2d(output_size=1))
self.output.add_module('classifier', conv1x1(
in_channels=in_channels,
out_channels=num_classes,
bias=True))
else:
self.output.add_module('avg_pool', nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output.add_module('classifier', conv1x1(
in_channels=in_channels,
out_channels=num_classes,
bias=True))
self.output.add_module('avgmax_pool', GlobalAvgMaxPool2D())
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = self.output(x)
x = x.view(x.size(0), -1)
return x
def get_dpn(num_layers,
b_case=False,
for_training=False,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create DPN model with specific parameters.
Parameters:
----------
num_layers : int
Number of layers.
b_case : bool, default False
Whether to use B-case model.
for_training : bool
Whether to use model for training.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if num_layers == 68:
init_block_channels = 10
init_block_kernel_size = 3
init_block_padding = 1
bw_factor = 1
k_r = 128
groups = 32
k_sec = (3, 4, 12, 3)
incs = (16, 32, 32, 64)
test_time_pool = True
elif num_layers == 98:
init_block_channels = 96
init_block_kernel_size = 7
init_block_padding = 3
bw_factor = 4
k_r = 160
groups = 40
k_sec = (3, 6, 20, 3)
incs = (16, 32, 32, 128)
test_time_pool = True
elif num_layers == 107:
init_block_channels = 128
init_block_kernel_size = 7
init_block_padding = 3
bw_factor = 4
k_r = 200
groups = 50
k_sec = (4, 8, 20, 3)
incs = (20, 64, 64, 128)
test_time_pool = True
elif num_layers == 131:
init_block_channels = 128
init_block_kernel_size = 7
init_block_padding = 3
bw_factor = 4
k_r = 160
groups = 40
k_sec = (4, 8, 28, 3)
incs = (16, 32, 32, 128)
test_time_pool = True
else:
raise ValueError("Unsupported DPN version with number of layers {}".format(num_layers))
channels = [[0] * li for li in k_sec]
rs = [0 * li for li in k_sec]
bws = [0 * li for li in k_sec]
for i in range(len(k_sec)):
rs[i] = (2 ** i) * k_r
bws[i] = (2 ** i) * 64 * bw_factor
inc = incs[i]
channels[i][0] = bws[i] + 3 * inc
for j in range(1, k_sec[i]):
channels[i][j] = channels[i][j - 1] + inc
net = DPN(
channels=channels,
init_block_channels=init_block_channels,
init_block_kernel_size=init_block_kernel_size,
init_block_padding=init_block_padding,
rs=rs,
bws=bws,
incs=incs,
groups=groups,
b_case=b_case,
for_training=for_training,
test_time_pool=test_time_pool,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def dpn68(**kwargs):
"""
DPN-68 model from 'Dual Path Networks,' https://arxiv.org/abs/1707.01629.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_dpn(num_layers=68, b_case=False, model_name="dpn68", **kwargs)
def dpn68b(**kwargs):
"""
DPN-68b model from 'Dual Path Networks,' https://arxiv.org/abs/1707.01629.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_dpn(num_layers=68, b_case=True, model_name="dpn68b", **kwargs)
def dpn98(**kwargs):
"""
DPN-98 model from 'Dual Path Networks,' https://arxiv.org/abs/1707.01629.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_dpn(num_layers=98, b_case=False, model_name="dpn98", **kwargs)
def dpn107(**kwargs):
"""
DPN-107 model from 'Dual Path Networks,' https://arxiv.org/abs/1707.01629.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_dpn(num_layers=107, b_case=False, model_name="dpn107", **kwargs)
def dpn131(**kwargs):
"""
DPN-131 model from 'Dual Path Networks,' https://arxiv.org/abs/1707.01629.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_dpn(num_layers=131, b_case=False, model_name="dpn131", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
for_training = False
models = [
dpn68,
# dpn68b,
dpn98,
# dpn107,
dpn131,
]
for model in models:
net = model(pretrained=pretrained, for_training=for_training)
net.train()
# net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != dpn68 or weight_count == 12611602)
assert (model != dpn68b or weight_count == 12611602)
assert (model != dpn98 or weight_count == 61570728)
assert (model != dpn107 or weight_count == 86917800)
assert (model != dpn131 or weight_count == 79254504)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 18,976 | 27.709531 | 115 | py |
null | qimera-main/pytorchcv/models/drn.py | """
DRN for ImageNet-1K, implemented in PyTorch.
Original paper: 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914.
"""
__all__ = ['DRN', 'drnc26', 'drnc42', 'drnc58', 'drnd22', 'drnd38', 'drnd54', 'drnd105']
import os
import torch.nn as nn
import torch.nn.init as init
class DRNConv(nn.Module):
"""
DRN specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
dilation : int or tuple/list of 2 int
Dilation value for convolution layer.
activate : bool
Whether activate the convolution block.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
dilation,
activate):
super(DRNConv, self).__init__()
self.activate = activate
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
bias=False)
self.bn = nn.BatchNorm2d(num_features=out_channels)
if self.activate:
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
if self.activate:
x = self.activ(x)
return x
def drn_conv1x1(in_channels,
out_channels,
stride,
activate):
"""
1x1 version of the DRN specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
activate : bool
Whether activate the convolution block.
"""
return DRNConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
stride=stride,
padding=0,
dilation=1,
activate=activate)
def drn_conv3x3(in_channels,
out_channels,
stride,
dilation,
activate):
"""
3x3 version of the DRN specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
dilation : int or tuple/list of 2 int
Padding/dilation value for convolution layer.
activate : bool
Whether activate the convolution block.
"""
return DRNConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=stride,
padding=dilation,
dilation=dilation,
activate=activate)
class DRNBlock(nn.Module):
"""
Simple DRN block for residual path in DRN unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
dilation : int or tuple/list of 2 int
Padding/dilation value for convolution layers.
"""
def __init__(self,
in_channels,
out_channels,
stride,
dilation):
super(DRNBlock, self).__init__()
self.conv1 = drn_conv3x3(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
dilation=dilation,
activate=True)
self.conv2 = drn_conv3x3(
in_channels=out_channels,
out_channels=out_channels,
stride=1,
dilation=dilation,
activate=False)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class DRNBottleneck(nn.Module):
"""
DRN bottleneck block for residual path in DRN unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
dilation : int or tuple/list of 2 int
Padding/dilation value for 3x3 convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
stride,
dilation):
super(DRNBottleneck, self).__init__()
mid_channels = out_channels // 4
self.conv1 = drn_conv1x1(
in_channels=in_channels,
out_channels=mid_channels,
stride=1,
activate=True)
self.conv2 = drn_conv3x3(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride,
dilation=dilation,
activate=True)
self.conv3 = drn_conv1x1(
in_channels=mid_channels,
out_channels=out_channels,
stride=1,
activate=False)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class DRNUnit(nn.Module):
"""
DRN unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
dilation : int or tuple/list of 2 int
Padding/dilation value for 3x3 convolution layers.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
simplified : bool
Whether to use a simple or simplified block in units.
residual : bool
Whether do residual calculations.
"""
def __init__(self,
in_channels,
out_channels,
stride,
dilation,
bottleneck,
simplified,
residual):
super(DRNUnit, self).__init__()
assert residual or (not bottleneck)
assert (not (bottleneck and simplified))
assert (not (residual and simplified))
self.residual = residual
self.resize_identity = ((in_channels != out_channels) or (stride != 1)) and self.residual and (not simplified)
if bottleneck:
self.body = DRNBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
dilation=dilation)
elif simplified:
self.body = drn_conv3x3(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
dilation=dilation,
activate=False)
else:
self.body = DRNBlock(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
dilation=dilation)
if self.resize_identity:
self.identity_conv = drn_conv1x1(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
activate=False)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
if self.residual:
x = x + identity
x = self.activ(x)
return x
def drn_init_block(in_channels,
out_channels):
"""
DRN specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
return DRNConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=7,
stride=1,
padding=3,
dilation=1,
activate=True)
class DRN(nn.Module):
"""
DRN-C&D model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
dilations : list of list of int
Dilation values for 3x3 convolution layers for each unit.
bottlenecks : list of list of int
Whether to use a bottleneck or simple block in each unit.
simplifieds : list of list of int
Whether to use a simple or simplified block in each unit.
residuals : list of list of int
Whether to use residual block in each unit.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
dilations,
bottlenecks,
simplifieds,
residuals,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(DRN, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", drn_init_block(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), DRNUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
dilation=dilations[i][j],
bottleneck=(bottlenecks[i][j] == 1),
simplified=(simplifieds[i][j] == 1),
residual=(residuals[i][j] == 1)))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=28,
stride=1))
self.output = nn.Conv2d(
in_channels=in_channels,
out_channels=num_classes,
kernel_size=1)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = self.output(x)
x = x.view(x.size(0), -1)
return x
def get_drn(blocks,
simplified=False,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create DRN-C or DRN-D model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
simplified : bool, default False
Whether to use simplified scheme (D architecture).
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 22:
assert simplified
layers = [1, 1, 2, 2, 2, 2, 1, 1]
elif blocks == 26:
layers = [1, 1, 2, 2, 2, 2, 1, 1]
elif blocks == 38:
assert simplified
layers = [1, 1, 3, 4, 6, 3, 1, 1]
elif blocks == 42:
layers = [1, 1, 3, 4, 6, 3, 1, 1]
elif blocks == 54:
assert simplified
layers = [1, 1, 3, 4, 6, 3, 1, 1]
elif blocks == 58:
layers = [1, 1, 3, 4, 6, 3, 1, 1]
elif blocks == 105:
assert simplified
layers = [1, 1, 3, 4, 23, 3, 1, 1]
else:
raise ValueError("Unsupported DRN with number of blocks: {}".format(blocks))
if blocks < 50:
channels_per_layers = [16, 32, 64, 128, 256, 512, 512, 512]
bottlenecks_per_layers = [0, 0, 0, 0, 0, 0, 0, 0]
else:
channels_per_layers = [16, 32, 256, 512, 1024, 2048, 512, 512]
bottlenecks_per_layers = [0, 0, 1, 1, 1, 1, 0, 0]
if simplified:
simplifieds_per_layers = [1, 1, 0, 0, 0, 0, 1, 1]
residuals_per_layers = [0, 0, 1, 1, 1, 1, 0, 0]
else:
simplifieds_per_layers = [0, 0, 0, 0, 0, 0, 0, 0]
residuals_per_layers = [1, 1, 1, 1, 1, 1, 0, 0]
dilations_per_layers = [1, 1, 1, 1, 2, 4, 2, 1]
downsample = [0, 1, 1, 1, 0, 0, 0, 0]
def expand(property_per_layers):
from functools import reduce
return reduce(
lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]],
zip(property_per_layers, layers, downsample),
[[]])
channels = expand(channels_per_layers)
dilations = expand(dilations_per_layers)
bottlenecks = expand(bottlenecks_per_layers)
residuals = expand(residuals_per_layers)
simplifieds = expand(simplifieds_per_layers)
init_block_channels = channels_per_layers[0]
net = DRN(
channels=channels,
init_block_channels=init_block_channels,
dilations=dilations,
bottlenecks=bottlenecks,
simplifieds=simplifieds,
residuals=residuals,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def drnc26(**kwargs):
"""
DRN-C-26 model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_drn(blocks=26, model_name="drnc26", **kwargs)
def drnc42(**kwargs):
"""
DRN-C-42 model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_drn(blocks=42, model_name="drnc42", **kwargs)
def drnc58(**kwargs):
"""
DRN-C-58 model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_drn(blocks=58, model_name="drnc58", **kwargs)
def drnd22(**kwargs):
"""
DRN-D-58 model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_drn(blocks=22, simplified=True, model_name="drnd22", **kwargs)
def drnd38(**kwargs):
"""
DRN-D-38 model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_drn(blocks=38, simplified=True, model_name="drnd38", **kwargs)
def drnd54(**kwargs):
"""
DRN-D-54 model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_drn(blocks=54, simplified=True, model_name="drnd54", **kwargs)
def drnd105(**kwargs):
"""
DRN-D-105 model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_drn(blocks=105, simplified=True, model_name="drnd105", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
drnc26,
drnc42,
drnc58,
drnd22,
drnd38,
drnd54,
drnd105,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != drnc26 or weight_count == 21126584)
assert (model != drnc42 or weight_count == 31234744)
assert (model != drnc58 or weight_count == 40542008) # 41591608
assert (model != drnd22 or weight_count == 16393752)
assert (model != drnd38 or weight_count == 26501912)
assert (model != drnd54 or weight_count == 35809176)
assert (model != drnd105 or weight_count == 54801304)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 18,826 | 28.695584 | 118 | py |
null | qimera-main/pytorchcv/models/efficientnet.py | """
EfficientNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,'
https://arxiv.org/abs/1905.11946.
"""
__all__ = ['EfficientNet', 'efficientnet_b0', 'efficientnet_b1', 'efficientnet_b2', 'efficientnet_b3',
'efficientnet_b4', 'efficientnet_b5', 'efficientnet_b6', 'efficientnet_b7', 'efficientnet_b0b',
'efficientnet_b1b', 'efficientnet_b2b', 'efficientnet_b3b', 'efficientnet_b4b', 'efficientnet_b5b',
'efficientnet_b6b', 'efficientnet_b7b']
import os
import math
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from .common import round_channels, conv1x1_block, conv3x3_block, dwconv3x3_block, dwconv5x5_block, SEBlock
def calc_tf_padding(x,
kernel_size,
stride=1,
dilation=1):
"""
Calculate TF-same like padding size.
Parameters:
----------
x : tensor
Input tensor.
kernel_size : int
Convolution window size.
stride : int, default 1
Strides of the convolution.
dilation : int, default 1
Dilation value for convolution layer.
Returns
-------
tuple of 4 int
The size of the padding.
"""
height, width = x.size()[2:]
oh = math.ceil(height / stride)
ow = math.ceil(width / stride)
pad_h = max((oh - 1) * stride + (kernel_size - 1) * dilation + 1 - height, 0)
pad_w = max((ow - 1) * stride + (kernel_size - 1) * dilation + 1 - width, 0)
return pad_h // 2, pad_h - pad_h // 2, pad_w // 2, pad_w - pad_w // 2
class EffiDwsConvUnit(nn.Module):
"""
EfficientNet specific depthwise separable convolution block/unit with BatchNorms and activations at each convolution
layers.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the second convolution layer.
bn_eps : float
Small float added to variance in Batch norm.
activation : str
Name of activation function.
tf_mode : bool
Whether to use TF-like mode.
"""
def __init__(self,
in_channels,
out_channels,
stride,
bn_eps,
activation,
tf_mode):
super(EffiDwsConvUnit, self).__init__()
self.tf_mode = tf_mode
self.residual = (in_channels == out_channels) and (stride == 1)
self.dw_conv = dwconv3x3_block(
in_channels=in_channels,
out_channels=in_channels,
padding=(0 if tf_mode else 1),
bn_eps=bn_eps,
activation=activation)
self.se = SEBlock(
channels=in_channels,
reduction=4,
activation=activation)
self.pw_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
bn_eps=bn_eps,
activation=None)
def forward(self, x):
if self.residual:
identity = x
if self.tf_mode:
x = F.pad(x, pad=calc_tf_padding(x, kernel_size=3))
x = self.dw_conv(x)
x = self.se(x)
x = self.pw_conv(x)
if self.residual:
x = x + identity
return x
class EffiInvResUnit(nn.Module):
"""
EfficientNet inverted residual unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the second convolution layer.
expansion_factor : int
Factor for expansion of channels.
bn_eps : float
Small float added to variance in Batch norm.
activation : str
Name of activation function.
tf_mode : bool
Whether to use TF-like mode.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
expansion_factor,
bn_eps,
activation,
tf_mode):
super(EffiInvResUnit, self).__init__()
self.kernel_size = kernel_size
self.stride = stride
self.tf_mode = tf_mode
self.residual = (in_channels == out_channels) and (stride == 1)
mid_channels = in_channels * expansion_factor
dwconv_block_fn = dwconv3x3_block if kernel_size == 3 else (dwconv5x5_block if kernel_size == 5 else None)
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
bn_eps=bn_eps,
activation=activation)
self.conv2 = dwconv_block_fn(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride,
padding=(0 if tf_mode else (kernel_size // 2)),
bn_eps=bn_eps,
activation=activation)
self.se = SEBlock(
channels=mid_channels,
reduction=24,
activation=activation)
self.conv3 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
bn_eps=bn_eps,
activation=None)
def forward(self, x):
if self.residual:
identity = x
x = self.conv1(x)
if self.tf_mode:
x = F.pad(x, pad=calc_tf_padding(x, kernel_size=self.kernel_size, stride=self.stride))
x = self.conv2(x)
x = self.se(x)
x = self.conv3(x)
if self.residual:
x = x + identity
return x
class EffiInitBlock(nn.Module):
"""
EfficientNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_eps : float
Small float added to variance in Batch norm.
activation : str
Name of activation function.
tf_mode : bool
Whether to use TF-like mode.
"""
def __init__(self,
in_channels,
out_channels,
bn_eps,
activation,
tf_mode):
super(EffiInitBlock, self).__init__()
self.tf_mode = tf_mode
self.conv = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
stride=2,
padding=(0 if tf_mode else 1),
bn_eps=bn_eps,
activation=activation)
def forward(self, x):
if self.tf_mode:
x = F.pad(x, pad=calc_tf_padding(x, kernel_size=3, stride=2))
x = self.conv(x)
return x
class EfficientNet(nn.Module):
"""
EfficientNet(-B0) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,'
https://arxiv.org/abs/1905.11946.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for initial unit.
final_block_channels : int
Number of output channels for the final block of the feature extractor.
kernel_sizes : list of list of int
Number of kernel sizes for each unit.
strides_per_stage : list int
Stride value for the first unit of each stage.
expansion_factors : list of list of int
Number of expansion factors for each unit.
dropout_rate : float, default 0.2
Fraction of the input units to drop. Must be a number between 0 and 1.
tf_mode : bool, default False
Whether to use TF-like mode.
bn_eps : float, default 1e-5
Small float added to variance in Batch norm.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
final_block_channels,
kernel_sizes,
strides_per_stage,
expansion_factors,
dropout_rate=0.2,
tf_mode=False,
bn_eps=1e-5,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(EfficientNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
activation = "swish"
self.features = nn.Sequential()
self.features.add_module("init_block", EffiInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_eps=bn_eps,
activation=activation,
tf_mode=tf_mode))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
kernel_sizes_per_stage = kernel_sizes[i]
expansion_factors_per_stage = expansion_factors[i]
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
kernel_size = kernel_sizes_per_stage[j]
expansion_factor = expansion_factors_per_stage[j]
stride = strides_per_stage[i] if (j == 0) else 1
if i == 0:
stage.add_module("unit{}".format(j + 1), EffiDwsConvUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bn_eps=bn_eps,
activation=activation,
tf_mode=tf_mode))
else:
stage.add_module("unit{}".format(j + 1), EffiInvResUnit(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
expansion_factor=expansion_factor,
bn_eps=bn_eps,
activation=activation,
tf_mode=tf_mode))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_block', conv1x1_block(
in_channels=in_channels,
out_channels=final_block_channels,
bn_eps=bn_eps,
activation=activation))
in_channels = final_block_channels
self.features.add_module("final_pool", nn.AdaptiveAvgPool2d(output_size=1))
self.output = nn.Sequential()
if dropout_rate > 0.0:
self.output.add_module("dropout", nn.Dropout(p=dropout_rate))
self.output.add_module("fc", nn.Linear(
in_features=in_channels,
out_features=num_classes))
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_efficientnet(version,
in_size,
tf_mode=False,
bn_eps=1e-5,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create EfficientNet model with specific parameters.
Parameters:
----------
version : str
Version of EfficientNet ('b0'...'b7').
in_size : tuple of two ints
Spatial size of the expected input image.
tf_mode : bool, default False
Whether to use TF-like mode.
bn_eps : float, default 1e-5
Small float added to variance in Batch norm.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if version == "b0":
assert (in_size == (224, 224))
depth_factor = 1.0
width_factor = 1.0
dropout_rate = 0.2
elif version == "b1":
assert (in_size == (240, 240))
depth_factor = 1.1
width_factor = 1.0
dropout_rate = 0.2
elif version == "b2":
assert (in_size == (260, 260))
depth_factor = 1.2
width_factor = 1.1
dropout_rate = 0.3
elif version == "b3":
assert (in_size == (300, 300))
depth_factor = 1.4
width_factor = 1.2
dropout_rate = 0.3
elif version == "b4":
assert (in_size == (380, 380))
depth_factor = 1.8
width_factor = 1.4
dropout_rate = 0.4
elif version == "b5":
assert (in_size == (456, 456))
depth_factor = 2.2
width_factor = 1.6
dropout_rate = 0.4
elif version == "b6":
assert (in_size == (528, 528))
depth_factor = 2.6
width_factor = 1.8
dropout_rate = 0.5
elif version == "b7":
assert (in_size == (600, 600))
depth_factor = 3.1
width_factor = 2.0
dropout_rate = 0.5
else:
raise ValueError("Unsupported EfficientNet version {}".format(version))
init_block_channels = 32
layers = [1, 2, 2, 3, 3, 4, 1]
downsample = [1, 1, 1, 1, 0, 1, 0]
channels_per_layers = [16, 24, 40, 80, 112, 192, 320]
expansion_factors_per_layers = [1, 6, 6, 6, 6, 6, 6]
kernel_sizes_per_layers = [3, 3, 5, 3, 5, 5, 3]
strides_per_stage = [1, 2, 2, 2, 1, 2, 1]
final_block_channels = 1280
layers = [int(math.ceil(li * depth_factor)) for li in layers]
channels_per_layers = [round_channels(ci * width_factor) for ci in channels_per_layers]
from functools import reduce
channels = reduce(lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]],
zip(channels_per_layers, layers, downsample), [])
kernel_sizes = reduce(lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]],
zip(kernel_sizes_per_layers, layers, downsample), [])
expansion_factors = reduce(lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]],
zip(expansion_factors_per_layers, layers, downsample), [])
strides_per_stage = reduce(lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]],
zip(strides_per_stage, layers, downsample), [])
strides_per_stage = [si[0] for si in strides_per_stage]
init_block_channels = round_channels(init_block_channels * width_factor)
if width_factor > 1.0:
assert (int(final_block_channels * width_factor) == round_channels(final_block_channels * width_factor))
final_block_channels = round_channels(final_block_channels * width_factor)
net = EfficientNet(
channels=channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
kernel_sizes=kernel_sizes,
strides_per_stage=strides_per_stage,
expansion_factors=expansion_factors,
dropout_rate=dropout_rate,
tf_mode=tf_mode,
bn_eps=bn_eps,
in_size=in_size,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def efficientnet_b0(in_size=(224, 224), **kwargs):
"""
EfficientNet-B0 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,'
https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b0", in_size=in_size, model_name="efficientnet_b0", **kwargs)
def efficientnet_b1(in_size=(240, 240), **kwargs):
"""
EfficientNet-B1 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,'
https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (240, 240)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b1", in_size=in_size, model_name="efficientnet_b1", **kwargs)
def efficientnet_b2(in_size=(260, 260), **kwargs):
"""
EfficientNet-B2 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,'
https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (260, 260)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b2", in_size=in_size, model_name="efficientnet_b2", **kwargs)
def efficientnet_b3(in_size=(300, 300), **kwargs):
"""
EfficientNet-B3 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,'
https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (300, 300)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b3", in_size=in_size, model_name="efficientnet_b3", **kwargs)
def efficientnet_b4(in_size=(380, 380), **kwargs):
"""
EfficientNet-B4 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,'
https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (380, 380)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b4", in_size=in_size, model_name="efficientnet_b4", **kwargs)
def efficientnet_b5(in_size=(456, 456), **kwargs):
"""
EfficientNet-B5 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,'
https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (456, 456)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b5", in_size=in_size, model_name="efficientnet_b5", **kwargs)
def efficientnet_b6(in_size=(528, 528), **kwargs):
"""
EfficientNet-B6 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,'
https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (528, 528)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b6", in_size=in_size, model_name="efficientnet_b6", **kwargs)
def efficientnet_b7(in_size=(600, 600), **kwargs):
"""
EfficientNet-B7 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,'
https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (600, 600)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b7", in_size=in_size, model_name="efficientnet_b7", **kwargs)
def efficientnet_b0b(in_size=(224, 224), **kwargs):
"""
EfficientNet-B0-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional
Neural Networks,' https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b0", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b0b",
**kwargs)
def efficientnet_b1b(in_size=(240, 240), **kwargs):
"""
EfficientNet-B1-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional
Neural Networks,' https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (240, 240)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b1", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b1b",
**kwargs)
def efficientnet_b2b(in_size=(260, 260), **kwargs):
"""
EfficientNet-B2-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional
Neural Networks,' https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (260, 260)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b2", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b2b",
**kwargs)
def efficientnet_b3b(in_size=(300, 300), **kwargs):
"""
EfficientNet-B3-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional
Neural Networks,' https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (300, 300)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b3", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b3b",
**kwargs)
def efficientnet_b4b(in_size=(380, 380), **kwargs):
"""
EfficientNet-B4-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional
Neural Networks,' https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (380, 380)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b4", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b4b",
**kwargs)
def efficientnet_b5b(in_size=(456, 456), **kwargs):
"""
EfficientNet-B5-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional
Neural Networks,' https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (456, 456)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b5", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b5b",
**kwargs)
def efficientnet_b6b(in_size=(528, 528), **kwargs):
"""
EfficientNet-B6-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional
Neural Networks,' https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (528, 528)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b6", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b6b",
**kwargs)
def efficientnet_b7b(in_size=(600, 600), **kwargs):
"""
EfficientNet-B7-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional
Neural Networks,' https://arxiv.org/abs/1905.11946.
Parameters:
----------
in_size : tuple of two ints, default (600, 600)
Spatial size of the expected input image.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_efficientnet(version="b7", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b7b",
**kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
efficientnet_b0,
efficientnet_b1,
efficientnet_b2,
efficientnet_b3,
efficientnet_b4,
efficientnet_b5,
efficientnet_b6,
efficientnet_b7,
efficientnet_b0b,
efficientnet_b1b,
efficientnet_b2b,
efficientnet_b3b,
efficientnet_b4b,
efficientnet_b5b,
efficientnet_b6b,
efficientnet_b7b,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != efficientnet_b0 or weight_count == 5288548)
assert (model != efficientnet_b1 or weight_count == 7794184)
assert (model != efficientnet_b2 or weight_count == 9109994)
assert (model != efficientnet_b3 or weight_count == 12233232)
assert (model != efficientnet_b4 or weight_count == 19341616)
assert (model != efficientnet_b5 or weight_count == 30389784)
assert (model != efficientnet_b6 or weight_count == 43040704)
assert (model != efficientnet_b7 or weight_count == 66347960)
assert (model != efficientnet_b0b or weight_count == 5288548)
assert (model != efficientnet_b1b or weight_count == 7794184)
assert (model != efficientnet_b2b or weight_count == 9109994)
assert (model != efficientnet_b3b or weight_count == 12233232)
assert (model != efficientnet_b4b or weight_count == 19341616)
assert (model != efficientnet_b5b or weight_count == 30389784)
assert (model != efficientnet_b6b or weight_count == 43040704)
assert (model != efficientnet_b7b or weight_count == 66347960)
x = torch.randn(1, 3, net.in_size[0], net.in_size[1])
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 29,350 | 34.925337 | 120 | py |
null | qimera-main/pytorchcv/models/espnetv2.py | """
ESPNetv2 for ImageNet-1K, implemented in PyTorch.
Original paper: 'ESPNetv2: A Light-weight, Power Efficient, and General Purpose Convolutional Neural Network,'
https://arxiv.org/abs/1811.11431.
"""
__all__ = ['ESPNetv2', 'espnetv2_wd2', 'espnetv2_w1', 'espnetv2_w5d4', 'espnetv2_w3d2', 'espnetv2_w2']
import os
import math
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv3x3, conv1x1_block, conv3x3_block, DualPathSequential
class PreActivation(nn.Module):
"""
PreResNet like pure pre-activation block without convolution layer.
Parameters:
----------
in_channels : int
Number of input channels.
"""
def __init__(self,
in_channels):
super(PreActivation, self).__init__()
self.bn = nn.BatchNorm2d(num_features=in_channels)
self.activ = nn.PReLU(num_parameters=in_channels)
def forward(self, x):
x = self.bn(x)
x = self.activ(x)
return x
class ShortcutBlock(nn.Module):
"""
ESPNetv2 shortcut block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(ShortcutBlock, self).__init__()
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=in_channels,
activation=(lambda: nn.PReLU(in_channels)))
self.conv2 = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
activation=None)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class HierarchicalConcurrent(nn.Sequential):
"""
A container for hierarchical concatenation of modules on the base of the sequential container.
Parameters:
----------
axis : int, default 1
The axis on which to concatenate the outputs.
"""
def __init__(self, axis=1):
super(HierarchicalConcurrent, self).__init__()
self.axis = axis
def forward(self, x):
out = []
y_prev = None
for module in self._modules.values():
y = module(x)
if y_prev is not None:
y += y_prev
out.append(y)
y_prev = y
out = torch.cat(tuple(out), dim=self.axis)
return out
class ESPBlock(nn.Module):
"""
ESPNetv2 block (so-called EESP block).
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the branch convolution layers.
dilations : list of int
Dilation values for branches.
"""
def __init__(self,
in_channels,
out_channels,
stride,
dilations):
super(ESPBlock, self).__init__()
num_branches = len(dilations)
assert (out_channels % num_branches == 0)
self.downsample = (stride != 1)
mid_channels = out_channels // num_branches
self.reduce_conv = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
groups=num_branches,
activation=(lambda: nn.PReLU(mid_channels)))
self.branches = HierarchicalConcurrent()
for i in range(num_branches):
self.branches.add_module("branch{}".format(i + 1), conv3x3(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride,
padding=dilations[i],
dilation=dilations[i],
groups=mid_channels))
self.merge_conv = conv1x1_block(
in_channels=out_channels,
out_channels=out_channels,
groups=num_branches,
activation=None)
self.preactiv = PreActivation(in_channels=out_channels)
self.activ = nn.PReLU(out_channels)
def forward(self, x, x0):
y = self.reduce_conv(x)
y = self.branches(y)
y = self.preactiv(y)
y = self.merge_conv(y)
if not self.downsample:
y = y + x
y = self.activ(y)
return y, x0
class DownsampleBlock(nn.Module):
"""
ESPNetv2 downsample block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
x0_channels : int
Number of input channels for shortcut.
dilations : list of int
Dilation values for branches in EESP block.
"""
def __init__(self,
in_channels,
out_channels,
x0_channels,
dilations):
super(DownsampleBlock, self).__init__()
inc_channels = out_channels - in_channels
self.pool = nn.AvgPool2d(
kernel_size=3,
stride=2,
padding=1)
self.eesp = ESPBlock(
in_channels=in_channels,
out_channels=inc_channels,
stride=2,
dilations=dilations)
self.shortcut_block = ShortcutBlock(
in_channels=x0_channels,
out_channels=out_channels)
self.activ = nn.PReLU(out_channels)
def forward(self, x, x0):
y1 = self.pool(x)
y2, _ = self.eesp(x, None)
x = torch.cat((y1, y2), dim=1)
x0 = self.pool(x0)
y3 = self.shortcut_block(x0)
x = x + y3
x = self.activ(x)
return x, x0
class ESPInitBlock(nn.Module):
"""
ESPNetv2 initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(ESPInitBlock, self).__init__()
self.conv = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
stride=2,
activation=(lambda: nn.PReLU(out_channels)))
self.pool = nn.AvgPool2d(
kernel_size=3,
stride=2,
padding=1)
def forward(self, x, x0):
x = self.conv(x)
x0 = self.pool(x0)
return x, x0
class ESPFinalBlock(nn.Module):
"""
ESPNetv2 final block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
final_groups : int
Number of groups in the last convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
final_groups):
super(ESPFinalBlock, self).__init__()
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=in_channels,
groups=in_channels,
activation=(lambda: nn.PReLU(in_channels)))
self.conv2 = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
groups=final_groups,
activation=(lambda: nn.PReLU(out_channels)))
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class ESPNetv2(nn.Module):
"""
ESPNetv2 model from 'ESPNetv2: A Light-weight, Power Efficient, and General Purpose Convolutional Neural Network,'
https://arxiv.org/abs/1811.11431.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
final_block_channels : int
Number of output channels for the final unit.
final_block_groups : int
Number of groups for the final unit.
dilations : list of list of list of int
Dilation values for branches in each unit.
dropout_rate : float, default 0.2
Parameter of Dropout layer. Faction of the input units to drop.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
final_block_channels,
final_block_groups,
dilations,
dropout_rate=0.2,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(ESPNetv2, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
x0_channels = in_channels
self.features = DualPathSequential(
return_two=False,
first_ordinals=0,
last_ordinals=2)
self.features.add_module("init_block", ESPInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = DualPathSequential()
for j, out_channels in enumerate(channels_per_stage):
if j == 0:
unit = DownsampleBlock(
in_channels=in_channels,
out_channels=out_channels,
x0_channels=x0_channels,
dilations=dilations[i][j])
else:
unit = ESPBlock(
in_channels=in_channels,
out_channels=out_channels,
stride=1,
dilations=dilations[i][j])
stage.add_module("unit{}".format(j + 1), unit)
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_block", ESPFinalBlock(
in_channels=in_channels,
out_channels=final_block_channels,
final_groups=final_block_groups))
in_channels = final_block_channels
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Sequential()
self.output.add_module("dropout", nn.Dropout(p=dropout_rate))
self.output.add_module("fc", nn.Linear(
in_features=in_channels,
out_features=num_classes))
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x, x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_espnetv2(width_scale,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create ESPNetv2 model with specific parameters.
Parameters:
----------
width_scale : float
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
assert (width_scale <= 2.0)
branches = 4
layers = [1, 4, 8, 4]
max_dilation_list = [6, 5, 4, 3, 2]
max_dilations = [[max_dilation_list[i]] + [max_dilation_list[i + 1]] * (li - 1) for (i, li) in enumerate(layers)]
dilations = [[sorted([k + 1 if k < dij else 1 for k in range(branches)]) for dij in di] for di in max_dilations]
base_channels = 32
weighed_base_channels = math.ceil(float(math.floor(base_channels * width_scale)) / branches) * branches
channels_per_layers = [weighed_base_channels * pow(2, i + 1) for i in range(len(layers))]
init_block_channels = base_channels if weighed_base_channels > base_channels else weighed_base_channels
final_block_channels = 1024 if width_scale <= 1.5 else 1280
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = ESPNetv2(
channels=channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
final_block_groups=branches,
dilations=dilations,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def espnetv2_wd2(**kwargs):
"""
ESPNetv2 x0.5 model from 'ESPNetv2: A Light-weight, Power Efficient, and General Purpose Convolutional Neural
Network,' https://arxiv.org/abs/1811.11431.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_espnetv2(width_scale=0.5, model_name="espnetv2_wd2", **kwargs)
def espnetv2_w1(**kwargs):
"""
ESPNetv2 x1.0 model from 'ESPNetv2: A Light-weight, Power Efficient, and General Purpose Convolutional Neural
Network,' https://arxiv.org/abs/1811.11431.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_espnetv2(width_scale=1.0, model_name="espnetv2_w1", **kwargs)
def espnetv2_w5d4(**kwargs):
"""
ESPNetv2 x1.25 model from 'ESPNetv2: A Light-weight, Power Efficient, and General Purpose Convolutional Neural
Network,' https://arxiv.org/abs/1811.11431.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_espnetv2(width_scale=1.25, model_name="espnetv2_w5d4", **kwargs)
def espnetv2_w3d2(**kwargs):
"""
ESPNetv2 x1.5 model from 'ESPNetv2: A Light-weight, Power Efficient, and General Purpose Convolutional Neural
Network,' https://arxiv.org/abs/1811.11431.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_espnetv2(width_scale=1.5, model_name="espnetv2_w3d2", **kwargs)
def espnetv2_w2(**kwargs):
"""
ESPNetv2 x2.0 model from 'ESPNetv2: A Light-weight, Power Efficient, and General Purpose Convolutional Neural
Network,' https://arxiv.org/abs/1811.11431.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_espnetv2(width_scale=2.0, model_name="espnetv2_w2", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
espnetv2_wd2,
espnetv2_w1,
espnetv2_w5d4,
espnetv2_w3d2,
espnetv2_w2,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != espnetv2_wd2 or weight_count == 1241332)
assert (model != espnetv2_w1 or weight_count == 1670072)
assert (model != espnetv2_w5d4 or weight_count == 1965440)
assert (model != espnetv2_w3d2 or weight_count == 2314856)
assert (model != espnetv2_w2 or weight_count == 3498136)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 16,827 | 29.990792 | 118 | py |
null | qimera-main/pytorchcv/models/fbnet.py | """
FBNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'FBNet: Hardware-Aware Efficient ConvNet Design via Differentiable Neural Architecture Search,'
https://arxiv.org/abs/1812.03443.
"""
__all__ = ['FBNet', 'fbnet_cb']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, conv3x3_block, dwconv3x3_block, dwconv5x5_block
class FBNetUnit(nn.Module):
"""
FBNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the second convolution layer.
bn_eps : float
Small float added to variance in Batch norm.
use_kernel3 : bool
Whether to use 3x3 (instead of 5x5) kernel.
exp_factor : int
Expansion factor for each unit.
activation : str, default 'relu'
Activation function or name of activation function.
"""
def __init__(self,
in_channels,
out_channels,
stride,
bn_eps,
use_kernel3,
exp_factor,
activation="relu"):
super(FBNetUnit, self).__init__()
assert (exp_factor >= 1)
self.residual = (in_channels == out_channels) and (stride == 1)
self.use_exp_conv = True
mid_channels = exp_factor * in_channels
if self.use_exp_conv:
self.exp_conv = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
bn_eps=bn_eps,
activation=activation)
if use_kernel3:
self.conv1 = dwconv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride,
bn_eps=bn_eps,
activation=activation)
else:
self.conv1 = dwconv5x5_block(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride,
bn_eps=bn_eps,
activation=activation)
self.conv2 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
bn_eps=bn_eps,
activation=None)
def forward(self, x):
if self.residual:
identity = x
if self.use_exp_conv:
x = self.exp_conv(x)
x = self.conv1(x)
x = self.conv2(x)
if self.residual:
x = x + identity
return x
class FBNetInitBlock(nn.Module):
"""
FBNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_eps : float
Small float added to variance in Batch norm.
"""
def __init__(self,
in_channels,
out_channels,
bn_eps):
super(FBNetInitBlock, self).__init__()
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
stride=2,
bn_eps=bn_eps)
self.conv2 = FBNetUnit(
in_channels=out_channels,
out_channels=out_channels,
stride=1,
bn_eps=bn_eps,
use_kernel3=True,
exp_factor=1)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class FBNet(nn.Module):
"""
FBNet model from 'FBNet: Hardware-Aware Efficient ConvNet Design via Differentiable Neural Architecture Search,'
https://arxiv.org/abs/1812.03443.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
final_block_channels : int
Number of output channels for the final block of the feature extractor.
kernels3 : list of list of int/bool
Using 3x3 (instead of 5x5) kernel for each unit.
exp_factors : list of list of int
Expansion factor for each unit.
bn_eps : float, default 1e-5
Small float added to variance in Batch norm.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
final_block_channels,
kernels3,
exp_factors,
bn_eps=1e-5,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(FBNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", FBNetInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_eps=bn_eps))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) else 1
use_kernel3 = kernels3[i][j] == 1
exp_factor = exp_factors[i][j]
stage.add_module("unit{}".format(j + 1), FBNetUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bn_eps=bn_eps,
use_kernel3=use_kernel3,
exp_factor=exp_factor))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_block', conv1x1_block(
in_channels=in_channels,
out_channels=final_block_channels,
bn_eps=bn_eps))
in_channels = final_block_channels
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_fbnet(version,
bn_eps=1e-5,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create FBNet model with specific parameters.
Parameters:
----------
version : str
Version of MobileNetV3 ('a', 'b' or 'c').
bn_eps : float, default 1e-5
Small float added to variance in Batch norm.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if version == "c":
init_block_channels = 16
final_block_channels = 1984
channels = [[24, 24, 24], [32, 32, 32, 32], [64, 64, 64, 64, 112, 112, 112, 112], [184, 184, 184, 184, 352]]
kernels3 = [[1, 1, 1], [0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1]]
exp_factors = [[6, 1, 1], [6, 3, 6, 6], [6, 3, 6, 6, 6, 6, 6, 3], [6, 6, 6, 6, 6]]
else:
raise ValueError("Unsupported FBNet version {}".format(version))
net = FBNet(
channels=channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
kernels3=kernels3,
exp_factors=exp_factors,
bn_eps=bn_eps,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def fbnet_cb(**kwargs):
"""
FBNet-Cb model (bn_eps=1e-3) from 'FBNet: Hardware-Aware Efficient ConvNet Design via Differentiable Neural
Architecture Search,' https://arxiv.org/abs/1812.03443.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_fbnet(version="c", bn_eps=1e-3, model_name="fbnet_cb", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
fbnet_cb,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != fbnet_cb or weight_count == 5572200)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 9,969 | 30.352201 | 116 | py |
null | qimera-main/pytorchcv/models/fcn8sd.py | """
FCN-8s(d) for image segmentation, implemented in PyTorch.
Original paper: 'Fully Convolutional Networks for Semantic Segmentation,' https://arxiv.org/abs/1411.4038.
"""
__all__ = ['FCN8sd', 'fcn8sd_resnetd50b_voc', 'fcn8sd_resnetd101b_voc', 'fcn8sd_resnetd50b_coco',
'fcn8sd_resnetd101b_coco', 'fcn8sd_resnetd50b_ade20k', 'fcn8sd_resnetd101b_ade20k',
'fcn8sd_resnetd50b_cityscapes', 'fcn8sd_resnetd101b_cityscapes']
import os
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from .common import conv1x1, conv3x3_block
from .resnetd import resnetd50b, resnetd101b
class FCNFinalBlock(nn.Module):
"""
FCN-8s(d) final block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bottleneck_factor : int, default 4
Bottleneck factor.
"""
def __init__(self,
in_channels,
out_channels,
bottleneck_factor=4):
super(FCNFinalBlock, self).__init__()
assert (in_channels % bottleneck_factor == 0)
mid_channels = in_channels // bottleneck_factor
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=mid_channels)
self.dropout = nn.Dropout(p=0.1, inplace=False)
self.conv2 = conv1x1(
in_channels=mid_channels,
out_channels=out_channels,
bias=True)
def forward(self, x, out_size):
x = self.conv1(x)
x = self.dropout(x)
x = self.conv2(x)
x = F.interpolate(x, size=out_size, mode="bilinear", align_corners=True)
return x
class FCN8sd(nn.Module):
"""
FCN-8s(d) model from 'Fully Convolutional Networks for Semantic Segmentation,' https://arxiv.org/abs/1411.4038.
It is an experimental model mixed FCN-8s and PSPNet.
Parameters:
----------
backbone : nn.Sequential
Feature extractor.
backbone_out_channels : int, default 2048
Number of output channels form feature extractor.
aux : bool, default False
Whether to output an auxiliary result.
fixed_size : bool, default True
Whether to expect fixed spatial size of input image.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (480, 480)
Spatial size of the expected input image.
num_classes : int, default 21
Number of segmentation classes.
"""
def __init__(self,
backbone,
backbone_out_channels=2048,
aux=False,
fixed_size=True,
in_channels=3,
in_size=(480, 480),
num_classes=21):
super(FCN8sd, self).__init__()
assert (in_channels > 0)
self.in_size = in_size
self.num_classes = num_classes
self.aux = aux
self.fixed_size = fixed_size
self.backbone = backbone
pool_out_channels = backbone_out_channels
self.final_block = FCNFinalBlock(
in_channels=pool_out_channels,
out_channels=num_classes)
if self.aux:
aux_out_channels = backbone_out_channels // 2
self.aux_block = FCNFinalBlock(
in_channels=aux_out_channels,
out_channels=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
in_size = self.in_size if self.fixed_size else x.shape[2:]
x, y = self.backbone(x)
x = self.final_block(x, in_size)
if self.aux:
y = self.aux_block(y, in_size)
return x, y
else:
return x
def get_fcn8sd(backbone,
num_classes,
aux=False,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create FCN-8s(d) model with specific parameters.
Parameters:
----------
backbone : nn.Sequential
Feature extractor.
num_classes : int
Number of segmentation classes.
aux : bool, default False
Whether to output an auxiliary result.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
net = FCN8sd(
backbone=backbone,
num_classes=num_classes,
aux=aux,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def fcn8sd_resnetd50b_voc(pretrained_backbone=False, num_classes=21, aux=True, **kwargs):
"""
FCN-8s(d) model on the base of ResNet(D)-50b for Pascal VOC from 'Fully Convolutional Networks for Semantic
Segmentation,' https://arxiv.org/abs/1411.4038.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 21
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_fcn8sd(backbone=backbone, num_classes=num_classes, aux=aux, model_name="fcn8sd_resnetd50b_voc", **kwargs)
def fcn8sd_resnetd101b_voc(pretrained_backbone=False, num_classes=21, aux=True, **kwargs):
"""
FCN-8s(d) model on the base of ResNet(D)-101b for Pascal VOC from 'Fully Convolutional Networks for Semantic
Segmentation,' https://arxiv.org/abs/1411.4038.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 21
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_fcn8sd(backbone=backbone, num_classes=num_classes, aux=aux, model_name="fcn8sd_resnetd101b_voc",
**kwargs)
def fcn8sd_resnetd50b_coco(pretrained_backbone=False, num_classes=21, aux=True, **kwargs):
"""
FCN-8s(d) model on the base of ResNet(D)-50b for COCO from 'Fully Convolutional Networks for Semantic
Segmentation,' https://arxiv.org/abs/1411.4038.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 21
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_fcn8sd(backbone=backbone, num_classes=num_classes, aux=aux, model_name="fcn8sd_resnetd50b_coco",
**kwargs)
def fcn8sd_resnetd101b_coco(pretrained_backbone=False, num_classes=21, aux=True, **kwargs):
"""
FCN-8s(d) model on the base of ResNet(D)-101b for COCO from 'Fully Convolutional Networks for Semantic
Segmentation,' https://arxiv.org/abs/1411.4038.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 21
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_fcn8sd(backbone=backbone, num_classes=num_classes, aux=aux, model_name="fcn8sd_resnetd101b_coco",
**kwargs)
def fcn8sd_resnetd50b_ade20k(pretrained_backbone=False, num_classes=150, aux=True, **kwargs):
"""
FCN-8s(d) model on the base of ResNet(D)-50b for ADE20K from 'Fully Convolutional Networks for Semantic
Segmentation,' https://arxiv.org/abs/1411.4038.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 150
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_fcn8sd(backbone=backbone, num_classes=num_classes, aux=aux, model_name="fcn8sd_resnetd50b_ade20k",
**kwargs)
def fcn8sd_resnetd101b_ade20k(pretrained_backbone=False, num_classes=150, aux=True, **kwargs):
"""
FCN-8s(d) model on the base of ResNet(D)-101b for ADE20K from 'Fully Convolutional Networks for Semantic
Segmentation,' https://arxiv.org/abs/1411.4038.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 150
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_fcn8sd(backbone=backbone, num_classes=num_classes, aux=aux, model_name="fcn8sd_resnetd101b_ade20k",
**kwargs)
def fcn8sd_resnetd50b_cityscapes(pretrained_backbone=False, num_classes=19, aux=True, **kwargs):
"""
FCN-8s(d) model on the base of ResNet(D)-50b for Cityscapes from 'Fully Convolutional Networks for Semantic
Segmentation,' https://arxiv.org/abs/1411.4038.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 19
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_fcn8sd(backbone=backbone, num_classes=num_classes, aux=aux, model_name="fcn8sd_resnetd50b_cityscapes",
**kwargs)
def fcn8sd_resnetd101b_cityscapes(pretrained_backbone=False, num_classes=19, aux=True, **kwargs):
"""
FCN-8s(d) model on the base of ResNet(D)-101b for Cityscapes from 'Fully Convolutional Networks for Semantic
Segmentation,' https://arxiv.org/abs/1411.4038.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 19
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_fcn8sd(backbone=backbone, num_classes=num_classes, aux=aux, model_name="fcn8sd_resnetd101b_cityscapes",
**kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
in_size = (480, 480)
aux = True
pretrained = False
models = [
(fcn8sd_resnetd50b_voc, 21),
(fcn8sd_resnetd101b_voc, 21),
(fcn8sd_resnetd50b_coco, 21),
(fcn8sd_resnetd101b_coco, 21),
(fcn8sd_resnetd50b_ade20k, 150),
(fcn8sd_resnetd101b_ade20k, 150),
(fcn8sd_resnetd50b_cityscapes, 19),
(fcn8sd_resnetd101b_cityscapes, 19),
]
for model, num_classes in models:
net = model(pretrained=pretrained, in_size=in_size, aux=aux)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
if aux:
assert (model != fcn8sd_resnetd50b_voc or weight_count == 35445994)
assert (model != fcn8sd_resnetd101b_voc or weight_count == 54438122)
assert (model != fcn8sd_resnetd50b_coco or weight_count == 35445994)
assert (model != fcn8sd_resnetd101b_coco or weight_count == 54438122)
assert (model != fcn8sd_resnetd50b_ade20k or weight_count == 35545324)
assert (model != fcn8sd_resnetd101b_ade20k or weight_count == 54537452)
assert (model != fcn8sd_resnetd50b_cityscapes or weight_count == 35444454)
assert (model != fcn8sd_resnetd101b_cityscapes or weight_count == 54436582)
else:
assert (model != fcn8sd_resnetd50b_voc or weight_count == 33080789)
assert (model != fcn8sd_resnetd101b_voc or weight_count == 52072917)
assert (model != fcn8sd_resnetd50b_coco or weight_count == 33080789)
assert (model != fcn8sd_resnetd101b_coco or weight_count == 52072917)
assert (model != fcn8sd_resnetd50b_ade20k or weight_count == 33146966)
assert (model != fcn8sd_resnetd101b_ade20k or weight_count == 52139094)
assert (model != fcn8sd_resnetd50b_cityscapes or weight_count == 33079763)
assert (model != fcn8sd_resnetd101b_cityscapes or weight_count == 52071891)
x = torch.randn(1, 3, in_size[0], in_size[1])
ys = net(x)
y = ys[0] if aux else ys
y.sum().backward()
assert ((y.size(0) == x.size(0)) and (y.size(1) == num_classes) and (y.size(2) == x.size(2)) and
(y.size(3) == x.size(3)))
if __name__ == "__main__":
_test()
| 16,182 | 37.257683 | 120 | py |
null | qimera-main/pytorchcv/models/fishnet.py | """
FishNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'FishNet: A Versatile Backbone for Image, Region, and Pixel Level Prediction,'
http://papers.nips.cc/paper/7356-fishnet-a-versatile-backbone-for-image-region-and-pixel-level-prediction.pdf.
"""
__all__ = ['FishNet', 'fishnet99', 'fishnet150', 'InterpolationBlock', 'ChannelSqueeze']
import os
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from .common import pre_conv1x1_block, pre_conv3x3_block, conv1x1, SesquialteralHourglass, Identity
from .preresnet import PreResActivation
from .senet import SEInitBlock
def channel_squeeze(x,
groups):
"""
Channel squeeze operation.
Parameters:
----------
x : Tensor
Input tensor.
groups : int
Number of groups.
Returns
-------
Tensor
Resulted tensor.
"""
batch, channels, height, width = x.size()
channels_per_group = channels // groups
x = x.view(batch, channels_per_group, groups, height, width).sum(dim=2)
return x
class ChannelSqueeze(nn.Module):
"""
Channel squeeze layer. This is a wrapper over the same operation. It is designed to save the number of groups.
Parameters:
----------
channels : int
Number of channels.
groups : int
Number of groups.
"""
def __init__(self,
channels,
groups):
super(ChannelSqueeze, self).__init__()
if channels % groups != 0:
raise ValueError('channels must be divisible by groups')
self.groups = groups
def forward(self, x):
return channel_squeeze(x, self.groups)
class InterpolationBlock(nn.Module):
"""
Interpolation block.
Parameters:
----------
scale_factor : float
Multiplier for spatial size.
mode : str, default 'nearest'
Algorithm used for upsampling.
align_corners : bool, default None
Whether to align the corner pixels of the input and output tensors
"""
def __init__(self,
scale_factor,
mode="nearest",
align_corners=None):
super(InterpolationBlock, self).__init__()
self.scale_factor = scale_factor
self.mode = mode
self.align_corners = align_corners
def forward(self, x):
return F.interpolate(
input=x,
scale_factor=self.scale_factor,
mode=self.mode,
align_corners=self.align_corners)
class PreSEAttBlock(nn.Module):
"""
FishNet specific Squeeze-and-Excitation attention block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
reduction : int, default 16
Squeeze reduction value.
"""
def __init__(self,
in_channels,
out_channels,
reduction=16):
super(PreSEAttBlock, self).__init__()
mid_cannels = out_channels // reduction
self.bn = nn.BatchNorm2d(num_features=in_channels)
self.relu = nn.ReLU(inplace=True)
self.pool = nn.AdaptiveAvgPool2d(output_size=1)
self.conv1 = conv1x1(
in_channels=in_channels,
out_channels=mid_cannels,
bias=True)
self.conv2 = conv1x1(
in_channels=mid_cannels,
out_channels=out_channels,
bias=True)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = self.bn(x)
x = self.relu(x)
x = self.pool(x)
x = self.conv1(x)
x = self.relu(x)
x = self.conv2(x)
x = self.sigmoid(x)
return x
class FishBottleneck(nn.Module):
"""
FishNet bottleneck block for residual unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
dilation : int or tuple/list of 2 int
Dilation value for convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
stride,
dilation):
super(FishBottleneck, self).__init__()
mid_channels = out_channels // 4
self.conv1 = pre_conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels)
self.conv2 = pre_conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride,
padding=dilation,
dilation=dilation)
self.conv3 = pre_conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class FishBlock(nn.Module):
"""
FishNet block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
squeeze : bool, default False
Whether to use a channel squeeze operation.
"""
def __init__(self,
in_channels,
out_channels,
stride=1,
dilation=1,
squeeze=False):
super(FishBlock, self).__init__()
self.squeeze = squeeze
self.resize_identity = (in_channels != out_channels) or (stride != 1)
self.body = FishBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
dilation=dilation)
if self.squeeze:
assert (in_channels // 2 == out_channels)
self.c_squeeze = ChannelSqueeze(
channels=in_channels,
groups=2)
elif self.resize_identity:
self.identity_conv = pre_conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
def forward(self, x):
if self.squeeze:
identity = self.c_squeeze(x)
elif self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = x + identity
return x
class DownUnit(nn.Module):
"""
FishNet down unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels_list : list of int
Number of output channels for each block.
"""
def __init__(self,
in_channels,
out_channels_list):
super(DownUnit, self).__init__()
self.blocks = nn.Sequential()
for i, out_channels in enumerate(out_channels_list):
self.blocks.add_module("block{}".format(i + 1), FishBlock(
in_channels=in_channels,
out_channels=out_channels))
in_channels = out_channels
self.pool = nn.MaxPool2d(
kernel_size=2,
stride=2)
def forward(self, x):
x = self.blocks(x)
x = self.pool(x)
return x
class UpUnit(nn.Module):
"""
FishNet up unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels_list : list of int
Number of output channels for each block.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
"""
def __init__(self,
in_channels,
out_channels_list,
dilation=1):
super(UpUnit, self).__init__()
self.blocks = nn.Sequential()
for i, out_channels in enumerate(out_channels_list):
squeeze = (dilation > 1) and (i == 0)
self.blocks.add_module("block{}".format(i + 1), FishBlock(
in_channels=in_channels,
out_channels=out_channels,
dilation=dilation,
squeeze=squeeze))
in_channels = out_channels
self.upsample = InterpolationBlock(scale_factor=2)
def forward(self, x):
x = self.blocks(x)
x = self.upsample(x)
return x
class SkipUnit(nn.Module):
"""
FishNet skip connection unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels_list : list of int
Number of output channels for each block.
"""
def __init__(self,
in_channels,
out_channels_list):
super(SkipUnit, self).__init__()
self.blocks = nn.Sequential()
for i, out_channels in enumerate(out_channels_list):
self.blocks.add_module("block{}".format(i + 1), FishBlock(
in_channels=in_channels,
out_channels=out_channels))
in_channels = out_channels
def forward(self, x):
x = self.blocks(x)
return x
class SkipAttUnit(nn.Module):
"""
FishNet skip connection unit with attention block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels_list : list of int
Number of output channels for each block.
"""
def __init__(self,
in_channels,
out_channels_list):
super(SkipAttUnit, self).__init__()
mid_channels1 = in_channels // 2
mid_channels2 = 2 * in_channels
self.conv1 = pre_conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels1)
self.conv2 = pre_conv1x1_block(
in_channels=mid_channels1,
out_channels=mid_channels2,
bias=True)
in_channels = mid_channels2
self.se = PreSEAttBlock(
in_channels=mid_channels2,
out_channels=out_channels_list[-1])
self.blocks = nn.Sequential()
for i, out_channels in enumerate(out_channels_list):
self.blocks.add_module("block{}".format(i + 1), FishBlock(
in_channels=in_channels,
out_channels=out_channels))
in_channels = out_channels
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
w = self.se(x)
x = self.blocks(x)
x = x * w + w
return x
class FishFinalBlock(nn.Module):
"""
FishNet final block.
Parameters:
----------
in_channels : int
Number of input channels.
"""
def __init__(self,
in_channels):
super(FishFinalBlock, self).__init__()
mid_channels = in_channels // 2
self.conv1 = pre_conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels)
self.preactiv = PreResActivation(
in_channels=mid_channels)
def forward(self, x):
x = self.conv1(x)
x = self.preactiv(x)
return x
class FishNet(nn.Module):
"""
FishNet model from 'FishNet: A Versatile Backbone for Image, Region, and Pixel Level Prediction,'
http://papers.nips.cc/paper/7356-fishnet-a-versatile-backbone-for-image-region-and-pixel-level-prediction.pdf.
Parameters:
----------
direct_channels : list of list of list of int
Number of output channels for each unit along the straight path.
skip_channels : list of list of list of int
Number of output channels for each skip connection unit.
init_block_channels : int
Number of output channels for the initial unit.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
direct_channels,
skip_channels,
init_block_channels,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(FishNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
depth = len(direct_channels[0])
down1_channels = direct_channels[0]
up_channels = direct_channels[1]
down2_channels = direct_channels[2]
skip1_channels = skip_channels[0]
skip2_channels = skip_channels[1]
self.features = nn.Sequential()
self.features.add_module("init_block", SEInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
down1_seq = nn.Sequential()
skip1_seq = nn.Sequential()
for i in range(depth + 1):
skip1_channels_list = skip1_channels[i]
if i < depth:
skip1_seq.add_module("unit{}".format(i + 1), SkipUnit(
in_channels=in_channels,
out_channels_list=skip1_channels_list))
down1_channels_list = down1_channels[i]
down1_seq.add_module("unit{}".format(i + 1), DownUnit(
in_channels=in_channels,
out_channels_list=down1_channels_list))
in_channels = down1_channels_list[-1]
else:
skip1_seq.add_module("unit{}".format(i + 1), SkipAttUnit(
in_channels=in_channels,
out_channels_list=skip1_channels_list))
in_channels = skip1_channels_list[-1]
up_seq = nn.Sequential()
skip2_seq = nn.Sequential()
for i in range(depth + 1):
skip2_channels_list = skip2_channels[i]
if i > 0:
in_channels += skip1_channels[depth - i][-1]
if i < depth:
skip2_seq.add_module("unit{}".format(i + 1), SkipUnit(
in_channels=in_channels,
out_channels_list=skip2_channels_list))
up_channels_list = up_channels[i]
dilation = 2 ** i
up_seq.add_module("unit{}".format(i + 1), UpUnit(
in_channels=in_channels,
out_channels_list=up_channels_list,
dilation=dilation))
in_channels = up_channels_list[-1]
else:
skip2_seq.add_module("unit{}".format(i + 1), Identity())
down2_seq = nn.Sequential()
for i in range(depth):
down2_channels_list = down2_channels[i]
down2_seq.add_module("unit{}".format(i + 1), DownUnit(
in_channels=in_channels,
out_channels_list=down2_channels_list))
in_channels = down2_channels_list[-1] + skip2_channels[depth - 1 - i][-1]
self.features.add_module("hg", SesquialteralHourglass(
down1_seq=down1_seq,
skip1_seq=skip1_seq,
up_seq=up_seq,
skip2_seq=skip2_seq,
down2_seq=down2_seq))
self.features.add_module("final_block", FishFinalBlock(in_channels=in_channels))
in_channels = in_channels // 2
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Sequential()
self.output.add_module("final_conv", conv1x1(
in_channels=in_channels,
out_channels=num_classes,
bias=True))
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = self.output(x)
x = x.view(x.size(0), -1)
return x
def get_fishnet(blocks,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create FishNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 99:
direct_layers = [[2, 2, 6], [1, 1, 1], [1, 2, 2]]
skip_layers = [[1, 1, 1, 2], [4, 1, 1, 0]]
elif blocks == 150:
direct_layers = [[2, 4, 8], [2, 2, 2], [2, 2, 4]]
skip_layers = [[2, 2, 2, 4], [4, 2, 2, 0]]
else:
raise ValueError("Unsupported FishNet with number of blocks: {}".format(blocks))
direct_channels_per_layers = [[128, 256, 512], [512, 384, 256], [320, 832, 1600]]
skip_channels_per_layers = [[64, 128, 256, 512], [512, 768, 512, 0]]
direct_channels = [[[b] * c for (b, c) in zip(*a)] for a in
([(ci, li) for (ci, li) in zip(direct_channels_per_layers, direct_layers)])]
skip_channels = [[[b] * c for (b, c) in zip(*a)] for a in
([(ci, li) for (ci, li) in zip(skip_channels_per_layers, skip_layers)])]
init_block_channels = 64
net = FishNet(
direct_channels=direct_channels,
skip_channels=skip_channels,
init_block_channels=init_block_channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def fishnet99(**kwargs):
"""
FishNet-99 model from 'FishNet: A Versatile Backbone for Image, Region, and Pixel Level Prediction,'
http://papers.nips.cc/paper/7356-fishnet-a-versatile-backbone-for-image-region-and-pixel-level-prediction.pdf.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_fishnet(blocks=99, model_name="fishnet99", **kwargs)
def fishnet150(**kwargs):
"""
FishNet-150 model from 'FishNet: A Versatile Backbone for Image, Region, and Pixel Level Prediction,'
http://papers.nips.cc/paper/7356-fishnet-a-versatile-backbone-for-image-region-and-pixel-level-prediction.pdf.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_fishnet(blocks=150, model_name="fishnet150", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
fishnet99,
fishnet150,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != fishnet99 or weight_count == 16628904)
assert (model != fishnet150 or weight_count == 24959400)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 20,141 | 29.845329 | 115 | py |
null | qimera-main/pytorchcv/models/fractalnet_cifar.py | """
FractalNet for CIFAR, implemented in PyTorch.
Original paper: 'FractalNet: Ultra-Deep Neural Networks without Residuals,' https://arxiv.org/abs/1605.07648.
"""
__all__ = ['CIFARFractalNet', 'fractalnet_cifar10', 'fractalnet_cifar100']
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import ParametricSequential
class DropConvBlock(nn.Module):
"""
Convolution block with Batch normalization, ReLU activation, and Dropout layer.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
bias : bool, default False
Whether the layer uses a bias vector.
dropout_rate : float, default 0.0
Parameter of Dropout layer. Faction of the input units to drop.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
bias=False,
dropout_prob=0.0):
super(DropConvBlock, self).__init__()
self.use_dropout = (dropout_prob != 0.0)
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
bias=bias)
self.bn = nn.BatchNorm2d(num_features=out_channels)
self.activ = nn.ReLU(inplace=True)
if self.use_dropout:
self.dropout = nn.Dropout2d(p=dropout_prob)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
x = self.activ(x)
if self.use_dropout:
x = self.dropout(x)
return x
def drop_conv3x3_block(in_channels,
out_channels,
stride=1,
padding=1,
bias=False,
dropout_prob=0.0):
"""
3x3 version of the convolution block with dropout.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
bias : bool, default False
Whether the layer uses a bias vector.
dropout_rate : float, default 0.0
Parameter of Dropout layer. Faction of the input units to drop.
"""
return DropConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=stride,
padding=padding,
bias=bias,
dropout_prob=dropout_prob)
class FractalBlock(nn.Module):
"""
FractalNet block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
num_columns : int
Number of columns in each block.
loc_drop_prob : float
Local drop path probability.
dropout_prob : float
Probability of dropout.
"""
def __init__(self,
in_channels,
out_channels,
num_columns,
loc_drop_prob,
dropout_prob):
super(FractalBlock, self).__init__()
assert (num_columns >= 1)
self.num_columns = num_columns
self.loc_drop_prob = loc_drop_prob
self.blocks = nn.Sequential()
depth = 2 ** (num_columns - 1)
for i in range(depth):
level_block_i = nn.Sequential()
for j in range(self.num_columns):
column_step_j = 2 ** j
if (i + 1) % column_step_j == 0:
in_channels_ij = in_channels if (i + 1 == column_step_j) else out_channels
level_block_i.add_module("subblock{}".format(j + 1), drop_conv3x3_block(
in_channels=in_channels_ij,
out_channels=out_channels,
dropout_prob=dropout_prob))
self.blocks.add_module("block{}".format(i + 1), level_block_i)
@staticmethod
def calc_drop_mask(batch_size,
glob_num_columns,
curr_num_columns,
max_num_columns,
loc_drop_prob):
"""
Calculate drop path mask.
Parameters:
----------
batch_size : int
Size of batch.
glob_num_columns : int
Number of columns in global drop path mask.
curr_num_columns : int
Number of active columns in the current level of block.
max_num_columns : int
Number of columns for all network.
loc_drop_prob : float
Local drop path probability.
Returns
-------
Tensor
Resulted mask.
"""
glob_batch_size = glob_num_columns.shape[0]
glob_drop_mask = np.zeros((curr_num_columns, glob_batch_size), dtype=np.float32)
glob_drop_num_columns = glob_num_columns - (max_num_columns - curr_num_columns)
glob_drop_indices = np.where(glob_drop_num_columns >= 0)[0]
glob_drop_mask[glob_drop_num_columns[glob_drop_indices], glob_drop_indices] = 1.0
loc_batch_size = batch_size - glob_batch_size
loc_drop_mask = np.random.binomial(
n=1,
p=(1.0 - loc_drop_prob),
size=(curr_num_columns, loc_batch_size)).astype(np.float32)
alive_count = loc_drop_mask.sum(axis=0)
dead_indices = np.where(alive_count == 0.0)[0]
loc_drop_mask[np.random.randint(0, curr_num_columns, size=dead_indices.shape), dead_indices] = 1.0
drop_mask = np.concatenate((glob_drop_mask, loc_drop_mask), axis=1)
return torch.from_numpy(drop_mask)
@staticmethod
def join_outs(raw_outs,
glob_num_columns,
num_columns,
loc_drop_prob,
training):
"""
Join outputs for current level of block.
Parameters:
----------
raw_outs : list of Tensor
Current outputs from active columns.
glob_num_columns : int
Number of columns in global drop path mask.
num_columns : int
Number of columns for all network.
loc_drop_prob : float
Local drop path probability.
training : bool
Whether training mode for network.
Returns
-------
Tensor
Joined output.
"""
curr_num_columns = len(raw_outs)
out = torch.stack(raw_outs, dim=0)
assert (out.size(0) == curr_num_columns)
if training:
batch_size = out.size(1)
batch_mask = FractalBlock.calc_drop_mask(
batch_size=batch_size,
glob_num_columns=glob_num_columns,
curr_num_columns=curr_num_columns,
max_num_columns=num_columns,
loc_drop_prob=loc_drop_prob)
batch_mask = batch_mask.to(out.device)
assert (batch_mask.size(0) == curr_num_columns)
assert (batch_mask.size(1) == batch_size)
batch_mask = batch_mask.unsqueeze(2).unsqueeze(3).unsqueeze(4)
masked_out = out * batch_mask
num_alive = batch_mask.sum(dim=0)
num_alive[num_alive == 0.0] = 1.0
out = masked_out.sum(dim=0) / num_alive
else:
out = out.mean(dim=0)
return out
def forward(self, x, glob_num_columns):
outs = [x] * self.num_columns
for level_block_i in self.blocks._modules.values():
outs_i = []
for j, block_ij in enumerate(level_block_i._modules.values()):
input_i = outs[j]
outs_i.append(block_ij(input_i))
joined_out = FractalBlock.join_outs(
raw_outs=outs_i[::-1],
glob_num_columns=glob_num_columns,
num_columns=self.num_columns,
loc_drop_prob=self.loc_drop_prob,
training=self.training)
len_level_block_i = len(level_block_i._modules.values())
for j in range(len_level_block_i):
outs[j] = joined_out
return outs[0]
class FractalUnit(nn.Module):
"""
FractalNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
num_columns : int
Number of columns in each block.
loc_drop_prob : float
Local drop path probability.
dropout_prob : float
Probability of dropout.
"""
def __init__(self,
in_channels,
out_channels,
num_columns,
loc_drop_prob,
dropout_prob):
super(FractalUnit, self).__init__()
self.block = FractalBlock(
in_channels=in_channels,
out_channels=out_channels,
num_columns=num_columns,
loc_drop_prob=loc_drop_prob,
dropout_prob=dropout_prob)
self.pool = nn.MaxPool2d(
kernel_size=2,
stride=2)
def forward(self, x, glob_num_columns):
x = self.block(x, glob_num_columns=glob_num_columns)
x = self.pool(x)
return x
class CIFARFractalNet(nn.Module):
"""
FractalNet model for CIFAR from 'FractalNet: Ultra-Deep Neural Networks without Residuals,'
https://arxiv.org/abs/1605.07648.
Parameters:
----------
channels : list of int
Number of output channels for each unit.
num_columns : int
Number of columns in each block.
dropout_probs : list of float
Probability of dropout in each block.
loc_drop_prob : float
Local drop path probability.
glob_drop_ratio : float
Global drop part fraction.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
num_classes : int, default 10
Number of classification classes.
"""
def __init__(self,
channels,
num_columns,
dropout_probs,
loc_drop_prob,
glob_drop_ratio,
in_channels=3,
in_size=(32, 32),
num_classes=10):
super(CIFARFractalNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.glob_drop_ratio = glob_drop_ratio
self.num_columns = num_columns
self.features = ParametricSequential()
for i, out_channels in enumerate(channels):
dropout_prob = dropout_probs[i]
self.features.add_module("unit{}".format(i + 1), FractalUnit(
in_channels=in_channels,
out_channels=out_channels,
num_columns=num_columns,
loc_drop_prob=loc_drop_prob,
dropout_prob=dropout_prob))
in_channels = out_channels
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
glob_batch_size = int(x.size(0) * self.glob_drop_ratio)
glob_num_columns = np.random.randint(0, self.num_columns, size=(glob_batch_size,))
x = self.features(x, glob_num_columns=glob_num_columns)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_fractalnet_cifar(num_classes,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create WRN model for CIFAR with specific parameters.
Parameters:
----------
num_classes : int
Number of classification classes.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
dropout_probs = (0.0, 0.1, 0.2, 0.3, 0.4)
channels = [64 * (2 ** (i if i != len(dropout_probs) - 1 else i - 1)) for i in range(len(dropout_probs))]
num_columns = 3
loc_drop_prob = 0.15
glob_drop_ratio = 0.5
net = CIFARFractalNet(
channels=channels,
num_columns=num_columns,
dropout_probs=dropout_probs,
loc_drop_prob=loc_drop_prob,
glob_drop_ratio=glob_drop_ratio,
num_classes=num_classes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def fractalnet_cifar10(num_classes=10, **kwargs):
"""
FractalNet model for CIFAR-10 from 'FractalNet: Ultra-Deep Neural Networks without Residuals,'
https://arxiv.org/abs/1605.07648.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_fractalnet_cifar(num_classes=num_classes, model_name="fractalnet_cifar10", **kwargs)
def fractalnet_cifar100(num_classes=100, **kwargs):
"""
FractalNet model for CIFAR-100 from 'FractalNet: Ultra-Deep Neural Networks without Residuals,'
https://arxiv.org/abs/1605.07648.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_fractalnet_cifar(num_classes=num_classes, model_name="fractalnet_cifar100", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
(fractalnet_cifar10, 10),
(fractalnet_cifar100, 100),
]
for model, num_classes in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != fractalnet_cifar10 or weight_count == 33724618)
assert (model != fractalnet_cifar100 or weight_count == 33770788)
x = torch.randn(1, 3, 32, 32)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, num_classes))
if __name__ == "__main__":
_test()
| 15,952 | 31.034137 | 115 | py |
null | qimera-main/pytorchcv/models/ibnbresnet.py | """
IBN(b)-ResNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
"""
__all__ = ['IBNbResNet', 'ibnb_resnet50', 'ibnb_resnet101', 'ibnb_resnet152']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block
from .resnet import ResBottleneck
class IBNbConvBlock(nn.Module):
"""
IBN(b)-ResNet specific convolution block with Instance normalization and ReLU activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
bias : bool, default False
Whether the layer uses a bias vector.
activate : bool, default True
Whether activate the convolution block.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
dilation=1,
groups=1,
bias=False,
activate=True):
super(IBNbConvBlock, self).__init__()
self.activate = activate
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
groups=groups,
bias=bias)
self.inst_norm = nn.InstanceNorm2d(
num_features=out_channels,
affine=True)
if self.activate:
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
x = self.conv(x)
x = self.inst_norm(x)
if self.activate:
x = self.activ(x)
return x
def ibnb_conv7x7_block(in_channels,
out_channels,
stride=1,
padding=3,
bias=False,
activate=True):
"""
7x7 version of the IBN(b)-ResNet specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 3
Padding value for convolution layer.
bias : bool, default False
Whether the layer uses a bias vector.
activate : bool, default True
Whether activate the convolution block.
"""
return IBNbConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=7,
stride=stride,
padding=padding,
bias=bias,
activate=activate)
class IBNbResUnit(nn.Module):
"""
IBN(b)-ResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
use_inst_norm : bool
Whether to use instance normalization.
"""
def __init__(self,
in_channels,
out_channels,
stride,
use_inst_norm):
super(IBNbResUnit, self).__init__()
self.use_inst_norm = use_inst_norm
self.resize_identity = (in_channels != out_channels) or (stride != 1)
self.body = ResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
conv1_stride=False)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
activation=None)
if self.use_inst_norm:
self.inst_norm = nn.InstanceNorm2d(
num_features=out_channels,
affine=True)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = x + identity
if self.use_inst_norm:
x = self.inst_norm(x)
x = self.activ(x)
return x
class IBNbResInitBlock(nn.Module):
"""
IBN(b)-ResNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(IBNbResInitBlock, self).__init__()
self.conv = ibnb_conv7x7_block(
in_channels=in_channels,
out_channels=out_channels,
stride=2)
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=1)
def forward(self, x):
x = self.conv(x)
x = self.pool(x)
return x
class IBNbResNet(nn.Module):
"""
IBN(b)-ResNet model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(IBNbResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", IBNbResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
use_inst_norm = (i < 2) and (j == len(channels_per_stage) - 1)
stage.add_module("unit{}".format(j + 1), IBNbResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
use_inst_norm=use_inst_norm))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_ibnbresnet(blocks,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create IBN(b)-ResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
else:
raise ValueError("Unsupported IBN(b)-ResNet with number of blocks: {}".format(blocks))
init_block_channels = 64
channels_per_layers = [256, 512, 1024, 2048]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = IBNbResNet(
channels=channels,
init_block_channels=init_block_channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def ibnb_resnet50(**kwargs):
"""
IBN(b)-ResNet-50 model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_ibnbresnet(blocks=50, model_name="ibnb_resnet50", **kwargs)
def ibnb_resnet101(**kwargs):
"""
IBN(b)-ResNet-101 model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_ibnbresnet(blocks=101, model_name="ibnb_resnet101", **kwargs)
def ibnb_resnet152(**kwargs):
"""
IBN(b)-ResNet-152 model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_ibnbresnet(blocks=152, model_name="ibnb_resnet152", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
ibnb_resnet50,
ibnb_resnet101,
ibnb_resnet152,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != ibnb_resnet50 or weight_count == 25558568)
assert (model != ibnb_resnet101 or weight_count == 44550696)
assert (model != ibnb_resnet152 or weight_count == 60194344)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 11,999 | 29 | 115 | py |
null | qimera-main/pytorchcv/models/ibndensenet.py | """
IBN-DenseNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
"""
__all__ = ['IBNDenseNet', 'ibn_densenet121', 'ibn_densenet161', 'ibn_densenet169', 'ibn_densenet201']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import pre_conv3x3_block, IBN
from .preresnet import PreResInitBlock, PreResActivation
from .densenet import TransitionBlock
class IBNPreConvBlock(nn.Module):
"""
IBN-Net specific convolution block with BN/IBN normalization and ReLU pre-activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
use_ibn : bool, default False
Whether use Instance-Batch Normalization.
return_preact : bool, default False
Whether return pre-activation. It's used by PreResNet.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
use_ibn=False,
return_preact=False):
super(IBNPreConvBlock, self).__init__()
self.use_ibn = use_ibn
self.return_preact = return_preact
if self.use_ibn:
self.ibn = IBN(
channels=in_channels,
first_fraction=0.6,
inst_first=False)
else:
self.bn = nn.BatchNorm2d(num_features=in_channels)
self.activ = nn.ReLU(inplace=True)
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
bias=False)
def forward(self, x):
if self.use_ibn:
x = self.ibn(x)
else:
x = self.bn(x)
x = self.activ(x)
if self.return_preact:
x_pre_activ = x
x = self.conv(x)
if self.return_preact:
return x, x_pre_activ
else:
return x
def ibn_pre_conv1x1_block(in_channels,
out_channels,
stride=1,
use_ibn=False,
return_preact=False):
"""
1x1 version of the IBN-Net specific pre-activated convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
use_ibn : bool, default False
Whether use Instance-Batch Normalization.
return_preact : bool, default False
Whether return pre-activation.
"""
return IBNPreConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
stride=stride,
padding=0,
use_ibn=use_ibn,
return_preact=return_preact)
class IBNDenseUnit(nn.Module):
"""
IBN-DenseNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
dropout_rate : float
Parameter of Dropout layer. Faction of the input units to drop.
conv1_ibn : bool
Whether to use IBN normalization in the first convolution layer of the block.
"""
def __init__(self,
in_channels,
out_channels,
dropout_rate,
conv1_ibn):
super(IBNDenseUnit, self).__init__()
self.use_dropout = (dropout_rate != 0.0)
bn_size = 4
inc_channels = out_channels - in_channels
mid_channels = inc_channels * bn_size
self.conv1 = ibn_pre_conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
use_ibn=conv1_ibn)
self.conv2 = pre_conv3x3_block(
in_channels=mid_channels,
out_channels=inc_channels)
if self.use_dropout:
self.dropout = nn.Dropout(p=dropout_rate)
def forward(self, x):
identity = x
x = self.conv1(x)
x = self.conv2(x)
if self.use_dropout:
x = self.dropout(x)
x = torch.cat((identity, x), dim=1)
return x
class IBNDenseNet(nn.Module):
"""
IBN-DenseNet model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
dropout_rate : float, default 0.0
Parameter of Dropout layer. Faction of the input units to drop.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
dropout_rate=0.0,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(IBNDenseNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", PreResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
if i != 0:
stage.add_module("trans{}".format(i + 1), TransitionBlock(
in_channels=in_channels,
out_channels=(in_channels // 2)))
in_channels = in_channels // 2
for j, out_channels in enumerate(channels_per_stage):
conv1_ibn = (i < 3) and (j % 3 == 0)
stage.add_module("unit{}".format(j + 1), IBNDenseUnit(
in_channels=in_channels,
out_channels=out_channels,
dropout_rate=dropout_rate,
conv1_ibn=conv1_ibn))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("post_activ", PreResActivation(in_channels=in_channels))
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_ibndensenet(num_layers,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create IBN-DenseNet model with specific parameters.
Parameters:
----------
num_layers : int
Number of layers.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if num_layers == 121:
init_block_channels = 64
growth_rate = 32
layers = [6, 12, 24, 16]
elif num_layers == 161:
init_block_channels = 96
growth_rate = 48
layers = [6, 12, 36, 24]
elif num_layers == 169:
init_block_channels = 64
growth_rate = 32
layers = [6, 12, 32, 32]
elif num_layers == 201:
init_block_channels = 64
growth_rate = 32
layers = [6, 12, 48, 32]
else:
raise ValueError("Unsupported IBN-DenseNet version with number of layers {}".format(num_layers))
from functools import reduce
channels = reduce(
lambda xi, yi: xi + [reduce(
lambda xj, yj: xj + [xj[-1] + yj],
[growth_rate] * yi,
[xi[-1][-1] // 2])[1:]],
layers,
[[init_block_channels * 2]])[1:]
net = IBNDenseNet(
channels=channels,
init_block_channels=init_block_channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def ibn_densenet121(**kwargs):
"""
IBN-DenseNet-121 model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_ibndensenet(num_layers=121, model_name="ibn_densenet121", **kwargs)
def ibn_densenet161(**kwargs):
"""
IBN-DenseNet-161 model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_ibndensenet(num_layers=161, model_name="ibn_densenet161", **kwargs)
def ibn_densenet169(**kwargs):
"""
IBN-DenseNet-169 model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_ibndensenet(num_layers=169, model_name="ibn_densenet169", **kwargs)
def ibn_densenet201(**kwargs):
"""
IBN-DenseNet-201 model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_ibndensenet(num_layers=201, model_name="ibn_densenet201", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
ibn_densenet121,
ibn_densenet161,
ibn_densenet169,
ibn_densenet201,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != ibn_densenet121 or weight_count == 7978856)
assert (model != ibn_densenet161 or weight_count == 28681000)
assert (model != ibn_densenet169 or weight_count == 14149480)
assert (model != ibn_densenet201 or weight_count == 20013928)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 12,647 | 30.384615 | 115 | py |
null | qimera-main/pytorchcv/models/ibnresnet.py | """
IBN-ResNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
"""
__all__ = ['IBNResNet', 'ibn_resnet50', 'ibn_resnet101', 'ibn_resnet152']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, conv3x3_block, IBN
from .resnet import ResInitBlock
class IBNConvBlock(nn.Module):
"""
IBN-Net specific convolution block with BN/IBN normalization and ReLU activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
bias : bool, default False
Whether the layer uses a bias vector.
use_ibn : bool, default False
Whether use Instance-Batch Normalization.
activate : bool, default True
Whether activate the convolution block.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
dilation=1,
groups=1,
bias=False,
use_ibn=False,
activate=True):
super(IBNConvBlock, self).__init__()
self.activate = activate
self.use_ibn = use_ibn
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
groups=groups,
bias=bias)
if self.use_ibn:
self.ibn = IBN(channels=out_channels)
else:
self.bn = nn.BatchNorm2d(num_features=out_channels)
if self.activate:
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
x = self.conv(x)
if self.use_ibn:
x = self.ibn(x)
else:
x = self.bn(x)
if self.activate:
x = self.activ(x)
return x
def ibn_conv1x1_block(in_channels,
out_channels,
stride=1,
groups=1,
bias=False,
use_ibn=False,
activate=True):
"""
1x1 version of the IBN-Net specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
groups : int, default 1
Number of groups.
bias : bool, default False
Whether the layer uses a bias vector.
use_ibn : bool, default False
Whether use Instance-Batch Normalization.
activate : bool, default True
Whether activate the convolution block.
"""
return IBNConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
stride=stride,
padding=0,
groups=groups,
bias=bias,
use_ibn=use_ibn,
activate=activate)
class IBNResBottleneck(nn.Module):
"""
IBN-ResNet bottleneck block for residual path in IBN-ResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
conv1_ibn : bool
Whether to use IBN normalization in the first convolution layer of the block.
"""
def __init__(self,
in_channels,
out_channels,
stride,
conv1_ibn):
super(IBNResBottleneck, self).__init__()
mid_channels = out_channels // 4
self.conv1 = ibn_conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
use_ibn=conv1_ibn)
self.conv2 = conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride)
self.conv3 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
activation=None)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class IBNResUnit(nn.Module):
"""
IBN-ResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
conv1_ibn : bool
Whether to use IBN normalization in the first convolution layer of the block.
"""
def __init__(self,
in_channels,
out_channels,
stride,
conv1_ibn):
super(IBNResUnit, self).__init__()
self.resize_identity = (in_channels != out_channels) or (stride != 1)
self.body = IBNResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
conv1_ibn=conv1_ibn)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
activation=None)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = x + identity
x = self.activ(x)
return x
class IBNResNet(nn.Module):
"""
IBN-ResNet model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(IBNResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
conv1_ibn = (out_channels < 2048)
stage.add_module("unit{}".format(j + 1), IBNResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
conv1_ibn=conv1_ibn))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_ibnresnet(blocks,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create IBN-ResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
else:
raise ValueError("Unsupported IBN-ResNet with number of blocks: {}".format(blocks))
init_block_channels = 64
channels_per_layers = [256, 512, 1024, 2048]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = IBNResNet(
channels=channels,
init_block_channels=init_block_channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def ibn_resnet50(**kwargs):
"""
IBN-ResNet-50 model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_ibnresnet(blocks=50, model_name="ibn_resnet50", **kwargs)
def ibn_resnet101(**kwargs):
"""
IBN-ResNet-101 model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_ibnresnet(blocks=101, model_name="ibn_resnet101", **kwargs)
def ibn_resnet152(**kwargs):
"""
IBN-ResNet-152 model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_ibnresnet(blocks=152, model_name="ibn_resnet152", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
ibn_resnet50,
ibn_resnet101,
ibn_resnet152,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != ibn_resnet50 or weight_count == 25557032)
assert (model != ibn_resnet101 or weight_count == 44549160)
assert (model != ibn_resnet152 or weight_count == 60192808)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 12,570 | 29.002387 | 115 | py |
null | qimera-main/pytorchcv/models/ibnresnext.py | """
IBN-ResNeXt for ImageNet-1K, implemented in PyTorch.
Original paper: 'Aggregated Residual Transformations for Deep Neural Networks,' http://arxiv.org/abs/1611.05431.
"""
__all__ = ['IBNResNeXt', 'ibn_resnext50_32x4d', 'ibn_resnext101_32x4d', 'ibn_resnext101_64x4d']
import os
import math
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, conv3x3_block
from .resnet import ResInitBlock
from .ibnresnet import ibn_conv1x1_block
class IBNResNeXtBottleneck(nn.Module):
"""
IBN-ResNeXt bottleneck block for residual path in IBN-ResNeXt unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
conv1_ibn : bool
Whether to use IBN normalization in the first convolution layer of the block.
"""
def __init__(self,
in_channels,
out_channels,
stride,
cardinality,
bottleneck_width,
conv1_ibn):
super(IBNResNeXtBottleneck, self).__init__()
mid_channels = out_channels // 4
D = int(math.floor(mid_channels * (bottleneck_width / 64.0)))
group_width = cardinality * D
self.conv1 = ibn_conv1x1_block(
in_channels=in_channels,
out_channels=group_width,
use_ibn=conv1_ibn)
self.conv2 = conv3x3_block(
in_channels=group_width,
out_channels=group_width,
stride=stride,
groups=cardinality)
self.conv3 = conv1x1_block(
in_channels=group_width,
out_channels=out_channels,
activation=None)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class IBNResNeXtUnit(nn.Module):
"""
IBN-ResNeXt unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
conv1_ibn : bool
Whether to use IBN normalization in the first convolution layer of the block.
"""
def __init__(self,
in_channels,
out_channels,
stride,
cardinality,
bottleneck_width,
conv1_ibn):
super(IBNResNeXtUnit, self).__init__()
self.resize_identity = (in_channels != out_channels) or (stride != 1)
self.body = IBNResNeXtBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
conv1_ibn=conv1_ibn)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
activation=None)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = x + identity
x = self.activ(x)
return x
class IBNResNeXt(nn.Module):
"""
IBN-ResNeXt model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
cardinality,
bottleneck_width,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(IBNResNeXt, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
conv1_ibn = (out_channels < 2048)
stage.add_module("unit{}".format(j + 1), IBNResNeXtUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
conv1_ibn=conv1_ibn))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_ibnresnext(blocks,
cardinality,
bottleneck_width,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create IBN-ResNeXt model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
else:
raise ValueError("Unsupported IBN-ResNeXt with number of blocks: {}".format(blocks))
init_block_channels = 64
channels_per_layers = [256, 512, 1024, 2048]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = IBNResNeXt(
channels=channels,
init_block_channels=init_block_channels,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def ibn_resnext50_32x4d(**kwargs):
"""
IBN-ResNeXt-50 (32x4d) model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_ibnresnext(blocks=50, cardinality=32, bottleneck_width=4, model_name="ibn_resnext50_32x4d", **kwargs)
def ibn_resnext101_32x4d(**kwargs):
"""
IBN-ResNeXt-101 (32x4d) model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_ibnresnext(blocks=101, cardinality=32, bottleneck_width=4, model_name="ibn_resnext101_32x4d", **kwargs)
def ibn_resnext101_64x4d(**kwargs):
"""
IBN-ResNeXt-101 (64x4d) model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_ibnresnext(blocks=101, cardinality=64, bottleneck_width=4, model_name="ibn_resnext101_64x4d", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
ibn_resnext50_32x4d,
ibn_resnext101_32x4d,
ibn_resnext101_64x4d,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != ibn_resnext50_32x4d or weight_count == 25028904)
assert (model != ibn_resnext101_32x4d or weight_count == 44177704)
assert (model != ibn_resnext101_64x4d or weight_count == 83455272)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 10,749 | 30.341108 | 118 | py |
null | qimera-main/pytorchcv/models/igcv3.py | """
IGCV3 for ImageNet-1K, implemented in PyTorch.
Original paper: 'IGCV3: Interleaved Low-Rank Group Convolutions for Efficient Deep Neural Networks,'
https://arxiv.org/abs/1806.00178.
"""
__all__ = ['IGCV3', 'igcv3_w1', 'igcv3_w3d4', 'igcv3_wd2', 'igcv3_wd4']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, conv3x3_block, dwconv3x3_block, ChannelShuffle
class InvResUnit(nn.Module):
"""
So-called 'Inverted Residual Unit' layer.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the second convolution layer.
expansion : bool
Whether do expansion of channels.
"""
def __init__(self,
in_channels,
out_channels,
stride,
expansion):
super(InvResUnit, self).__init__()
self.residual = (in_channels == out_channels) and (stride == 1)
mid_channels = in_channels * 6 if expansion else in_channels
groups = 2
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
groups=groups,
activation=None)
self.c_shuffle = ChannelShuffle(
channels=mid_channels,
groups=groups)
self.conv2 = dwconv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride,
activation="relu6")
self.conv3 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
groups=groups,
activation=None)
def forward(self, x):
if self.residual:
identity = x
x = self.conv1(x)
x = self.c_shuffle(x)
x = self.conv2(x)
x = self.conv3(x)
if self.residual:
x = x + identity
return x
class IGCV3(nn.Module):
"""
IGCV3 model from 'IGCV3: Interleaved Low-Rank Group Convolutions for Efficient Deep Neural Networks,'
https://arxiv.org/abs/1806.00178.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
final_block_channels : int
Number of output channels for the final block of the feature extractor.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
final_block_channels,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(IGCV3, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels,
stride=2,
activation="relu6"))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
expansion = (i != 0) or (j != 0)
stage.add_module("unit{}".format(j + 1), InvResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
expansion=expansion))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_block', conv1x1_block(
in_channels=in_channels,
out_channels=final_block_channels,
activation="relu6"))
in_channels = final_block_channels
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_igcv3(width_scale,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create IGCV3-D model with specific parameters.
Parameters:
----------
width_scale : float
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
init_block_channels = 32
final_block_channels = 1280
layers = [1, 4, 6, 8, 6, 6, 1]
downsample = [0, 1, 1, 1, 0, 1, 0]
channels_per_layers = [16, 24, 32, 64, 96, 160, 320]
from functools import reduce
channels = reduce(
lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]],
zip(channels_per_layers, layers, downsample),
[[]])
if width_scale != 1.0:
def make_even(x):
return x if (x % 2 == 0) else x + 1
channels = [[make_even(int(cij * width_scale)) for cij in ci] for ci in channels]
init_block_channels = make_even(int(init_block_channels * width_scale))
if width_scale > 1.0:
final_block_channels = make_even(int(final_block_channels * width_scale))
net = IGCV3(
channels=channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def igcv3_w1(**kwargs):
"""
IGCV3-D 1.0x model from 'IGCV3: Interleaved Low-Rank Group Convolutions for Efficient Deep Neural Networks,'
https://arxiv.org/abs/1806.00178.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_igcv3(width_scale=1.0, model_name="igcv3_w1", **kwargs)
def igcv3_w3d4(**kwargs):
"""
IGCV3-D 0.75x model from 'IGCV3: Interleaved Low-Rank Group Convolutions for Efficient Deep Neural Networks,'
https://arxiv.org/abs/1806.00178.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_igcv3(width_scale=0.75, model_name="igcv3_w3d4", **kwargs)
def igcv3_wd2(**kwargs):
"""
IGCV3-D 0.5x model from 'IGCV3: Interleaved Low-Rank Group Convolutions for Efficient Deep Neural Networks,'
https://arxiv.org/abs/1806.00178.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_igcv3(width_scale=0.5, model_name="igcv3_wd2", **kwargs)
def igcv3_wd4(**kwargs):
"""
IGCV3-D 0.25x model from 'IGCV3: Interleaved Low-Rank Group Convolutions for Efficient Deep Neural Networks,'
https://arxiv.org/abs/1806.00178.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_igcv3(width_scale=0.25, model_name="igcv3_wd4", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
igcv3_w1,
igcv3_w3d4,
igcv3_wd2,
igcv3_wd4,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != igcv3_w1 or weight_count == 3491688)
assert (model != igcv3_w3d4 or weight_count == 2638084)
assert (model != igcv3_wd2 or weight_count == 1985528)
assert (model != igcv3_wd4 or weight_count == 1534020)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 9,829 | 30.709677 | 115 | py |
null | qimera-main/pytorchcv/models/inceptionresnetv2.py | """
InceptionResNetV2 for ImageNet-1K, implemented in PyTorch.
Original paper: 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,'
https://arxiv.org/abs/1602.07261.
"""
__all__ = ['InceptionResNetV2', 'inceptionresnetv2']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1, Concurrent
class InceptConv(nn.Module):
"""
InceptionResNetV2 specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding):
super(InceptConv, self).__init__()
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
bias=False)
self.bn = nn.BatchNorm2d(
num_features=out_channels,
eps=1e-3,
momentum=0.1)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
x = self.activ(x)
return x
def incept_conv1x1(in_channels,
out_channels):
"""
1x1 version of the InceptionResNetV2 specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
return InceptConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
stride=1,
padding=0)
class MaxPoolBranch(nn.Module):
"""
InceptionResNetV2 specific max pooling branch block.
"""
def __init__(self):
super(MaxPoolBranch, self).__init__()
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=0)
def forward(self, x):
x = self.pool(x)
return x
class AvgPoolBranch(nn.Module):
"""
InceptionResNetV2 specific average pooling branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(AvgPoolBranch, self).__init__()
self.pool = nn.AvgPool2d(
kernel_size=3,
stride=1,
padding=1,
count_include_pad=False)
self.conv = incept_conv1x1(
in_channels=in_channels,
out_channels=out_channels)
def forward(self, x):
x = self.pool(x)
x = self.conv(x)
return x
class Conv1x1Branch(nn.Module):
"""
InceptionResNetV2 specific convolutional 1x1 branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(Conv1x1Branch, self).__init__()
self.conv = incept_conv1x1(
in_channels=in_channels,
out_channels=out_channels)
def forward(self, x):
x = self.conv(x)
return x
class ConvSeqBranch(nn.Module):
"""
InceptionResNetV2 specific convolutional sequence branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels_list : list of tuple of int
List of numbers of output channels.
kernel_size_list : list of tuple of int or tuple of tuple/list of 2 int
List of convolution window sizes.
strides_list : list of tuple of int or tuple of tuple/list of 2 int
List of strides of the convolution.
padding_list : list of tuple of int or tuple of tuple/list of 2 int
List of padding values for convolution layers.
"""
def __init__(self,
in_channels,
out_channels_list,
kernel_size_list,
strides_list,
padding_list):
super(ConvSeqBranch, self).__init__()
assert (len(out_channels_list) == len(kernel_size_list))
assert (len(out_channels_list) == len(strides_list))
assert (len(out_channels_list) == len(padding_list))
self.conv_list = nn.Sequential()
for i, (out_channels, kernel_size, strides, padding) in enumerate(zip(
out_channels_list, kernel_size_list, strides_list, padding_list)):
self.conv_list.add_module("conv{}".format(i + 1), InceptConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=strides,
padding=padding))
in_channels = out_channels
def forward(self, x):
x = self.conv_list(x)
return x
class InceptionAUnit(nn.Module):
"""
InceptionResNetV2 type Inception-A unit.
"""
def __init__(self):
super(InceptionAUnit, self).__init__()
self.scale = 0.17
in_channels = 320
self.branches = Concurrent()
self.branches.add_module("branch1", Conv1x1Branch(
in_channels=in_channels,
out_channels=32))
self.branches.add_module("branch2", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(32, 32),
kernel_size_list=(1, 3),
strides_list=(1, 1),
padding_list=(0, 1)))
self.branches.add_module("branch3", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(32, 48, 64),
kernel_size_list=(1, 3, 3),
strides_list=(1, 1, 1),
padding_list=(0, 1, 1)))
self.conv = conv1x1(
in_channels=128,
out_channels=in_channels,
bias=True)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
identity = x
x = self.branches(x)
x = self.conv(x)
x = self.scale * x + identity
x = self.activ(x)
return x
class ReductionAUnit(nn.Module):
"""
InceptionResNetV2 type Reduction-A unit.
"""
def __init__(self):
super(ReductionAUnit, self).__init__()
in_channels = 320
self.branches = Concurrent()
self.branches.add_module("branch1", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(384,),
kernel_size_list=(3,),
strides_list=(2,),
padding_list=(0,)))
self.branches.add_module("branch2", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(256, 256, 384),
kernel_size_list=(1, 3, 3),
strides_list=(1, 1, 2),
padding_list=(0, 1, 0)))
self.branches.add_module("branch3", MaxPoolBranch())
def forward(self, x):
x = self.branches(x)
return x
class InceptionBUnit(nn.Module):
"""
InceptionResNetV2 type Inception-B unit.
"""
def __init__(self):
super(InceptionBUnit, self).__init__()
self.scale = 0.10
in_channels = 1088
self.branches = Concurrent()
self.branches.add_module("branch1", Conv1x1Branch(
in_channels=in_channels,
out_channels=192))
self.branches.add_module("branch2", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(128, 160, 192),
kernel_size_list=(1, (1, 7), (7, 1)),
strides_list=(1, 1, 1),
padding_list=(0, (0, 3), (3, 0))))
self.conv = conv1x1(
in_channels=384,
out_channels=in_channels,
bias=True)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
identity = x
x = self.branches(x)
x = self.conv(x)
x = self.scale * x + identity
x = self.activ(x)
return x
class ReductionBUnit(nn.Module):
"""
InceptionResNetV2 type Reduction-B unit.
"""
def __init__(self):
super(ReductionBUnit, self).__init__()
in_channels = 1088
self.branches = Concurrent()
self.branches.add_module("branch1", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(256, 384),
kernel_size_list=(1, 3),
strides_list=(1, 2),
padding_list=(0, 0)))
self.branches.add_module("branch2", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(256, 288),
kernel_size_list=(1, 3),
strides_list=(1, 2),
padding_list=(0, 0)))
self.branches.add_module("branch3", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(256, 288, 320),
kernel_size_list=(1, 3, 3),
strides_list=(1, 1, 2),
padding_list=(0, 1, 0)))
self.branches.add_module("branch4", MaxPoolBranch())
def forward(self, x):
x = self.branches(x)
return x
class InceptionCUnit(nn.Module):
"""
InceptionResNetV2 type Inception-C unit.
Parameters:
----------
scale : float, default 1.0
Scale value for residual branch.
activate : bool, default True
Whether activate the convolution block.
"""
def __init__(self,
scale=0.2,
activate=True):
super(InceptionCUnit, self).__init__()
self.activate = activate
self.scale = scale
in_channels = 2080
self.branches = Concurrent()
self.branches.add_module("branch1", Conv1x1Branch(
in_channels=in_channels,
out_channels=192))
self.branches.add_module("branch2", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(192, 224, 256),
kernel_size_list=(1, (1, 3), (3, 1)),
strides_list=(1, 1, 1),
padding_list=(0, (0, 1), (1, 0))))
self.conv = conv1x1(
in_channels=448,
out_channels=in_channels,
bias=True)
if self.activate:
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
identity = x
x = self.branches(x)
x = self.conv(x)
x = self.scale * x + identity
if self.activate:
x = self.activ(x)
return x
class InceptBlock5b(nn.Module):
"""
InceptionResNetV2 type Mixed-5b block.
"""
def __init__(self):
super(InceptBlock5b, self).__init__()
in_channels = 192
self.branches = Concurrent()
self.branches.add_module("branch1", Conv1x1Branch(
in_channels=in_channels,
out_channels=96))
self.branches.add_module("branch2", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(48, 64),
kernel_size_list=(1, 5),
strides_list=(1, 1),
padding_list=(0, 2)))
self.branches.add_module("branch3", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(64, 96, 96),
kernel_size_list=(1, 3, 3),
strides_list=(1, 1, 1),
padding_list=(0, 1, 1)))
self.branches.add_module("branch4", AvgPoolBranch(
in_channels=in_channels,
out_channels=64))
def forward(self, x):
x = self.branches(x)
return x
class InceptInitBlock(nn.Module):
"""
InceptionResNetV2 specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
"""
def __init__(self,
in_channels):
super(InceptInitBlock, self).__init__()
self.conv1 = InceptConv(
in_channels=in_channels,
out_channels=32,
kernel_size=3,
stride=2,
padding=0)
self.conv2 = InceptConv(
in_channels=32,
out_channels=32,
kernel_size=3,
stride=1,
padding=0)
self.conv3 = InceptConv(
in_channels=32,
out_channels=64,
kernel_size=3,
stride=1,
padding=1)
self.pool1 = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=0)
self.conv4 = InceptConv(
in_channels=64,
out_channels=80,
kernel_size=1,
stride=1,
padding=0)
self.conv5 = InceptConv(
in_channels=80,
out_channels=192,
kernel_size=3,
stride=1,
padding=0)
self.pool2 = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=0)
self.block = InceptBlock5b()
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.pool1(x)
x = self.conv4(x)
x = self.conv5(x)
x = self.pool2(x)
x = self.block(x)
return x
class InceptionResNetV2(nn.Module):
"""
InceptionResNetV2 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,'
https://arxiv.org/abs/1602.07261.
Parameters:
----------
dropout_rate : float, default 0.0
Fraction of the input units to drop. Must be a number between 0 and 1.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (299, 299)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
dropout_rate=0.0,
in_channels=3,
in_size=(299, 299),
num_classes=1000):
super(InceptionResNetV2, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
layers = [10, 21, 11]
normal_units = [InceptionAUnit, InceptionBUnit, InceptionCUnit]
reduction_units = [ReductionAUnit, ReductionBUnit]
self.features = nn.Sequential()
self.features.add_module("init_block", InceptInitBlock(
in_channels=in_channels))
for i, layers_per_stage in enumerate(layers):
stage = nn.Sequential()
for j in range(layers_per_stage):
if (j == 0) and (i != 0):
unit = reduction_units[i - 1]
else:
unit = normal_units[i]
if (i == len(layers) - 1) and (j == layers_per_stage - 1):
stage.add_module("unit{}".format(j + 1), unit(scale=1.0, activate=False))
else:
stage.add_module("unit{}".format(j + 1), unit())
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_conv', incept_conv1x1(
in_channels=2080,
out_channels=1536))
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=8,
stride=1))
self.output = nn.Sequential()
if dropout_rate > 0.0:
self.output.add_module('dropout', nn.Dropout(p=dropout_rate))
self.output.add_module('fc', nn.Linear(
in_features=1536,
out_features=num_classes))
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_inceptionresnetv2(model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create InceptionResNetV2 model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
net = InceptionResNetV2(**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def inceptionresnetv2(**kwargs):
"""
InceptionResNetV2 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,'
https://arxiv.org/abs/1602.07261.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_inceptionresnetv2(model_name="inceptionresnetv2", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
inceptionresnetv2,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != inceptionresnetv2 or weight_count == 55843464)
x = torch.randn(1, 3, 299, 299)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 18,580 | 28.540541 | 117 | py |
null | qimera-main/pytorchcv/models/inceptionv3.py | """
InceptionV3 for ImageNet-1K, implemented in PyTorch.
Original paper: 'Rethinking the Inception Architecture for Computer Vision,'
https://arxiv.org/abs/1512.00567.
"""
__all__ = ['InceptionV3', 'inceptionv3']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import Concurrent
class InceptConv(nn.Module):
"""
InceptionV3 specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding):
super(InceptConv, self).__init__()
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
bias=False)
self.bn = nn.BatchNorm2d(
num_features=out_channels,
eps=1e-3)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
x = self.activ(x)
return x
def incept_conv1x1(in_channels,
out_channels):
"""
1x1 version of the InceptionV3 specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
return InceptConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
stride=1,
padding=0)
class MaxPoolBranch(nn.Module):
"""
InceptionV3 specific max pooling branch block.
"""
def __init__(self):
super(MaxPoolBranch, self).__init__()
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=0)
def forward(self, x):
x = self.pool(x)
return x
class AvgPoolBranch(nn.Module):
"""
InceptionV3 specific average pooling branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(AvgPoolBranch, self).__init__()
self.pool = nn.AvgPool2d(
kernel_size=3,
stride=1,
padding=1)
self.conv = incept_conv1x1(
in_channels=in_channels,
out_channels=out_channels)
def forward(self, x):
x = self.pool(x)
x = self.conv(x)
return x
class Conv1x1Branch(nn.Module):
"""
InceptionV3 specific convolutional 1x1 branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(Conv1x1Branch, self).__init__()
self.conv = incept_conv1x1(
in_channels=in_channels,
out_channels=out_channels)
def forward(self, x):
x = self.conv(x)
return x
class ConvSeqBranch(nn.Module):
"""
InceptionV3 specific convolutional sequence branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels_list : list of tuple of int
List of numbers of output channels.
kernel_size_list : list of tuple of int or tuple of tuple/list of 2 int
List of convolution window sizes.
strides_list : list of tuple of int or tuple of tuple/list of 2 int
List of strides of the convolution.
padding_list : list of tuple of int or tuple of tuple/list of 2 int
List of padding values for convolution layers.
"""
def __init__(self,
in_channels,
out_channels_list,
kernel_size_list,
strides_list,
padding_list):
super(ConvSeqBranch, self).__init__()
assert (len(out_channels_list) == len(kernel_size_list))
assert (len(out_channels_list) == len(strides_list))
assert (len(out_channels_list) == len(padding_list))
self.conv_list = nn.Sequential()
for i, (out_channels, kernel_size, strides, padding) in enumerate(zip(
out_channels_list, kernel_size_list, strides_list, padding_list)):
self.conv_list.add_module("conv{}".format(i + 1), InceptConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=strides,
padding=padding))
in_channels = out_channels
def forward(self, x):
x = self.conv_list(x)
return x
class ConvSeq3x3Branch(nn.Module):
"""
InceptionV3 specific convolutional sequence branch block with splitting by 3x3.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels_list : list of tuple of int
List of numbers of output channels.
kernel_size_list : list of tuple of int or tuple of tuple/list of 2 int
List of convolution window sizes.
strides_list : list of tuple of int or tuple of tuple/list of 2 int
List of strides of the convolution.
padding_list : list of tuple of int or tuple of tuple/list of 2 int
List of padding values for convolution layers.
"""
def __init__(self,
in_channels,
out_channels_list,
kernel_size_list,
strides_list,
padding_list):
super(ConvSeq3x3Branch, self).__init__()
self.conv_list = nn.Sequential()
for i, (out_channels, kernel_size, strides, padding) in enumerate(zip(
out_channels_list, kernel_size_list, strides_list, padding_list)):
self.conv_list.add_module("conv{}".format(i + 1), InceptConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=strides,
padding=padding))
in_channels = out_channels
self.conv1x3 = InceptConv(
in_channels=in_channels,
out_channels=in_channels,
kernel_size=(1, 3),
stride=1,
padding=(0, 1))
self.conv3x1 = InceptConv(
in_channels=in_channels,
out_channels=in_channels,
kernel_size=(3, 1),
stride=1,
padding=(1, 0))
def forward(self, x):
x = self.conv_list(x)
y1 = self.conv1x3(x)
y2 = self.conv3x1(x)
x = torch.cat((y1, y2), dim=1)
return x
class InceptionAUnit(nn.Module):
"""
InceptionV3 type Inception-A unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(InceptionAUnit, self).__init__()
assert (out_channels > 224)
pool_out_channels = out_channels - 224
self.branches = Concurrent()
self.branches.add_module("branch1", Conv1x1Branch(
in_channels=in_channels,
out_channels=64))
self.branches.add_module("branch2", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(48, 64),
kernel_size_list=(1, 5),
strides_list=(1, 1),
padding_list=(0, 2)))
self.branches.add_module("branch3", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(64, 96, 96),
kernel_size_list=(1, 3, 3),
strides_list=(1, 1, 1),
padding_list=(0, 1, 1)))
self.branches.add_module("branch4", AvgPoolBranch(
in_channels=in_channels,
out_channels=pool_out_channels))
def forward(self, x):
x = self.branches(x)
return x
class ReductionAUnit(nn.Module):
"""
InceptionV3 type Reduction-A unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(ReductionAUnit, self).__init__()
assert (in_channels == 288)
assert (out_channels == 768)
self.branches = Concurrent()
self.branches.add_module("branch1", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(384,),
kernel_size_list=(3,),
strides_list=(2,),
padding_list=(0,)))
self.branches.add_module("branch2", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(64, 96, 96),
kernel_size_list=(1, 3, 3),
strides_list=(1, 1, 2),
padding_list=(0, 1, 0)))
self.branches.add_module("branch3", MaxPoolBranch())
def forward(self, x):
x = self.branches(x)
return x
class InceptionBUnit(nn.Module):
"""
InceptionV3 type Inception-B unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
mid_channels : int
Number of output channels in the 7x7 branches.
"""
def __init__(self,
in_channels,
out_channels,
mid_channels):
super(InceptionBUnit, self).__init__()
assert (in_channels == 768)
assert (out_channels == 768)
self.branches = Concurrent()
self.branches.add_module("branch1", Conv1x1Branch(
in_channels=in_channels,
out_channels=192))
self.branches.add_module("branch2", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(mid_channels, mid_channels, 192),
kernel_size_list=(1, (1, 7), (7, 1)),
strides_list=(1, 1, 1),
padding_list=(0, (0, 3), (3, 0))))
self.branches.add_module("branch3", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(mid_channels, mid_channels, mid_channels, mid_channels, 192),
kernel_size_list=(1, (7, 1), (1, 7), (7, 1), (1, 7)),
strides_list=(1, 1, 1, 1, 1),
padding_list=(0, (3, 0), (0, 3), (3, 0), (0, 3))))
self.branches.add_module("branch4", AvgPoolBranch(
in_channels=in_channels,
out_channels=192))
def forward(self, x):
x = self.branches(x)
return x
class ReductionBUnit(nn.Module):
"""
InceptionV3 type Reduction-B unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(ReductionBUnit, self).__init__()
assert (in_channels == 768)
assert (out_channels == 1280)
self.branches = Concurrent()
self.branches.add_module("branch1", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(192, 320),
kernel_size_list=(1, 3),
strides_list=(1, 2),
padding_list=(0, 0)))
self.branches.add_module("branch2", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(192, 192, 192, 192),
kernel_size_list=(1, (1, 7), (7, 1), 3),
strides_list=(1, 1, 1, 2),
padding_list=(0, (0, 3), (3, 0), 0)))
self.branches.add_module("branch3", MaxPoolBranch())
def forward(self, x):
x = self.branches(x)
return x
class InceptionCUnit(nn.Module):
"""
InceptionV3 type Inception-C unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(InceptionCUnit, self).__init__()
assert (out_channels == 2048)
self.branches = Concurrent()
self.branches.add_module("branch1", Conv1x1Branch(
in_channels=in_channels,
out_channels=320))
self.branches.add_module("branch2", ConvSeq3x3Branch(
in_channels=in_channels,
out_channels_list=(384,),
kernel_size_list=(1,),
strides_list=(1,),
padding_list=(0,)))
self.branches.add_module("branch3", ConvSeq3x3Branch(
in_channels=in_channels,
out_channels_list=(448, 384),
kernel_size_list=(1, 3),
strides_list=(1, 1),
padding_list=(0, 1)))
self.branches.add_module("branch4", AvgPoolBranch(
in_channels=in_channels,
out_channels=192))
def forward(self, x):
x = self.branches(x)
return x
class InceptInitBlock(nn.Module):
"""
InceptionV3 specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(InceptInitBlock, self).__init__()
assert (out_channels == 192)
self.conv1 = InceptConv(
in_channels=in_channels,
out_channels=32,
kernel_size=3,
stride=2,
padding=0)
self.conv2 = InceptConv(
in_channels=32,
out_channels=32,
kernel_size=3,
stride=1,
padding=0)
self.conv3 = InceptConv(
in_channels=32,
out_channels=64,
kernel_size=3,
stride=1,
padding=1)
self.pool1 = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=0)
self.conv4 = InceptConv(
in_channels=64,
out_channels=80,
kernel_size=1,
stride=1,
padding=0)
self.conv5 = InceptConv(
in_channels=80,
out_channels=192,
kernel_size=3,
stride=1,
padding=0)
self.pool2 = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=0)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.pool1(x)
x = self.conv4(x)
x = self.conv5(x)
x = self.pool2(x)
return x
class InceptionV3(nn.Module):
"""
InceptionV3 model from 'Rethinking the Inception Architecture for Computer Vision,'
https://arxiv.org/abs/1512.00567.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
b_mid_channels : list of int
Number of middle channels for each Inception-B unit.
dropout_rate : float, default 0.0
Fraction of the input units to drop. Must be a number between 0 and 1.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (299, 299)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
b_mid_channels,
dropout_rate=0.5,
in_channels=3,
in_size=(299, 299),
num_classes=1000):
super(InceptionV3, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
normal_units = [InceptionAUnit, InceptionBUnit, InceptionCUnit]
reduction_units = [ReductionAUnit, ReductionBUnit]
self.features = nn.Sequential()
self.features.add_module("init_block", InceptInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
if (j == 0) and (i != 0):
unit = reduction_units[i - 1]
else:
unit = normal_units[i]
if unit == InceptionBUnit:
stage.add_module("unit{}".format(j + 1), unit(
in_channels=in_channels,
out_channels=out_channels,
mid_channels=b_mid_channels[j - 1]))
else:
stage.add_module("unit{}".format(j + 1), unit(
in_channels=in_channels,
out_channels=out_channels))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=8,
stride=1))
self.output = nn.Sequential()
self.output.add_module('dropout', nn.Dropout(p=dropout_rate))
self.output.add_module('fc', nn.Linear(
in_features=in_channels,
out_features=num_classes))
self._init_params()
def _init_params(self):
for module in self.modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_inceptionv3(model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create InceptionV3 model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
init_block_channels = 192
channels = [[256, 288, 288],
[768, 768, 768, 768, 768],
[1280, 2048, 2048]]
b_mid_channels = [128, 160, 160, 192]
net = InceptionV3(
channels=channels,
init_block_channels=init_block_channels,
b_mid_channels=b_mid_channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def inceptionv3(**kwargs):
"""
InceptionV3 model from 'Rethinking the Inception Architecture for Computer Vision,'
https://arxiv.org/abs/1512.00567.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_inceptionv3(model_name="inceptionv3", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
inceptionv3,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != inceptionv3 or weight_count == 23834568)
x = torch.randn(1, 3, 299, 299)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 20,977 | 28.968571 | 115 | py |
null | qimera-main/pytorchcv/models/inceptionv4.py | """
InceptionV4 for ImageNet-1K, implemented in PyTorch.
Original paper: 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,'
https://arxiv.org/abs/1602.07261.
"""
__all__ = ['InceptionV4', 'inceptionv4']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import Concurrent
class InceptConv(nn.Module):
"""
InceptionV4 specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding):
super(InceptConv, self).__init__()
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
bias=False)
self.bn = nn.BatchNorm2d(
num_features=out_channels,
eps=1e-3,
momentum=0.1)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
x = self.activ(x)
return x
def incept_conv1x1(in_channels,
out_channels):
"""
1x1 version of the InceptionV4 specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
return InceptConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
stride=1,
padding=0)
def incept_conv3x3(in_channels,
out_channels,
stride,
padding=1):
"""
3x3 version of the InceptionV4 specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int, default 0
Padding value for convolution layer.
"""
return InceptConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=stride,
padding=padding)
class MaxPoolBranch(nn.Module):
"""
InceptionV4 specific max pooling branch block.
"""
def __init__(self):
super(MaxPoolBranch, self).__init__()
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=0)
def forward(self, x):
x = self.pool(x)
return x
class AvgPoolBranch(nn.Module):
"""
InceptionV4 specific average pooling branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(AvgPoolBranch, self).__init__()
self.pool = nn.AvgPool2d(
kernel_size=3,
stride=1,
padding=1,
count_include_pad=False)
self.conv = incept_conv1x1(
in_channels=in_channels,
out_channels=out_channels)
def forward(self, x):
x = self.pool(x)
x = self.conv(x)
return x
class Conv1x1Branch(nn.Module):
"""
InceptionV4 specific convolutional 1x1 branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(Conv1x1Branch, self).__init__()
self.conv = incept_conv1x1(
in_channels=in_channels,
out_channels=out_channels)
def forward(self, x):
x = self.conv(x)
return x
class Conv3x3Branch(nn.Module):
"""
InceptionV4 specific convolutional 3x3 branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(Conv3x3Branch, self).__init__()
self.conv = incept_conv3x3(
in_channels=in_channels,
out_channels=out_channels,
stride=2,
padding=0)
def forward(self, x):
x = self.conv(x)
return x
class ConvSeqBranch(nn.Module):
"""
InceptionV4 specific convolutional sequence branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels_list : list of tuple of int
List of numbers of output channels.
kernel_size_list : list of tuple of int or tuple of tuple/list of 2 int
List of convolution window sizes.
strides_list : list of tuple of int or tuple of tuple/list of 2 int
List of strides of the convolution.
padding_list : list of tuple of int or tuple of tuple/list of 2 int
List of padding values for convolution layers.
"""
def __init__(self,
in_channels,
out_channels_list,
kernel_size_list,
strides_list,
padding_list):
super(ConvSeqBranch, self).__init__()
assert (len(out_channels_list) == len(kernel_size_list))
assert (len(out_channels_list) == len(strides_list))
assert (len(out_channels_list) == len(padding_list))
self.conv_list = nn.Sequential()
for i, (out_channels, kernel_size, strides, padding) in enumerate(zip(
out_channels_list, kernel_size_list, strides_list, padding_list)):
self.conv_list.add_module("conv{}".format(i + 1), InceptConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=strides,
padding=padding))
in_channels = out_channels
def forward(self, x):
x = self.conv_list(x)
return x
class ConvSeq3x3Branch(nn.Module):
"""
InceptionV4 specific convolutional sequence branch block with splitting by 3x3.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
mid_channels_list : list of tuple of int
List of numbers of output channels for middle layers.
kernel_size_list : list of tuple of int or tuple of tuple/list of 2 int
List of convolution window sizes.
strides_list : list of tuple of int or tuple of tuple/list of 2 int
List of strides of the convolution.
padding_list : list of tuple of int or tuple of tuple/list of 2 int
List of padding values for convolution layers.
"""
def __init__(self,
in_channels,
out_channels,
mid_channels_list,
kernel_size_list,
strides_list,
padding_list):
super(ConvSeq3x3Branch, self).__init__()
self.conv_list = nn.Sequential()
for i, (mid_channels, kernel_size, strides, padding) in enumerate(zip(
mid_channels_list, kernel_size_list, strides_list, padding_list)):
self.conv_list.add_module("conv{}".format(i + 1), InceptConv(
in_channels=in_channels,
out_channels=mid_channels,
kernel_size=kernel_size,
stride=strides,
padding=padding))
in_channels = mid_channels
self.conv1x3 = InceptConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=(1, 3),
stride=1,
padding=(0, 1))
self.conv3x1 = InceptConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=(3, 1),
stride=1,
padding=(1, 0))
def forward(self, x):
x = self.conv_list(x)
y1 = self.conv1x3(x)
y2 = self.conv3x1(x)
x = torch.cat((y1, y2), dim=1)
return x
class InceptionAUnit(nn.Module):
"""
InceptionV4 type Inception-A unit.
"""
def __init__(self):
super(InceptionAUnit, self).__init__()
in_channels = 384
self.branches = Concurrent()
self.branches.add_module("branch1", Conv1x1Branch(
in_channels=in_channels,
out_channels=96))
self.branches.add_module("branch2", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(64, 96),
kernel_size_list=(1, 3),
strides_list=(1, 1),
padding_list=(0, 1)))
self.branches.add_module("branch3", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(64, 96, 96),
kernel_size_list=(1, 3, 3),
strides_list=(1, 1, 1),
padding_list=(0, 1, 1)))
self.branches.add_module("branch4", AvgPoolBranch(
in_channels=in_channels,
out_channels=96))
def forward(self, x):
x = self.branches(x)
return x
class ReductionAUnit(nn.Module):
"""
InceptionV4 type Reduction-A unit.
"""
def __init__(self):
super(ReductionAUnit, self).__init__()
in_channels = 384
self.branches = Concurrent()
self.branches.add_module("branch1", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(384,),
kernel_size_list=(3,),
strides_list=(2,),
padding_list=(0,)))
self.branches.add_module("branch2", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(192, 224, 256),
kernel_size_list=(1, 3, 3),
strides_list=(1, 1, 2),
padding_list=(0, 1, 0)))
self.branches.add_module("branch3", MaxPoolBranch())
def forward(self, x):
x = self.branches(x)
return x
class InceptionBUnit(nn.Module):
"""
InceptionV4 type Inception-B unit.
"""
def __init__(self):
super(InceptionBUnit, self).__init__()
in_channels = 1024
self.branches = Concurrent()
self.branches.add_module("branch1", Conv1x1Branch(
in_channels=in_channels,
out_channels=384))
self.branches.add_module("branch2", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(192, 224, 256),
kernel_size_list=(1, (1, 7), (7, 1)),
strides_list=(1, 1, 1),
padding_list=(0, (0, 3), (3, 0))))
self.branches.add_module("branch3", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(192, 192, 224, 224, 256),
kernel_size_list=(1, (7, 1), (1, 7), (7, 1), (1, 7)),
strides_list=(1, 1, 1, 1, 1),
padding_list=(0, (3, 0), (0, 3), (3, 0), (0, 3))))
self.branches.add_module("branch4", AvgPoolBranch(
in_channels=in_channels,
out_channels=128))
def forward(self, x):
x = self.branches(x)
return x
class ReductionBUnit(nn.Module):
"""
InceptionV4 type Reduction-B unit.
"""
def __init__(self):
super(ReductionBUnit, self).__init__()
in_channels = 1024
self.branches = Concurrent()
self.branches.add_module("branch1", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(192, 192),
kernel_size_list=(1, 3),
strides_list=(1, 2),
padding_list=(0, 0)))
self.branches.add_module("branch2", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(256, 256, 320, 320),
kernel_size_list=(1, (1, 7), (7, 1), 3),
strides_list=(1, 1, 1, 2),
padding_list=(0, (0, 3), (3, 0), 0)))
self.branches.add_module("branch3", MaxPoolBranch())
def forward(self, x):
x = self.branches(x)
return x
class InceptionCUnit(nn.Module):
"""
InceptionV4 type Inception-C unit.
"""
def __init__(self):
super(InceptionCUnit, self).__init__()
in_channels = 1536
self.branches = Concurrent()
self.branches.add_module("branch1", Conv1x1Branch(
in_channels=in_channels,
out_channels=256))
self.branches.add_module("branch2", ConvSeq3x3Branch(
in_channels=in_channels,
out_channels=256,
mid_channels_list=(384,),
kernel_size_list=(1,),
strides_list=(1,),
padding_list=(0,)))
self.branches.add_module("branch3", ConvSeq3x3Branch(
in_channels=in_channels,
out_channels=256,
mid_channels_list=(384, 448, 512),
kernel_size_list=(1, (3, 1), (1, 3)),
strides_list=(1, 1, 1),
padding_list=(0, (1, 0), (0, 1))))
self.branches.add_module("branch4", AvgPoolBranch(
in_channels=in_channels,
out_channels=256))
def forward(self, x):
x = self.branches(x)
return x
class InceptBlock3a(nn.Module):
"""
InceptionV4 type Mixed-3a block.
"""
def __init__(self):
super(InceptBlock3a, self).__init__()
self.branches = Concurrent()
self.branches.add_module("branch1", MaxPoolBranch())
self.branches.add_module("branch2", Conv3x3Branch(
in_channels=64,
out_channels=96))
def forward(self, x):
x = self.branches(x)
return x
class InceptBlock4a(nn.Module):
"""
InceptionV4 type Mixed-4a block.
"""
def __init__(self):
super(InceptBlock4a, self).__init__()
self.branches = Concurrent()
self.branches.add_module("branch1", ConvSeqBranch(
in_channels=160,
out_channels_list=(64, 96),
kernel_size_list=(1, 3),
strides_list=(1, 1),
padding_list=(0, 0)))
self.branches.add_module("branch2", ConvSeqBranch(
in_channels=160,
out_channels_list=(64, 64, 64, 96),
kernel_size_list=(1, (1, 7), (7, 1), 3),
strides_list=(1, 1, 1, 1),
padding_list=(0, (0, 3), (3, 0), 0)))
def forward(self, x):
x = self.branches(x)
return x
class InceptBlock5a(nn.Module):
"""
InceptionV4 type Mixed-5a block.
"""
def __init__(self):
super(InceptBlock5a, self).__init__()
self.branches = Concurrent()
self.branches.add_module("branch1", Conv3x3Branch(
in_channels=192,
out_channels=192))
self.branches.add_module("branch2", MaxPoolBranch())
def forward(self, x):
x = self.branches(x)
return x
class InceptInitBlock(nn.Module):
"""
InceptionV4 specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
"""
def __init__(self,
in_channels):
super(InceptInitBlock, self).__init__()
self.conv1 = InceptConv(
in_channels=in_channels,
out_channels=32,
kernel_size=3,
stride=2,
padding=0)
self.conv2 = InceptConv(
in_channels=32,
out_channels=32,
kernel_size=3,
stride=1,
padding=0)
self.conv3 = InceptConv(
in_channels=32,
out_channels=64,
kernel_size=3,
stride=1,
padding=1)
self.block1 = InceptBlock3a()
self.block2 = InceptBlock4a()
self.block3 = InceptBlock5a()
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.block1(x)
x = self.block2(x)
x = self.block3(x)
return x
class InceptionV4(nn.Module):
"""
InceptionV4 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,'
https://arxiv.org/abs/1602.07261.
Parameters:
----------
dropout_rate : float, default 0.0
Fraction of the input units to drop. Must be a number between 0 and 1.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (299, 299)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
dropout_rate=0.0,
in_channels=3,
in_size=(299, 299),
num_classes=1000):
super(InceptionV4, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
layers = [4, 8, 4]
normal_units = [InceptionAUnit, InceptionBUnit, InceptionCUnit]
reduction_units = [ReductionAUnit, ReductionBUnit]
self.features = nn.Sequential()
self.features.add_module("init_block", InceptInitBlock(
in_channels=in_channels))
for i, layers_per_stage in enumerate(layers):
stage = nn.Sequential()
for j in range(layers_per_stage):
if (j == 0) and (i != 0):
unit = reduction_units[i - 1]
else:
unit = normal_units[i]
stage.add_module("unit{}".format(j + 1), unit())
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=8,
stride=1))
self.output = nn.Sequential()
if dropout_rate > 0.0:
self.output.add_module('dropout', nn.Dropout(p=dropout_rate))
self.output.add_module('fc', nn.Linear(
in_features=1536,
out_features=num_classes))
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_inceptionv4(model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create InceptionV4 model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
net = InceptionV4(**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def inceptionv4(**kwargs):
"""
InceptionV4 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,'
https://arxiv.org/abs/1602.07261.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_inceptionv4(model_name="inceptionv4", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
inceptionv4,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != InceptionV4 or weight_count == 42679816)
x = torch.randn(1, 3, 299, 299)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 21,112 | 28.570028 | 115 | py |
null | qimera-main/pytorchcv/models/irevnet.py | """
i-RevNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'i-RevNet: Deep Invertible Networks,' https://arxiv.org/abs/1802.07088.
"""
__all__ = ['IRevNet', 'irevnet301', 'IRevDownscale', 'IRevSplitBlock', 'IRevMergeBlock']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv3x3, pre_conv3x3_block, DualPathSequential
class IRevDualPathSequential(DualPathSequential):
"""
An invertible sequential container for modules with dual inputs/outputs.
Modules will be executed in the order they are added.
Parameters:
----------
return_two : bool, default True
Whether to return two output after execution.
first_ordinals : int, default 0
Number of the first modules with single input/output.
last_ordinals : int, default 0
Number of the final modules with single input/output.
dual_path_scheme : function
Scheme of dual path response for a module.
dual_path_scheme_ordinal : function
Scheme of dual path response for an ordinal module.
last_noninvertible : int, default 0
Number of the final modules skipped during inverse.
"""
def __init__(self,
return_two=True,
first_ordinals=0,
last_ordinals=0,
dual_path_scheme=(lambda module, x1, x2: module(x1, x2)),
dual_path_scheme_ordinal=(lambda module, x1, x2: (module(x1), x2)),
last_noninvertible=0):
super(IRevDualPathSequential, self).__init__(
return_two=return_two,
first_ordinals=first_ordinals,
last_ordinals=last_ordinals,
dual_path_scheme=dual_path_scheme,
dual_path_scheme_ordinal=dual_path_scheme_ordinal)
self.last_noninvertible = last_noninvertible
def inverse(self, x1, x2=None):
length = len(self._modules.values())
for i, module in enumerate(reversed(self._modules.values())):
if i < self.last_noninvertible:
pass
elif (i < self.last_ordinals) or (i >= length - self.first_ordinals):
x1, x2 = self.dual_path_scheme_ordinal(module.inverse, x1, x2)
else:
x1, x2 = self.dual_path_scheme(module.inverse, x1, x2)
if self.return_two:
return x1, x2
else:
return x1
class IRevDownscale(nn.Module):
"""
i-RevNet specific downscale (so-called psi-block).
Parameters:
----------
scale : int
Scale (downscale) value.
"""
def __init__(self, scale):
super(IRevDownscale, self).__init__()
self.scale = scale
def forward(self, x):
batch, x_channels, x_height, x_width = x.size()
y_channels = x_channels * self.scale * self.scale
assert (x_height % self.scale == 0)
y_height = x_height // self.scale
y = x.permute(0, 2, 3, 1)
d2_split_seq = y.split(split_size=self.scale, dim=2)
d2_split_seq = [t.contiguous().view(batch, y_height, y_channels) for t in d2_split_seq]
y = torch.stack(d2_split_seq, dim=1)
y = y.permute(0, 3, 2, 1)
return y.contiguous()
def inverse(self, y):
scale_sqr = self.scale * self.scale
batch, y_channels, y_height, y_width = y.size()
assert (y_channels % scale_sqr == 0)
x_channels = y_channels // scale_sqr
x_height = y_height * self.scale
x_width = y_width * self.scale
x = y.permute(0, 2, 3, 1)
x = x.contiguous().view(batch, y_height, y_width, scale_sqr, x_channels)
d3_split_seq = x.split(split_size=self.scale, dim=3)
d3_split_seq = [t.contiguous().view(batch, y_height, x_width, x_channels) for t in d3_split_seq]
x = torch.stack(d3_split_seq, dim=0)
x = x.transpose(0, 1).permute(0, 2, 1, 3, 4).contiguous().view(batch, x_height, x_width, x_channels)
x = x.permute(0, 3, 1, 2)
return x.contiguous()
class IRevInjectivePad(nn.Module):
"""
i-RevNet channel zero padding block.
Parameters:
----------
padding : int
Size of the padding.
"""
def __init__(self, padding):
super(IRevInjectivePad, self).__init__()
self.padding = padding
self.pad = nn.ZeroPad2d(padding=(0, 0, 0, padding))
def forward(self, x):
x = x.permute(0, 2, 1, 3)
x = self.pad(x)
return x.permute(0, 2, 1, 3)
def inverse(self, x):
return x[:, :x.size(1) - self.padding, :, :]
class IRevSplitBlock(nn.Module):
"""
iRevNet split block.
"""
def __init__(self):
super(IRevSplitBlock, self).__init__()
def forward(self, x, _):
x1, x2 = torch.chunk(x, chunks=2, dim=1)
return x1, x2
def inverse(self, x1, x2):
x = torch.cat((x1, x2), dim=1)
return x, None
class IRevMergeBlock(nn.Module):
"""
iRevNet merge block.
"""
def __init__(self):
super(IRevMergeBlock, self).__init__()
def forward(self, x1, x2):
x = torch.cat((x1, x2), dim=1)
return x, x
def inverse(self, x, _):
x1, x2 = torch.chunk(x, chunks=2, dim=1)
return x1, x2
class IRevBottleneck(nn.Module):
"""
iRevNet bottleneck block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the branch convolution layers.
preactivate : bool
Whether use pre-activation for the first convolution block.
"""
def __init__(self,
in_channels,
out_channels,
stride,
preactivate):
super(IRevBottleneck, self).__init__()
mid_channels = out_channels // 4
if preactivate:
self.conv1 = pre_conv3x3_block(
in_channels=in_channels,
out_channels=mid_channels,
stride=stride)
else:
self.conv1 = conv3x3(
in_channels=in_channels,
out_channels=mid_channels,
stride=stride)
self.conv2 = pre_conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels)
self.conv3 = pre_conv3x3_block(
in_channels=mid_channels,
out_channels=out_channels)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class IRevUnit(nn.Module):
"""
iRevNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the branch convolution layers.
preactivate : bool
Whether use pre-activation for the first convolution block.
"""
def __init__(self,
in_channels,
out_channels,
stride,
preactivate):
super(IRevUnit, self).__init__()
if not preactivate:
in_channels = in_channels // 2
padding = 2 * (out_channels - in_channels)
self.do_padding = (padding != 0) and (stride == 1)
self.do_downscale = (stride != 1)
if self.do_padding:
self.pad = IRevInjectivePad(padding)
self.bottleneck = IRevBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
preactivate=preactivate)
if self.do_downscale:
self.psi = IRevDownscale(stride)
def forward(self, x1, x2):
if self.do_padding:
x = torch.cat((x1, x2), dim=1)
x = self.pad(x)
x1, x2 = torch.chunk(x, chunks=2, dim=1)
fx2 = self.bottleneck(x2)
if self.do_downscale:
x1 = self.psi(x1)
x2 = self.psi(x2)
y1 = fx2 + x1
return x2, y1
def inverse(self, x2, y1):
if self.do_downscale:
x2 = self.psi.inverse(x2)
fx2 = - self.bottleneck(x2)
x1 = fx2 + y1
if self.do_downscale:
x1 = self.psi.inverse(x1)
if self.do_padding:
x = torch.cat((x1, x2), dim=1)
x = self.pad.inverse(x)
x1, x2 = torch.chunk(x, chunks=2, dim=1)
return x1, x2
class IRevPostActivation(nn.Module):
"""
iRevNet specific post-activation block.
Parameters:
----------
in_channels : int
Number of input channels.
"""
def __init__(self,
in_channels):
super(IRevPostActivation, self).__init__()
self.bn = nn.BatchNorm2d(
num_features=in_channels,
momentum=0.9)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
x = self.bn(x)
x = self.activ(x)
return x
class IRevNet(nn.Module):
"""
i-RevNet model from 'i-RevNet: Deep Invertible Networks,' https://arxiv.org/abs/1802.07088.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
init_block_channels : int
Number of output channels for the initial unit.
final_block_channels : int
Number of output channels for the final unit.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
final_block_channels,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(IRevNet, self).__init__()
assert (in_channels > 0)
self.in_size = in_size
self.num_classes = num_classes
self.features = IRevDualPathSequential(
first_ordinals=1,
last_ordinals=2,
last_noninvertible=2)
self.features.add_module("init_block", IRevDownscale(scale=2))
in_channels = init_block_channels
self.features.add_module("init_split", IRevSplitBlock())
for i, channels_per_stage in enumerate(channels):
stage = IRevDualPathSequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) else 1
preactivate = not ((i == 0) and (j == 0))
stage.add_module("unit{}".format(j + 1), IRevUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
preactivate=preactivate))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
in_channels = final_block_channels
self.features.add_module("final_merge", IRevMergeBlock())
self.features.add_module("final_postactiv", IRevPostActivation(in_channels=in_channels))
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x, return_out_bij=False):
x, out_bij = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
if return_out_bij:
return x, out_bij
else:
return x
def inverse(self, out_bij):
x, _ = self.features.inverse(out_bij)
return x
def get_irevnet(blocks,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create i-RevNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 301:
layers = [6, 16, 72, 6]
else:
raise ValueError("Unsupported i-RevNet with number of blocks: {}".format(blocks))
assert (sum(layers) * 3 + 1 == blocks)
channels_per_layers = [24, 96, 384, 1536]
init_block_channels = 12
final_block_channels = 3072
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = IRevNet(
channels=channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def irevnet301(**kwargs):
"""
i-RevNet-301 model from 'i-RevNet: Deep Invertible Networks,' https://arxiv.org/abs/1802.07088.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_irevnet(blocks=301, model_name="irevnet301", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
irevnet301,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != irevnet301 or weight_count == 125120356)
x = torch.randn(2, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (2, 1000))
y, out_bij = net(x, return_out_bij=True)
x_ = net.inverse(out_bij)
assert (tuple(x_.size()) == (2, 3, 224, 224))
import numpy as np
assert (np.max(np.abs(x.detach().numpy() - x_.detach().numpy())) < 1e-4)
if __name__ == "__main__":
_test()
| 15,151 | 29.796748 | 115 | py |
null | qimera-main/pytorchcv/models/isqrtcovresnet.py | """
iSQRT-COV-ResNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'Towards Faster Training of Global Covariance Pooling Networks by Iterative Matrix Square Root
Normalization,' https://arxiv.org/abs/1712.01034.
"""
__all__ = ['iSQRTCOVResNet', 'isqrtcovresnet18', 'isqrtcovresnet34', 'isqrtcovresnet50', 'isqrtcovresnet50b',
'isqrtcovresnet101', 'isqrtcovresnet101b']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block
from .resnet import ResUnit, ResInitBlock
class CovPool(torch.autograd.Function):
"""
Covariance pooling function.
"""
@staticmethod
def forward(ctx, x):
batch, channels, height, width = x.size()
n = height * width
xn = x.reshape(batch, channels, n)
identity_bar = ((1.0 / n) * torch.eye(n, dtype=xn.dtype, device=xn.device)).unsqueeze(dim=0).repeat(batch, 1, 1)
ones_bar = torch.full((batch, n, n), fill_value=(-1.0 / n / n), dtype=xn.dtype, device=xn.device)
i_bar = identity_bar + ones_bar
sigma = xn.bmm(i_bar).bmm(xn.transpose(1, 2))
ctx.save_for_backward(x, i_bar)
return sigma
@staticmethod
def backward(ctx, grad_sigma):
x, i_bar = ctx.saved_tensors
batch, channels, height, width = x.size()
n = height * width
xn = x.reshape(batch, channels, n)
grad_x = grad_sigma + grad_sigma.transpose(1, 2)
grad_x = grad_x.bmm(xn).bmm(i_bar)
grad_x = grad_x.reshape(batch, channels, height, width)
return grad_x
class NewtonSchulzSqrt(torch.autograd.Function):
"""
Newton-Schulz iterative matrix square root function.
Parameters:
----------
x : Tensor
Input tensor (batch * cols * rows).
n : int
Number of iterations (n > 1).
"""
@staticmethod
def forward(ctx, x, n):
assert (n > 1)
batch, cols, rows = x.size()
assert (cols == rows)
m = cols
identity = torch.eye(m, dtype=x.dtype, device=x.device).unsqueeze(dim=0).repeat(batch, 1, 1)
x_trace = (x * identity).sum(dim=(1, 2), keepdim=True)
a = x / x_trace
i3 = 3.0 * identity
yi = torch.zeros(batch, n - 1, m, m, dtype=x.dtype, device=x.device)
zi = torch.zeros(batch, n - 1, m, m, dtype=x.dtype, device=x.device)
b2 = 0.5 * (i3 - a)
yi[:, 0, :, :] = a.bmm(b2)
zi[:, 0, :, :] = b2
for i in range(1, n - 1):
b2 = 0.5 * (i3 - zi[:, i - 1, :, :].bmm(yi[:, i - 1, :, :]))
yi[:, i, :, :] = yi[:, i - 1, :, :].bmm(b2)
zi[:, i, :, :] = b2.bmm(zi[:, i - 1, :, :])
b2 = 0.5 * (i3 - zi[:, n - 2, :, :].bmm(yi[:, n - 2, :, :]))
yn = yi[:, n - 2, :, :].bmm(b2)
x_trace_sqrt = torch.sqrt(x_trace)
c = yn * x_trace_sqrt
ctx.save_for_backward(x, x_trace, a, yi, zi, yn, x_trace_sqrt)
ctx.n = n
return c
@staticmethod
def backward(ctx, grad_c):
x, x_trace, a, yi, zi, yn, x_trace_sqrt = ctx.saved_tensors
n = ctx.n
batch, m, _ = x.size()
identity0 = torch.eye(m, dtype=x.dtype, device=x.device)
identity = identity0.unsqueeze(dim=0).repeat(batch, 1, 1)
i3 = 3.0 * identity
grad_yn = grad_c * x_trace_sqrt
b = i3 - yi[:, n - 2, :, :].bmm(zi[:, n - 2, :, :])
grad_yi = 0.5 * (grad_yn.bmm(b) - zi[:, n - 2, :, :].bmm(yi[:, n - 2, :, :]).bmm(grad_yn))
grad_zi = -0.5 * yi[:, n - 2, :, :].bmm(grad_yn).bmm(yi[:, n - 2, :, :])
for i in range(n - 3, -1, -1):
b = i3 - yi[:, i, :, :].bmm(zi[:, i, :, :])
ziyi = zi[:, i, :, :].bmm(yi[:, i, :, :])
grad_yi_m1 = 0.5 * (grad_yi.bmm(b) - zi[:, i, :, :].bmm(grad_zi).bmm(zi[:, i, :, :]) - ziyi.bmm(grad_yi))
grad_zi_m1 = 0.5 * (b.bmm(grad_zi) - yi[:, i, :, :].bmm(grad_yi).bmm(yi[:, i, :, :]) - grad_zi.bmm(ziyi))
grad_yi = grad_yi_m1
grad_zi = grad_zi_m1
grad_a = 0.5 * (grad_yi.bmm(i3 - a) - grad_zi - a.bmm(grad_yi))
x_trace_sqr = x_trace * x_trace
grad_atx_trace = (grad_a.transpose(1, 2).bmm(x) * identity).sum(dim=(1, 2), keepdim=True)
grad_cty_trace = (grad_c.transpose(1, 2).bmm(yn) * identity).sum(dim=(1, 2), keepdim=True)
grad_x_extra = (0.5 * grad_cty_trace / x_trace_sqrt - grad_atx_trace / x_trace_sqr).repeat(1, m, m) * identity
grad_x = grad_a / x_trace + grad_x_extra
return grad_x, None
class Triuvec(torch.autograd.Function):
"""
Extract upper triangular part of matrix into vector form.
"""
@staticmethod
def forward(ctx, x):
batch, cols, rows = x.size()
assert (cols == rows)
n = cols
triuvec_inds = torch.ones(n, n).triu().view(n * n).nonzero()
# assert (len(triuvec_inds) == n * (n + 1) // 2)
x_vec = x.reshape(batch, -1)
y = x_vec[:, triuvec_inds]
ctx.save_for_backward(x, triuvec_inds)
return y
@staticmethod
def backward(ctx, grad_y):
x, triuvec_inds = ctx.saved_tensors
batch, n, _ = x.size()
grad_x = torch.zeros_like(x).view(batch, -1)
grad_x[:, triuvec_inds] = grad_y
grad_x = grad_x.view(batch, n, n)
return grad_x
class iSQRTCOVPool(nn.Module):
"""
iSQRT-COV pooling layer.
Parameters:
----------
num_iter : int, default 5
Number of iterations (num_iter > 1).
"""
def __init__(self,
num_iter=5):
super(iSQRTCOVPool, self).__init__()
self.num_iter = num_iter
self.cov_pool = CovPool.apply
self.sqrt = NewtonSchulzSqrt.apply
self.triuvec = Triuvec.apply
def forward(self, x):
x = self.cov_pool(x)
x = self.sqrt(x, self.num_iter)
x = self.triuvec(x)
return x
class iSQRTCOVResNet(nn.Module):
"""
iSQRT-COV-ResNet model from 'Towards Faster Training of Global Covariance Pooling Networks by Iterative Matrix
Square Root Normalization,' https://arxiv.org/abs/1712.01034.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
final_block_channels : int
Number of output channels for the final unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer in units.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
final_block_channels,
bottleneck,
conv1_stride,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(iSQRTCOVResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i not in [0, len(channels) - 1]) else 1
stage.add_module("unit{}".format(j + 1), ResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck,
conv1_stride=conv1_stride))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_block", conv1x1_block(
in_channels=in_channels,
out_channels=final_block_channels))
in_channels = final_block_channels
self.features.add_module("final_pool", iSQRTCOVPool())
in_features = in_channels * (in_channels + 1) // 2
self.output = nn.Linear(
in_features=in_features,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_isqrtcovresnet(blocks,
conv1_stride=True,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create iSQRT-COV-ResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
conv1_stride : bool, default True
Whether to use stride in the first or the second convolution layer in units.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 18:
layers = [2, 2, 2, 2]
elif blocks == 34:
layers = [3, 4, 6, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
elif blocks == 200:
layers = [3, 24, 36, 3]
else:
raise ValueError("Unsupported iSQRT-COV-ResNet with number of blocks: {}".format(blocks))
init_block_channels = 64
final_block_channels = 256
if blocks < 50:
channels_per_layers = [64, 128, 256, 512]
bottleneck = False
else:
channels_per_layers = [256, 512, 1024, 2048]
bottleneck = True
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = iSQRTCOVResNet(
channels=channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def isqrtcovresnet18(**kwargs):
"""
iSQRT-COV-ResNet-18 model from 'Towards Faster Training of Global Covariance Pooling Networks by Iterative Matrix
Square Root Normalization,' https://arxiv.org/abs/1712.01034.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_isqrtcovresnet(blocks=18, model_name="isqrtcovresnet18", **kwargs)
def isqrtcovresnet34(**kwargs):
"""
iSQRT-COV-ResNet-34 model from 'Towards Faster Training of Global Covariance Pooling Networks by Iterative Matrix
Square Root Normalization,' https://arxiv.org/abs/1712.01034.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_isqrtcovresnet(blocks=34, model_name="isqrtcovresnet34", **kwargs)
def isqrtcovresnet50(**kwargs):
"""
iSQRT-COV-ResNet-50 model from 'Towards Faster Training of Global Covariance Pooling Networks by Iterative Matrix
Square Root Normalization,' https://arxiv.org/abs/1712.01034.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_isqrtcovresnet(blocks=50, model_name="isqrtcovresnet50", **kwargs)
def isqrtcovresnet50b(**kwargs):
"""
iSQRT-COV-ResNet-50 model with stride at the second convolution in bottleneck block from 'Towards Faster Training
of Global Covariance Pooling Networks by Iterative Matrix Square Root Normalization,'
https://arxiv.org/abs/1712.01034.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_isqrtcovresnet(blocks=50, conv1_stride=False, model_name="isqrtcovresnet50b", **kwargs)
def isqrtcovresnet101(**kwargs):
"""
iSQRT-COV-ResNet-101 model from 'Towards Faster Training of Global Covariance Pooling Networks by Iterative Matrix
Square Root Normalization,' https://arxiv.org/abs/1712.01034.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_isqrtcovresnet(blocks=101, model_name="isqrtcovresnet101", **kwargs)
def isqrtcovresnet101b(**kwargs):
"""
iSQRT-COV-ResNet-101 model with stride at the second convolution in bottleneck block from 'Towards Faster Training
of Global Covariance Pooling Networks by Iterative Matrix Square Root Normalization,'
https://arxiv.org/abs/1712.01034.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_isqrtcovresnet(blocks=101, conv1_stride=False, model_name="isqrtcovresnet101b", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
isqrtcovresnet18,
isqrtcovresnet34,
isqrtcovresnet50,
isqrtcovresnet50b,
isqrtcovresnet101,
isqrtcovresnet101b,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != isqrtcovresnet18 or weight_count == 44205096)
assert (model != isqrtcovresnet34 or weight_count == 54313256)
assert (model != isqrtcovresnet50 or weight_count == 56929832)
assert (model != isqrtcovresnet50b or weight_count == 56929832)
assert (model != isqrtcovresnet101 or weight_count == 75921960)
assert (model != isqrtcovresnet101b or weight_count == 75921960)
x = torch.randn(14, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (14, 1000))
if __name__ == "__main__":
_test()
| 15,872 | 33.885714 | 120 | py |
null | qimera-main/pytorchcv/models/menet.py | """
MENet for ImageNet-1K, implemented in PyTorch.
Original paper: 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile Applications,'
https://arxiv.org/abs/1803.09127.
"""
__all__ = ['MENet', 'menet108_8x1_g3', 'menet128_8x1_g4', 'menet160_8x1_g8', 'menet228_12x1_g3', 'menet256_12x1_g4',
'menet348_12x1_g3', 'menet352_12x1_g8', 'menet456_24x1_g3']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1, conv3x3, depthwise_conv3x3, ChannelShuffle
class MEUnit(nn.Module):
"""
MENet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
side_channels : int
Number of side channels.
groups : int
Number of groups in convolution layers.
downsample : bool
Whether do downsample.
ignore_group : bool
Whether ignore group value in the first convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
side_channels,
groups,
downsample,
ignore_group):
super(MEUnit, self).__init__()
self.downsample = downsample
mid_channels = out_channels // 4
if downsample:
out_channels -= in_channels
# residual branch
self.compress_conv1 = conv1x1(
in_channels=in_channels,
out_channels=mid_channels,
groups=(1 if ignore_group else groups))
self.compress_bn1 = nn.BatchNorm2d(num_features=mid_channels)
self.c_shuffle = ChannelShuffle(
channels=mid_channels,
groups=groups)
self.dw_conv2 = depthwise_conv3x3(
channels=mid_channels,
stride=(2 if self.downsample else 1))
self.dw_bn2 = nn.BatchNorm2d(num_features=mid_channels)
self.expand_conv3 = conv1x1(
in_channels=mid_channels,
out_channels=out_channels,
groups=groups)
self.expand_bn3 = nn.BatchNorm2d(num_features=out_channels)
if downsample:
self.avgpool = nn.AvgPool2d(kernel_size=3, stride=2, padding=1)
self.activ = nn.ReLU(inplace=True)
# fusion branch
self.s_merge_conv = conv1x1(
in_channels=mid_channels,
out_channels=side_channels)
self.s_merge_bn = nn.BatchNorm2d(num_features=side_channels)
self.s_conv = conv3x3(
in_channels=side_channels,
out_channels=side_channels,
stride=(2 if self.downsample else 1))
self.s_conv_bn = nn.BatchNorm2d(num_features=side_channels)
self.s_evolve_conv = conv1x1(
in_channels=side_channels,
out_channels=mid_channels)
self.s_evolve_bn = nn.BatchNorm2d(num_features=mid_channels)
def forward(self, x):
identity = x
# pointwise group convolution 1
x = self.compress_conv1(x)
x = self.compress_bn1(x)
x = self.activ(x)
x = self.c_shuffle(x)
# merging
y = self.s_merge_conv(x)
y = self.s_merge_bn(y)
y = self.activ(y)
# depthwise convolution (bottleneck)
x = self.dw_conv2(x)
x = self.dw_bn2(x)
# evolution
y = self.s_conv(y)
y = self.s_conv_bn(y)
y = self.activ(y)
y = self.s_evolve_conv(y)
y = self.s_evolve_bn(y)
y = torch.sigmoid(y)
x = x * y
# pointwise group convolution 2
x = self.expand_conv3(x)
x = self.expand_bn3(x)
# identity branch
if self.downsample:
identity = self.avgpool(identity)
x = torch.cat((x, identity), dim=1)
else:
x = x + identity
x = self.activ(x)
return x
class MEInitBlock(nn.Module):
"""
MENet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(MEInitBlock, self).__init__()
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=2,
padding=1,
bias=False)
self.bn = nn.BatchNorm2d(num_features=out_channels)
self.activ = nn.ReLU(inplace=True)
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=1)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
x = self.activ(x)
x = self.pool(x)
return x
class MENet(nn.Module):
"""
MENet model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile Applications,'
https://arxiv.org/abs/1803.09127.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
side_channels : int
Number of side channels in a ME-unit.
groups : int
Number of groups in convolution layers.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
side_channels,
groups,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(MENet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", MEInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
downsample = (j == 0)
ignore_group = (i == 0) and (j == 0)
stage.add_module("unit{}".format(j + 1), MEUnit(
in_channels=in_channels,
out_channels=out_channels,
side_channels=side_channels,
groups=groups,
downsample=downsample,
ignore_group=ignore_group))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_menet(first_stage_channels,
side_channels,
groups,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create MENet model with specific parameters.
Parameters:
----------
first_stage_channels : int
Number of output channels at the first stage.
side_channels : int
Number of side channels in a ME-unit.
groups : int
Number of groups in convolution layers.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
layers = [4, 8, 4]
if first_stage_channels == 108:
init_block_channels = 12
channels_per_layers = [108, 216, 432]
elif first_stage_channels == 128:
init_block_channels = 12
channels_per_layers = [128, 256, 512]
elif first_stage_channels == 160:
init_block_channels = 16
channels_per_layers = [160, 320, 640]
elif first_stage_channels == 228:
init_block_channels = 24
channels_per_layers = [228, 456, 912]
elif first_stage_channels == 256:
init_block_channels = 24
channels_per_layers = [256, 512, 1024]
elif first_stage_channels == 348:
init_block_channels = 24
channels_per_layers = [348, 696, 1392]
elif first_stage_channels == 352:
init_block_channels = 24
channels_per_layers = [352, 704, 1408]
elif first_stage_channels == 456:
init_block_channels = 48
channels_per_layers = [456, 912, 1824]
else:
raise ValueError("The {} of `first_stage_channels` is not supported".format(first_stage_channels))
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = MENet(
channels=channels,
init_block_channels=init_block_channels,
side_channels=side_channels,
groups=groups,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def menet108_8x1_g3(**kwargs):
"""
108-MENet-8x1 (g=3) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile
Applications,' https://arxiv.org/abs/1803.09127.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_menet(first_stage_channels=108, side_channels=8, groups=3, model_name="menet108_8x1_g3", **kwargs)
def menet128_8x1_g4(**kwargs):
"""
128-MENet-8x1 (g=4) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile
Applications,' https://arxiv.org/abs/1803.09127.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_menet(first_stage_channels=128, side_channels=8, groups=4, model_name="menet128_8x1_g4", **kwargs)
def menet160_8x1_g8(**kwargs):
"""
160-MENet-8x1 (g=8) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile
Applications,' https://arxiv.org/abs/1803.09127.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_menet(first_stage_channels=160, side_channels=8, groups=8, model_name="menet160_8x1_g8", **kwargs)
def menet228_12x1_g3(**kwargs):
"""
228-MENet-12x1 (g=3) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile
Applications,' https://arxiv.org/abs/1803.09127.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_menet(first_stage_channels=228, side_channels=12, groups=3, model_name="menet228_12x1_g3", **kwargs)
def menet256_12x1_g4(**kwargs):
"""
256-MENet-12x1 (g=4) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile
Applications,' https://arxiv.org/abs/1803.09127.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_menet(first_stage_channels=256, side_channels=12, groups=4, model_name="menet256_12x1_g4", **kwargs)
def menet348_12x1_g3(**kwargs):
"""
348-MENet-12x1 (g=3) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile
Applications,' https://arxiv.org/abs/1803.09127.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_menet(first_stage_channels=348, side_channels=12, groups=3, model_name="menet348_12x1_g3", **kwargs)
def menet352_12x1_g8(**kwargs):
"""
352-MENet-12x1 (g=8) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile
Applications,' https://arxiv.org/abs/1803.09127.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_menet(first_stage_channels=352, side_channels=12, groups=8, model_name="menet352_12x1_g8", **kwargs)
def menet456_24x1_g3(**kwargs):
"""
456-MENet-24x1 (g=3) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile
Applications,' https://arxiv.org/abs/1803.09127.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_menet(first_stage_channels=456, side_channels=24, groups=3, model_name="menet456_24x1_g3", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
menet108_8x1_g3,
menet128_8x1_g4,
menet160_8x1_g8,
menet228_12x1_g3,
menet256_12x1_g4,
menet348_12x1_g3,
menet352_12x1_g8,
menet456_24x1_g3,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != menet108_8x1_g3 or weight_count == 654516)
assert (model != menet128_8x1_g4 or weight_count == 750796)
assert (model != menet160_8x1_g8 or weight_count == 850120)
assert (model != menet228_12x1_g3 or weight_count == 1806568)
assert (model != menet256_12x1_g4 or weight_count == 1888240)
assert (model != menet348_12x1_g3 or weight_count == 3368128)
assert (model != menet352_12x1_g8 or weight_count == 2272872)
assert (model != menet456_24x1_g3 or weight_count == 5304784)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 15,917 | 31.956522 | 116 | py |
null | qimera-main/pytorchcv/models/mixnet.py | """
MixNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'MixConv: Mixed Depthwise Convolutional Kernels,' https://arxiv.org/abs/1907.09595.
"""
__all__ = ['MixNet', 'mixnet_s', 'mixnet_m', 'mixnet_l']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import round_channels, get_activation_layer, conv1x1_block, conv3x3_block, dwconv3x3_block, SEBlock
class MixConv(nn.Module):
"""
Mixed convolution layer from 'MixConv: Mixed Depthwise Convolutional Kernels,' https://arxiv.org/abs/1907.09595.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of int, or tuple/list of tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of int, or tuple/list of tuple/list of 2 int
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
bias : bool, default False
Whether the layer uses a bias vector.
axis : int, default 1
The axis on which to concatenate the outputs.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
dilation=1,
groups=1,
bias=False,
axis=1):
super(MixConv, self).__init__()
kernel_size = kernel_size if isinstance(kernel_size, list) else [kernel_size]
padding = padding if isinstance(padding, list) else [padding]
kernel_count = len(kernel_size)
self.splitted_in_channels = self.split_channels(in_channels, kernel_count)
splitted_out_channels = self.split_channels(out_channels, kernel_count)
for i, kernel_size_i in enumerate(kernel_size):
in_channels_i = self.splitted_in_channels[i]
out_channels_i = splitted_out_channels[i]
padding_i = padding[i]
self.add_module(
name=str(i),
module=nn.Conv2d(
in_channels=in_channels_i,
out_channels=out_channels_i,
kernel_size=kernel_size_i,
stride=stride,
padding=padding_i,
dilation=dilation,
groups=(out_channels_i if out_channels == groups else groups),
bias=bias))
self.axis = axis
def forward(self, x):
xx = torch.split(x, self.splitted_in_channels, dim=self.axis)
out = [conv_i(x_i) for x_i, conv_i in zip(xx, self._modules.values())]
x = torch.cat(tuple(out), dim=self.axis)
return x
@staticmethod
def split_channels(channels, kernel_count):
splitted_channels = [channels // kernel_count] * kernel_count
splitted_channels[0] += channels - sum(splitted_channels)
return splitted_channels
class MixConvBlock(nn.Module):
"""
Mixed convolution block with Batch normalization and activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of int, or tuple/list of tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of int, or tuple/list of tuple/list of 2 int
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
bias : bool, default False
Whether the layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layer.
bn_eps : float, default 1e-5
Small float added to variance in Batch norm.
activation : function or str or None, default nn.ReLU(inplace=True)
Activation function or name of activation function.
activate : bool, default True
Whether activate the convolution block.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
dilation=1,
groups=1,
bias=False,
use_bn=True,
bn_eps=1e-5,
activation=(lambda: nn.ReLU(inplace=True))):
super(MixConvBlock, self).__init__()
self.activate = (activation is not None)
self.use_bn = use_bn
self.conv = MixConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
groups=groups,
bias=bias)
if self.use_bn:
self.bn = nn.BatchNorm2d(
num_features=out_channels,
eps=bn_eps)
if self.activate:
self.activ = get_activation_layer(activation)
def forward(self, x):
x = self.conv(x)
if self.use_bn:
x = self.bn(x)
if self.activate:
x = self.activ(x)
return x
def mixconv1x1_block(in_channels,
out_channels,
kernel_count,
stride=1,
groups=1,
bias=False,
use_bn=True,
bn_eps=1e-5,
activation=(lambda: nn.ReLU(inplace=True))):
"""
1x1 version of the mixed convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_count : int
Kernel count.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
groups : int, default 1
Number of groups.
bias : bool, default False
Whether the layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layer.
bn_eps : float, default 1e-5
Small float added to variance in Batch norm.
activation : function or str, or None, default nn.ReLU(inplace=True)
Activation function or name of activation function.
"""
return MixConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=([1] * kernel_count),
stride=stride,
padding=([0] * kernel_count),
groups=groups,
bias=bias,
use_bn=use_bn,
bn_eps=bn_eps,
activation=activation)
class MixUnit(nn.Module):
"""
MixNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
exp_channels : int
Number of middle (expanded) channels.
stride : int or tuple/list of 2 int
Strides of the second convolution layer.
exp_kernel_count : int
Expansion convolution kernel count for each unit.
conv1_kernel_count : int
Conv1 kernel count for each unit.
conv2_kernel_count : int
Conv2 kernel count for each unit.
exp_factor : int
Expansion factor for each unit.
se_factor : int
SE reduction factor for each unit.
activation : str
Activation function or name of activation function.
"""
def __init__(self,
in_channels,
out_channels,
stride,
exp_kernel_count,
conv1_kernel_count,
conv2_kernel_count,
exp_factor,
se_factor,
activation):
super(MixUnit, self).__init__()
assert (exp_factor >= 1)
assert (se_factor >= 0)
self.residual = (in_channels == out_channels) and (stride == 1)
self.use_se = se_factor > 0
mid_channels = exp_factor * in_channels
self.use_exp_conv = exp_factor > 1
if self.use_exp_conv:
if exp_kernel_count == 1:
self.exp_conv = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
activation=activation)
else:
self.exp_conv = mixconv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
kernel_count=exp_kernel_count,
activation=activation)
if conv1_kernel_count == 1:
self.conv1 = dwconv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride,
activation=activation)
else:
self.conv1 = MixConvBlock(
in_channels=mid_channels,
out_channels=mid_channels,
kernel_size=[3 + 2 * i for i in range(conv1_kernel_count)],
stride=stride,
padding=[1 + i for i in range(conv1_kernel_count)],
groups=mid_channels,
activation=activation)
if self.use_se:
self.se = SEBlock(
channels=mid_channels,
reduction=(exp_factor * se_factor),
approx_sigmoid=False,
round_mid=False,
activation=activation)
if conv2_kernel_count == 1:
self.conv2 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
activation=None)
else:
self.conv2 = mixconv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
kernel_count=conv2_kernel_count,
activation=None)
def forward(self, x):
if self.residual:
identity = x
if self.use_exp_conv:
x = self.exp_conv(x)
x = self.conv1(x)
if self.use_se:
x = self.se(x)
x = self.conv2(x)
if self.residual:
x = x + identity
return x
class MixInitBlock(nn.Module):
"""
MixNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(MixInitBlock, self).__init__()
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
stride=2)
self.conv2 = MixUnit(
in_channels=out_channels,
out_channels=out_channels,
stride=1,
exp_kernel_count=1,
conv1_kernel_count=1,
conv2_kernel_count=1,
exp_factor=1,
se_factor=0,
activation="relu")
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class MixNet(nn.Module):
"""
MixNet model from 'MixConv: Mixed Depthwise Convolutional Kernels,' https://arxiv.org/abs/1907.09595.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
final_block_channels : int
Number of output channels for the final block of the feature extractor.
exp_kernel_counts : list of list of int
Expansion convolution kernel count for each unit.
conv1_kernel_counts : list of list of int
Conv1 kernel count for each unit.
conv2_kernel_counts : list of list of int
Conv2 kernel count for each unit.
exp_factors : list of list of int
Expansion factor for each unit.
se_factors : list of list of int
SE reduction factor for each unit.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
final_block_channels,
exp_kernel_counts,
conv1_kernel_counts,
conv2_kernel_counts,
exp_factors,
se_factors,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(MixNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", MixInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if ((j == 0) and (i != 3)) or ((j == len(channels_per_stage) // 2) and (i == 3)) else 1
exp_kernel_count = exp_kernel_counts[i][j]
conv1_kernel_count = conv1_kernel_counts[i][j]
conv2_kernel_count = conv2_kernel_counts[i][j]
exp_factor = exp_factors[i][j]
se_factor = se_factors[i][j]
activation = "relu" if i == 0 else "swish"
stage.add_module("unit{}".format(j + 1), MixUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
exp_kernel_count=exp_kernel_count,
conv1_kernel_count=conv1_kernel_count,
conv2_kernel_count=conv2_kernel_count,
exp_factor=exp_factor,
se_factor=se_factor,
activation=activation))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_block', conv1x1_block(
in_channels=in_channels,
out_channels=final_block_channels))
in_channels = final_block_channels
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_mixnet(version,
width_scale,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create MixNet model with specific parameters.
Parameters:
----------
version : str
Version of MobileNetV3 ('s' or 'm').
width_scale : float
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if version == "s":
init_block_channels = 16
channels = [[24, 24], [40, 40, 40, 40], [80, 80, 80], [120, 120, 120, 200, 200, 200]]
exp_kernel_counts = [[2, 2], [1, 2, 2, 2], [1, 1, 1], [2, 2, 2, 1, 1, 1]]
conv1_kernel_counts = [[1, 1], [3, 2, 2, 2], [3, 2, 2], [3, 4, 4, 5, 4, 4]]
conv2_kernel_counts = [[2, 2], [1, 2, 2, 2], [2, 2, 2], [2, 2, 2, 1, 2, 2]]
exp_factors = [[6, 3], [6, 6, 6, 6], [6, 6, 6], [6, 3, 3, 6, 6, 6]]
se_factors = [[0, 0], [2, 2, 2, 2], [4, 4, 4], [2, 2, 2, 2, 2, 2]]
elif version == "m":
init_block_channels = 24
channels = [[32, 32], [40, 40, 40, 40], [80, 80, 80, 80], [120, 120, 120, 120, 200, 200, 200, 200]]
exp_kernel_counts = [[2, 2], [1, 2, 2, 2], [1, 2, 2, 2], [1, 2, 2, 2, 1, 1, 1, 1]]
conv1_kernel_counts = [[3, 1], [4, 2, 2, 2], [3, 4, 4, 4], [1, 4, 4, 4, 4, 4, 4, 4]]
conv2_kernel_counts = [[2, 2], [1, 2, 2, 2], [1, 2, 2, 2], [1, 2, 2, 2, 1, 2, 2, 2]]
exp_factors = [[6, 3], [6, 6, 6, 6], [6, 6, 6, 6], [6, 3, 3, 3, 6, 6, 6, 6]]
se_factors = [[0, 0], [2, 2, 2, 2], [4, 4, 4, 4], [2, 2, 2, 2, 2, 2, 2, 2]]
else:
raise ValueError("Unsupported MixNet version {}".format(version))
final_block_channels = 1536
if width_scale != 1.0:
channels = [[round_channels(cij * width_scale) for cij in ci] for ci in channels]
init_block_channels = round_channels(init_block_channels * width_scale)
net = MixNet(
channels=channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
exp_kernel_counts=exp_kernel_counts,
conv1_kernel_counts=conv1_kernel_counts,
conv2_kernel_counts=conv2_kernel_counts,
exp_factors=exp_factors,
se_factors=se_factors,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def mixnet_s(**kwargs):
"""
MixNet-S model from 'MixConv: Mixed Depthwise Convolutional Kernels,' https://arxiv.org/abs/1907.09595.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mixnet(version="s", width_scale=1.0, model_name="mixnet_s", **kwargs)
def mixnet_m(**kwargs):
"""
MixNet-M model from 'MixConv: Mixed Depthwise Convolutional Kernels,' https://arxiv.org/abs/1907.09595.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mixnet(version="m", width_scale=1.0, model_name="mixnet_m", **kwargs)
def mixnet_l(**kwargs):
"""
MixNet-L model from 'MixConv: Mixed Depthwise Convolutional Kernels,' https://arxiv.org/abs/1907.09595.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mixnet(version="m", width_scale=1.3, model_name="mixnet_l", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
mixnet_s,
mixnet_m,
mixnet_l,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != mixnet_s or weight_count == 4134606)
assert (model != mixnet_m or weight_count == 5014382)
assert (model != mixnet_l or weight_count == 7329252)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 20,562 | 33.386288 | 116 | py |
null | qimera-main/pytorchcv/models/mnasnet.py | """
MnasNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'MnasNet: Platform-Aware Neural Architecture Search for Mobile,' https://arxiv.org/abs/1807.11626.
"""
__all__ = ['MnasNet', 'mnasnet']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, conv3x3_block, dwconv3x3_block, dwconv5x5_block
class DwsConvBlock(nn.Module):
"""
Depthwise separable convolution block with BatchNorms and activations at each convolution layers.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(DwsConvBlock, self).__init__()
self.dw_conv = dwconv3x3_block(
in_channels=in_channels,
out_channels=in_channels)
self.pw_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels)
def forward(self, x):
x = self.dw_conv(x)
x = self.pw_conv(x)
return x
class MnasUnit(nn.Module):
"""
MnasNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the second convolution layer.
expansion_factor : int
Factor for expansion of channels.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
expansion_factor):
super(MnasUnit, self).__init__()
self.residual = (in_channels == out_channels) and (stride == 1)
mid_channels = in_channels * expansion_factor
dwconv_block_fn = dwconv3x3_block if kernel_size == 3 else (dwconv5x5_block if kernel_size == 5 else None)
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels)
self.conv2 = dwconv_block_fn(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride)
self.conv3 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
activation=None)
def forward(self, x):
if self.residual:
identity = x
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
if self.residual:
x = x + identity
return x
class MnasInitBlock(nn.Module):
"""
MnasNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels_list : list of 2 int
Numbers of output channels.
"""
def __init__(self,
in_channels,
out_channels_list):
super(MnasInitBlock, self).__init__()
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels_list[0],
stride=2)
self.conv2 = DwsConvBlock(
in_channels=out_channels_list[0],
out_channels=out_channels_list[1])
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class MnasNet(nn.Module):
"""
MnasNet model from 'MnasNet: Platform-Aware Neural Architecture Search for Mobile,'
https://arxiv.org/abs/1807.11626.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : list of 2 int
Numbers of output channels for the initial unit.
final_block_channels : int
Number of output channels for the final block of the feature extractor.
kernel_sizes : list of list of int
Number of kernel sizes for each unit.
expansion_factors : list of list of int
Number of expansion factors for each unit.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
final_block_channels,
kernel_sizes,
expansion_factors,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(MnasNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", MnasInitBlock(
in_channels=in_channels,
out_channels_list=init_block_channels))
in_channels = init_block_channels[-1]
for i, channels_per_stage in enumerate(channels):
kernel_sizes_per_stage = kernel_sizes[i]
expansion_factors_per_stage = expansion_factors[i]
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
kernel_size = kernel_sizes_per_stage[j]
expansion_factor = expansion_factors_per_stage[j]
stride = 2 if (j == 0) else 1
stage.add_module("unit{}".format(j + 1), MnasUnit(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
expansion_factor=expansion_factor))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_block', conv1x1_block(
in_channels=in_channels,
out_channels=final_block_channels))
in_channels = final_block_channels
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_mnasnet(model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create MnasNet model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
init_block_channels = [32, 16]
final_block_channels = 1280
layers = [3, 3, 3, 2, 4, 1]
downsample = [1, 1, 1, 0, 1, 0]
channels_per_layers = [24, 40, 80, 96, 192, 320]
expansion_factors_per_layers = [3, 3, 6, 6, 6, 6]
kernel_sizes_per_layers = [3, 5, 5, 3, 5, 3]
default_kernel_size = 3
from functools import reduce
channels = reduce(lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]],
zip(channels_per_layers, layers, downsample), [])
kernel_sizes = reduce(lambda x, y: x + [[y[0]] + [default_kernel_size] * (y[1] - 1)] if y[2] != 0 else x[:-1] + [
x[-1] + [y[0]] + [default_kernel_size] * (y[1] - 1)], zip(kernel_sizes_per_layers, layers, downsample), [])
expansion_factors = reduce(lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]],
zip(expansion_factors_per_layers, layers, downsample), [])
net = MnasNet(
channels=channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
kernel_sizes=kernel_sizes,
expansion_factors=expansion_factors,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def mnasnet(**kwargs):
"""
MnasNet model from 'MnasNet: Platform-Aware Neural Architecture Search for Mobile,'
https://arxiv.org/abs/1807.11626.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mnasnet(model_name="mnasnet", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
mnasnet,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != mnasnet or weight_count == 4308816)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 10,012 | 30.990415 | 118 | py |
null | qimera-main/pytorchcv/models/mobilenet.py | """
MobileNet & FD-MobileNet for ImageNet-1K, implemented in PyTorch.
Original papers:
- 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,'
https://arxiv.org/abs/1704.04861.
- 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,' https://arxiv.org/abs/1802.03750.
"""
__all__ = ['MobileNet', 'mobilenet_w1', 'mobilenet_w3d4', 'mobilenet_wd2', 'mobilenet_wd4', 'fdmobilenet_w1',
'fdmobilenet_w3d4', 'fdmobilenet_wd2', 'fdmobilenet_wd4']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, conv3x3_block, dwconv3x3_block
class DwsConvBlock(nn.Module):
"""
Depthwise separable convolution block with BatchNorms and activations at each convolution layers. It is used as
a MobileNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
"""
def __init__(self,
in_channels,
out_channels,
stride):
super(DwsConvBlock, self).__init__()
self.dw_conv = dwconv3x3_block(
in_channels=in_channels,
out_channels=in_channels,
stride=stride)
self.pw_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels)
def forward(self, x):
x = self.dw_conv(x)
x = self.pw_conv(x)
return x
class MobileNet(nn.Module):
"""
MobileNet model from 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,'
https://arxiv.org/abs/1704.04861. Also this class implements FD-MobileNet from 'FD-MobileNet: Improved MobileNet
with A Fast Downsampling Strategy,' https://arxiv.org/abs/1802.03750.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
first_stage_stride : bool
Whether stride is used at the first stage.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
first_stage_stride,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(MobileNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
init_block_channels = channels[0][0]
self.features.add_module("init_block", conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels,
stride=2))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels[1:]):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and ((i != 0) or first_stage_stride) else 1
stage.add_module("unit{}".format(j + 1), DwsConvBlock(
in_channels=in_channels,
out_channels=out_channels,
stride=stride))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if 'dw_conv.conv' in name:
init.kaiming_normal_(module.weight, mode='fan_in')
elif name == 'init_block.conv' or 'pw_conv.conv' in name:
init.kaiming_normal_(module.weight, mode='fan_out')
elif 'bn' in name:
init.constant_(module.weight, 1)
init.constant_(module.bias, 0)
elif 'output' in name:
init.kaiming_normal_(module.weight, mode='fan_out')
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_mobilenet(version,
width_scale,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create MobileNet or FD-MobileNet model with specific parameters.
Parameters:
----------
version : str
Version of SqueezeNet ('orig' or 'fd').
width_scale : float
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if version == 'orig':
channels = [[32], [64], [128, 128], [256, 256], [512, 512, 512, 512, 512, 512], [1024, 1024]]
first_stage_stride = False
elif version == 'fd':
channels = [[32], [64], [128, 128], [256, 256], [512, 512, 512, 512, 512, 1024]]
first_stage_stride = True
else:
raise ValueError("Unsupported MobileNet version {}".format(version))
if width_scale != 1.0:
channels = [[int(cij * width_scale) for cij in ci] for ci in channels]
net = MobileNet(
channels=channels,
first_stage_stride=first_stage_stride,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def mobilenet_w1(**kwargs):
"""
1.0 MobileNet-224 model from 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,'
https://arxiv.org/abs/1704.04861.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenet(version="orig", width_scale=1.0, model_name="mobilenet_w1", **kwargs)
def mobilenet_w3d4(**kwargs):
"""
0.75 MobileNet-224 model from 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,'
https://arxiv.org/abs/1704.04861.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenet(version="orig", width_scale=0.75, model_name="mobilenet_w3d4", **kwargs)
def mobilenet_wd2(**kwargs):
"""
0.5 MobileNet-224 model from 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,'
https://arxiv.org/abs/1704.04861.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenet(version="orig", width_scale=0.5, model_name="mobilenet_wd2", **kwargs)
def mobilenet_wd4(**kwargs):
"""
0.25 MobileNet-224 model from 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,'
https://arxiv.org/abs/1704.04861.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenet(version="orig", width_scale=0.25, model_name="mobilenet_wd4", **kwargs)
def fdmobilenet_w1(**kwargs):
"""
FD-MobileNet 1.0x model from 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'
https://arxiv.org/abs/1802.03750.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenet(version="fd", width_scale=1.0, model_name="fdmobilenet_w1", **kwargs)
def fdmobilenet_w3d4(**kwargs):
"""
FD-MobileNet 0.75x model from 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'
https://arxiv.org/abs/1802.03750.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenet(version="fd", width_scale=0.75, model_name="fdmobilenet_w3d4", **kwargs)
def fdmobilenet_wd2(**kwargs):
"""
FD-MobileNet 0.5x model from 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'
https://arxiv.org/abs/1802.03750.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenet(version="fd", width_scale=0.5, model_name="fdmobilenet_wd2", **kwargs)
def fdmobilenet_wd4(**kwargs):
"""
FD-MobileNet 0.25x model from 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'
https://arxiv.org/abs/1802.03750.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenet(version="fd", width_scale=0.25, model_name="fdmobilenet_wd4", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
mobilenet_w1,
mobilenet_w3d4,
mobilenet_wd2,
mobilenet_wd4,
fdmobilenet_w1,
fdmobilenet_w3d4,
fdmobilenet_wd2,
fdmobilenet_wd4,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != mobilenet_w1 or weight_count == 4231976)
assert (model != mobilenet_w3d4 or weight_count == 2585560)
assert (model != mobilenet_wd2 or weight_count == 1331592)
assert (model != mobilenet_wd4 or weight_count == 470072)
assert (model != fdmobilenet_w1 or weight_count == 2901288)
assert (model != fdmobilenet_w3d4 or weight_count == 1833304)
assert (model != fdmobilenet_wd2 or weight_count == 993928)
assert (model != fdmobilenet_wd4 or weight_count == 383160)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 11,801 | 32.816619 | 119 | py |
null | qimera-main/pytorchcv/models/mobilenet_cub.py | """
MobileNet & FD-MobileNet for CUB-200-2011, implemented in torch.
Original papers:
- 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,'
https://arxiv.org/abs/1704.04861.
- 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,' https://arxiv.org/abs/1802.03750.
"""
__all__ = ['mobilenet_w1_cub', 'mobilenet_w3d4_cub', 'mobilenet_wd2_cub', 'mobilenet_wd4_cub', 'fdmobilenet_w1_cub',
'fdmobilenet_w3d4_cub', 'fdmobilenet_wd2_cub', 'fdmobilenet_wd4_cub']
from .mobilenet import get_mobilenet
def mobilenet_w1_cub(num_classes=200, **kwargs):
"""
1.0 MobileNet-224 model for CUB-200-2011 from 'MobileNets: Efficient Convolutional Neural Networks for Mobile
Vision Applications,' https://arxiv.org/abs/1704.04861.
Parameters:
----------
num_classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenet(num_classes=num_classes, version="orig", width_scale=1.0, model_name="mobilenet_w1_cub",
**kwargs)
def mobilenet_w3d4_cub(num_classes=200, **kwargs):
"""
0.75 MobileNet-224 model for CUB-200-2011 from 'MobileNets: Efficient Convolutional Neural Networks for Mobile
Vision Applications,' https://arxiv.org/abs/1704.04861.
Parameters:
----------
num_classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenet(num_classes=num_classes, version="orig", width_scale=0.75, model_name="mobilenet_w3d4_cub",
**kwargs)
def mobilenet_wd2_cub(num_classes=200, **kwargs):
"""
0.5 MobileNet-224 model for CUB-200-2011 from 'MobileNets: Efficient Convolutional Neural Networks for Mobile
Vision Applications,' https://arxiv.org/abs/1704.04861.
Parameters:
----------
num_classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenet(num_classes=num_classes, version="orig", width_scale=0.5, model_name="mobilenet_wd2_cub",
**kwargs)
def mobilenet_wd4_cub(num_classes=200, **kwargs):
"""
0.25 MobileNet-224 model for CUB-200-2011 from 'MobileNets: Efficient Convolutional Neural Networks for Mobile
Vision Applications,' https://arxiv.org/abs/1704.04861.
Parameters:
----------
num_classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenet(num_classes=num_classes, version="orig", width_scale=0.25, model_name="mobilenet_wd4_cub",
**kwargs)
def fdmobilenet_w1_cub(num_classes=200, **kwargs):
"""
FD-MobileNet 1.0x model for CUB-200-2011 from 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'
https://arxiv.org/abs/1802.03750.
Parameters:
----------
num_classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenet(num_classes=num_classes, version="fd", width_scale=1.0, model_name="fdmobilenet_w1_cub",
**kwargs)
def fdmobilenet_w3d4_cub(num_classes=200, **kwargs):
"""
FD-MobileNet 0.75x model for CUB-200-2011 from 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'
https://arxiv.org/abs/1802.03750.
Parameters:
----------
num_classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenet(num_classes=num_classes, version="fd", width_scale=0.75, model_name="fdmobilenet_w3d4_cub",
**kwargs)
def fdmobilenet_wd2_cub(num_classes=200, **kwargs):
"""
FD-MobileNet 0.5x model for CUB-200-2011 from 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'
https://arxiv.org/abs/1802.03750.
Parameters:
----------
num_classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenet(num_classes=num_classes, version="fd", width_scale=0.5, model_name="fdmobilenet_wd2_cub",
**kwargs)
def fdmobilenet_wd4_cub(num_classes=200, **kwargs):
"""
FD-MobileNet 0.25x model for CUB-200-2011 from 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'
https://arxiv.org/abs/1802.03750.
Parameters:
----------
num_classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenet(num_classes=num_classes, version="fd", width_scale=0.25, model_name="fdmobilenet_wd4_cub",
**kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
mobilenet_w1_cub,
mobilenet_w3d4_cub,
mobilenet_wd2_cub,
mobilenet_wd4_cub,
fdmobilenet_w1_cub,
fdmobilenet_w3d4_cub,
fdmobilenet_wd2_cub,
fdmobilenet_wd4_cub,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != mobilenet_w1_cub or weight_count == 3411976)
assert (model != mobilenet_w3d4_cub or weight_count == 1970360)
assert (model != mobilenet_wd2_cub or weight_count == 921192)
assert (model != mobilenet_wd4_cub or weight_count == 264472)
assert (model != fdmobilenet_w1_cub or weight_count == 2081288)
assert (model != fdmobilenet_w3d4_cub or weight_count == 1218104)
assert (model != fdmobilenet_wd2_cub or weight_count == 583528)
assert (model != fdmobilenet_wd4_cub or weight_count == 177560)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 200))
if __name__ == "__main__":
_test()
| 7,540 | 35.08134 | 120 | py |
null | qimera-main/pytorchcv/models/mobilenetv2.py | """
MobileNetV2 for ImageNet-1K, implemented in PyTorch.
Original paper: 'MobileNetV2: Inverted Residuals and Linear Bottlenecks,' https://arxiv.org/abs/1801.04381.
"""
__all__ = ['MobileNetV2', 'mobilenetv2_w1', 'mobilenetv2_w3d4', 'mobilenetv2_wd2', 'mobilenetv2_wd4']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1, conv1x1_block, conv3x3_block, dwconv3x3_block
class LinearBottleneck(nn.Module):
"""
So-called 'Linear Bottleneck' layer. It is used as a MobileNetV2 unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the second convolution layer.
expansion : bool
Whether do expansion of channels.
"""
def __init__(self,
in_channels,
out_channels,
stride,
expansion):
super(LinearBottleneck, self).__init__()
self.residual = (in_channels == out_channels) and (stride == 1)
mid_channels = in_channels * 6 if expansion else in_channels
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
activation="relu6")
self.conv2 = dwconv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride,
activation="relu6")
self.conv3 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
activation=None)
def forward(self, x):
if self.residual:
identity = x
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
if self.residual:
x = x + identity
return x
class MobileNetV2(nn.Module):
"""
MobileNetV2 model from 'MobileNetV2: Inverted Residuals and Linear Bottlenecks,' https://arxiv.org/abs/1801.04381.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
final_block_channels : int
Number of output channels for the final block of the feature extractor.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
final_block_channels,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(MobileNetV2, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels,
stride=2,
activation="relu6"))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
expansion = (i != 0) or (j != 0)
stage.add_module("unit{}".format(j + 1), LinearBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
expansion=expansion))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_block', conv1x1_block(
in_channels=in_channels,
out_channels=final_block_channels,
activation="relu6"))
in_channels = final_block_channels
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = conv1x1(
in_channels=in_channels,
out_channels=num_classes,
bias=False)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = self.output(x)
x = x.view(x.size(0), -1)
return x
def get_mobilenetv2(width_scale,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create MobileNetV2 model with specific parameters.
Parameters:
----------
width_scale : float
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
init_block_channels = 32
final_block_channels = 1280
layers = [1, 2, 3, 4, 3, 3, 1]
downsample = [0, 1, 1, 1, 0, 1, 0]
channels_per_layers = [16, 24, 32, 64, 96, 160, 320]
from functools import reduce
channels = reduce(
lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]],
zip(channels_per_layers, layers, downsample),
[[]])
if width_scale != 1.0:
channels = [[int(cij * width_scale) for cij in ci] for ci in channels]
init_block_channels = int(init_block_channels * width_scale)
if width_scale > 1.0:
final_block_channels = int(final_block_channels * width_scale)
net = MobileNetV2(
channels=channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def mobilenetv2_w1(**kwargs):
"""
1.0 MobileNetV2-224 model from 'MobileNetV2: Inverted Residuals and Linear Bottlenecks,'
https://arxiv.org/abs/1801.04381.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenetv2(width_scale=1.0, model_name="mobilenetv2_w1", **kwargs)
def mobilenetv2_w3d4(**kwargs):
"""
0.75 MobileNetV2-224 model from 'MobileNetV2: Inverted Residuals and Linear Bottlenecks,'
https://arxiv.org/abs/1801.04381.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenetv2(width_scale=0.75, model_name="mobilenetv2_w3d4", **kwargs)
def mobilenetv2_wd2(**kwargs):
"""
0.5 MobileNetV2-224 model from 'MobileNetV2: Inverted Residuals and Linear Bottlenecks,'
https://arxiv.org/abs/1801.04381.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenetv2(width_scale=0.5, model_name="mobilenetv2_wd2", **kwargs)
def mobilenetv2_wd4(**kwargs):
"""
0.25 MobileNetV2-224 model from 'MobileNetV2: Inverted Residuals and Linear Bottlenecks,'
https://arxiv.org/abs/1801.04381.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenetv2(width_scale=0.25, model_name="mobilenetv2_wd4", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
mobilenetv2_w1,
mobilenetv2_w3d4,
mobilenetv2_wd2,
mobilenetv2_wd4,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != mobilenetv2_w1 or weight_count == 3504960)
assert (model != mobilenetv2_w3d4 or weight_count == 2627592)
assert (model != mobilenetv2_wd2 or weight_count == 1964736)
assert (model != mobilenetv2_wd4 or weight_count == 1516392)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 9,653 | 31.18 | 118 | py |
null | qimera-main/pytorchcv/models/mobilenetv3.py | """
MobileNetV3 for ImageNet-1K, implemented in PyTorch.
Original paper: 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
"""
__all__ = ['MobileNetV3', 'mobilenetv3_small_w7d20', 'mobilenetv3_small_wd2', 'mobilenetv3_small_w3d4',
'mobilenetv3_small_w1', 'mobilenetv3_small_w5d4', 'mobilenetv3_large_w7d20', 'mobilenetv3_large_wd2',
'mobilenetv3_large_w3d4', 'mobilenetv3_large_w1', 'mobilenetv3_large_w5d4']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import round_channels, conv1x1, conv1x1_block, conv3x3_block, dwconv3x3_block, dwconv5x5_block, SEBlock,\
HSwish
class MobileNetV3Unit(nn.Module):
"""
MobileNetV3 unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
exp_channels : int
Number of middle (expanded) channels.
stride : int or tuple/list of 2 int
Strides of the second convolution layer.
use_kernel3 : bool
Whether to use 3x3 (instead of 5x5) kernel.
activation : str
Activation function or name of activation function.
use_se : bool
Whether to use SE-module.
"""
def __init__(self,
in_channels,
out_channels,
exp_channels,
stride,
use_kernel3,
activation,
use_se):
super(MobileNetV3Unit, self).__init__()
assert (exp_channels >= out_channels)
self.residual = (in_channels == out_channels) and (stride == 1)
self.use_se = use_se
self.use_exp_conv = exp_channels != out_channels
mid_channels = exp_channels
if self.use_exp_conv:
self.exp_conv = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
activation=activation)
if use_kernel3:
self.conv1 = dwconv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride,
activation=activation)
else:
self.conv1 = dwconv5x5_block(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride,
activation=activation)
if self.use_se:
self.se = SEBlock(
channels=mid_channels,
reduction=4,
approx_sigmoid=True,
round_mid=True)
self.conv2 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
activation=None)
def forward(self, x):
if self.residual:
identity = x
if self.use_exp_conv:
x = self.exp_conv(x)
x = self.conv1(x)
if self.use_se:
x = self.se(x)
x = self.conv2(x)
if self.residual:
x = x + identity
return x
class MobileNetV3FinalBlock(nn.Module):
"""
MobileNetV3 final block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
use_se : bool
Whether to use SE-module.
"""
def __init__(self,
in_channels,
out_channels,
use_se):
super(MobileNetV3FinalBlock, self).__init__()
self.use_se = use_se
self.conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
activation="hswish")
if self.use_se:
self.se = SEBlock(
channels=out_channels,
reduction=4,
approx_sigmoid=True,
round_mid=True)
def forward(self, x):
x = self.conv(x)
if self.use_se:
x = self.se(x)
return x
class MobileNetV3Classifier(nn.Module):
"""
MobileNetV3 classifier.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
mid_channels : int
Number of middle channels.
dropout_rate : float
Parameter of Dropout layer. Faction of the input units to drop.
"""
def __init__(self,
in_channels,
out_channels,
mid_channels,
dropout_rate):
super(MobileNetV3Classifier, self).__init__()
self.use_dropout = (dropout_rate != 0.0)
self.conv1 = conv1x1(
in_channels=in_channels,
out_channels=mid_channels)
self.activ = HSwish(inplace=True)
if self.use_dropout:
self.dropout = nn.Dropout(p=dropout_rate)
self.conv2 = conv1x1(
in_channels=mid_channels,
out_channels=out_channels,
bias=True)
def forward(self, x):
x = self.conv1(x)
x = self.activ(x)
if self.use_dropout:
x = self.dropout(x)
x = self.conv2(x)
return x
class MobileNetV3(nn.Module):
"""
MobileNetV3 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
exp_channels : list of list of int
Number of middle (expanded) channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
final_block_channels : int
Number of output channels for the final block of the feature extractor.
classifier_mid_channels : int
Number of middle channels for classifier.
kernels3 : list of list of int/bool
Using 3x3 (instead of 5x5) kernel for each unit.
use_relu : list of list of int/bool
Using ReLU activation flag for each unit.
use_se : list of list of int/bool
Using SE-block flag for each unit.
first_stride : bool
Whether to use stride for the first stage.
final_use_se : bool
Whether to use SE-module in the final block.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
exp_channels,
init_block_channels,
final_block_channels,
classifier_mid_channels,
kernels3,
use_relu,
use_se,
first_stride,
final_use_se,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(MobileNetV3, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels,
stride=2,
activation="hswish"))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
exp_channels_ij = exp_channels[i][j]
stride = 2 if (j == 0) and ((i != 0) or first_stride) else 1
use_kernel3 = kernels3[i][j] == 1
activation = "relu" if use_relu[i][j] == 1 else "hswish"
use_se_flag = use_se[i][j] == 1
stage.add_module("unit{}".format(j + 1), MobileNetV3Unit(
in_channels=in_channels,
out_channels=out_channels,
exp_channels=exp_channels_ij,
use_kernel3=use_kernel3,
stride=stride,
activation=activation,
use_se=use_se_flag))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_block', MobileNetV3FinalBlock(
in_channels=in_channels,
out_channels=final_block_channels,
use_se=final_use_se))
in_channels = final_block_channels
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = MobileNetV3Classifier(
in_channels=in_channels,
out_channels=num_classes,
mid_channels=classifier_mid_channels,
dropout_rate=0.2)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = self.output(x)
x = x.view(x.size(0), -1)
return x
def get_mobilenetv3(version,
width_scale,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create MobileNetV3 model with specific parameters.
Parameters:
----------
version : str
Version of MobileNetV3 ('small' or 'large').
width_scale : float
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if version == "small":
init_block_channels = 16
channels = [[16], [24, 24], [40, 40, 40, 48, 48], [96, 96, 96]]
exp_channels = [[16], [72, 88], [96, 240, 240, 120, 144], [288, 576, 576]]
kernels3 = [[1], [1, 1], [0, 0, 0, 0, 0], [0, 0, 0]]
use_relu = [[1], [1, 1], [0, 0, 0, 0, 0], [0, 0, 0]]
use_se = [[1], [0, 0], [1, 1, 1, 1, 1], [1, 1, 1]]
first_stride = True
final_block_channels = 576
elif version == "large":
init_block_channels = 16
channels = [[16], [24, 24], [40, 40, 40], [80, 80, 80, 80, 112, 112], [160, 160, 160]]
exp_channels = [[16], [64, 72], [72, 120, 120], [240, 200, 184, 184, 480, 672], [672, 960, 960]]
kernels3 = [[1], [1, 1], [0, 0, 0], [1, 1, 1, 1, 1, 1], [0, 0, 0]]
use_relu = [[1], [1, 1], [1, 1, 1], [0, 0, 0, 0, 0, 0], [0, 0, 0]]
use_se = [[0], [0, 0], [1, 1, 1], [0, 0, 0, 0, 1, 1], [1, 1, 1]]
first_stride = False
final_block_channels = 960
else:
raise ValueError("Unsupported MobileNetV3 version {}".format(version))
final_use_se = False
classifier_mid_channels = 1280
if width_scale != 1.0:
channels = [[round_channels(cij * width_scale) for cij in ci] for ci in channels]
exp_channels = [[round_channels(cij * width_scale) for cij in ci] for ci in exp_channels]
init_block_channels = round_channels(init_block_channels * width_scale)
if width_scale > 1.0:
final_block_channels = round_channels(final_block_channels * width_scale)
net = MobileNetV3(
channels=channels,
exp_channels=exp_channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
classifier_mid_channels=classifier_mid_channels,
kernels3=kernels3,
use_relu=use_relu,
use_se=use_se,
first_stride=first_stride,
final_use_se=final_use_se,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def mobilenetv3_small_w7d20(**kwargs):
"""
MobileNetV3 Small 224/0.35 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenetv3(version="small", width_scale=0.35, model_name="mobilenetv3_small_w7d20", **kwargs)
def mobilenetv3_small_wd2(**kwargs):
"""
MobileNetV3 Small 224/0.5 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenetv3(version="small", width_scale=0.5, model_name="mobilenetv3_small_wd2", **kwargs)
def mobilenetv3_small_w3d4(**kwargs):
"""
MobileNetV3 Small 224/0.75 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenetv3(version="small", width_scale=0.75, model_name="mobilenetv3_small_w3d4", **kwargs)
def mobilenetv3_small_w1(**kwargs):
"""
MobileNetV3 Small 224/1.0 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenetv3(version="small", width_scale=1.0, model_name="mobilenetv3_small_w1", **kwargs)
def mobilenetv3_small_w5d4(**kwargs):
"""
MobileNetV3 Small 224/1.25 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenetv3(version="small", width_scale=1.25, model_name="mobilenetv3_small_w5d4", **kwargs)
def mobilenetv3_large_w7d20(**kwargs):
"""
MobileNetV3 Small 224/0.35 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenetv3(version="large", width_scale=0.35, model_name="mobilenetv3_small_w7d20", **kwargs)
def mobilenetv3_large_wd2(**kwargs):
"""
MobileNetV3 Large 224/0.5 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenetv3(version="large", width_scale=0.5, model_name="mobilenetv3_large_wd2", **kwargs)
def mobilenetv3_large_w3d4(**kwargs):
"""
MobileNetV3 Large 224/0.75 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenetv3(version="large", width_scale=0.75, model_name="mobilenetv3_large_w3d4", **kwargs)
def mobilenetv3_large_w1(**kwargs):
"""
MobileNetV3 Large 224/1.0 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenetv3(version="large", width_scale=1.0, model_name="mobilenetv3_large_w1", **kwargs)
def mobilenetv3_large_w5d4(**kwargs):
"""
MobileNetV3 Large 224/1.25 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_mobilenetv3(version="large", width_scale=1.25, model_name="mobilenetv3_large_w5d4", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
mobilenetv3_small_w7d20,
mobilenetv3_small_wd2,
mobilenetv3_small_w3d4,
mobilenetv3_small_w1,
mobilenetv3_small_w5d4,
mobilenetv3_large_w7d20,
mobilenetv3_large_wd2,
mobilenetv3_large_w3d4,
mobilenetv3_large_w1,
mobilenetv3_large_w5d4,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != mobilenetv3_small_w7d20 or weight_count == 2159600)
assert (model != mobilenetv3_small_wd2 or weight_count == 2288976)
assert (model != mobilenetv3_small_w3d4 or weight_count == 2581312)
assert (model != mobilenetv3_small_w1 or weight_count == 2945288)
assert (model != mobilenetv3_small_w5d4 or weight_count == 3643632)
assert (model != mobilenetv3_large_w7d20 or weight_count == 2943080)
assert (model != mobilenetv3_large_wd2 or weight_count == 3334896)
assert (model != mobilenetv3_large_w3d4 or weight_count == 4263496)
assert (model != mobilenetv3_large_w1 or weight_count == 5481752)
assert (model != mobilenetv3_large_w5d4 or weight_count == 7459144)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 18,988 | 33.152878 | 118 | py |
null | qimera-main/pytorchcv/models/model_store.py | """
Model store which provides pretrained models.
"""
__all__ = ['get_model_file', 'load_model', 'download_model', 'calc_num_params']
import os
import zipfile
import logging
import hashlib
_model_sha1 = {name: (error, checksum, repo_release_tag) for name, error, checksum, repo_release_tag in [
('alexnet', '1824', '8ada73bf8de14507a949c6a4a7e55d001a633bc5', 'v0.0.394'),
('alexnetb', '1900', '55176c6ad29c18243f4fdd0764840018a4ed1ca4', 'v0.0.384'),
('zfnet', '1727', 'd010ddca1eb32a50a8cceb475c792f53e769b631', 'v0.0.395'),
('zfnetb', '1490', 'f6bec24eba037c8e4956704ed5bafaed29966601', 'v0.0.400'),
('vgg11', '1036', '71e85f6ef76f56e3e89d597d2fc461496ed281e9', 'v0.0.381'),
('vgg13', '0975', '2b2c8770a7610d9dcd444ec8ae992681e270eb42', 'v0.0.388'),
('vgg16', '0865', '5ca155da3dc6687e070ff34815cb5aabd0bed4b9', 'v0.0.401'),
('vgg19', '0839', 'd4e69a0d393f4d46f1d9c4d4ba96f5a83de3399c', 'v0.0.109'),
('bn_vgg11', '0961', '10f01fba064ec168df074b98d59ae7b82b1207d4', 'v0.0.339'),
('bn_vgg13', '0913', 'b1acd7158e6e9973ce9e274c65ceb64a244f9967', 'v0.0.353'),
('bn_vgg16', '0779', '0f570b928b180f909fa39df3924f89c746816722', 'v0.0.359'),
('bn_vgg19', '0712', '3f286cbd2a57abb4c516425c5e095c2cfc8d54e3', 'v0.0.360'),
('bn_vgg11b', '0996', 'ef747edc87705e1ed500a31c80199273b2fbd5fa', 'v0.0.407'),
('bn_vgg13b', '0963', 'cf9352f47805c18798c0f80ab0e158ec5401331e', 'v0.0.110'),
('bn_vgg16b', '0874', 'af4f2d0bbfda667e6b7b3ad4cda5ca331021cd18', 'v0.0.110'),
('bn_vgg19b', '0840', 'b6919f7f74b3174a86818062b2d1d4cf5a110b8b', 'v0.0.110'),
('bninception', '0774', 'd79ba5f573ba2da5fea5e4c9a7f67ddd526e234b', 'v0.0.405'),
('resnet10', '1436', '67d9a618e8670497386af806564f7ac1a4dbcd76', 'v0.0.248'),
('resnet12', '1328', 'd7d2f4d6c7fcf3aff0458533ae5204b7f0eee2d7', 'v0.0.253'),
('resnet14', '1246', 'd5b55c113168c02f1b39b65f8908b0db467a2d74', 'v0.0.256'),
('resnetbc14b', '1151', 'ca61209c4052228edad1fe7bb48ad6a19db509d1', 'v0.0.309'),
('resnet16', '1118', 'd54bc41afa244476ca28380111f66d188905ecbc', 'v0.0.259'),
('resnet18_wd4', '1785', 'fe79b31f56e7becab9c014dbc14ccdb564b5148f', 'v0.0.262'),
('resnet18_wd2', '1327', '6654f50ad357f4596502b92b3dca2147776089ac', 'v0.0.263'),
('resnet18_w3d4', '1106', '3636648b504e1ba134947743eb34dd0e78feda02', 'v0.0.266'),
('resnet18', '0982', '0126861b4cd7f7b14196b1e01827da688f8bab6d', 'v0.0.153'),
('resnet26', '0854', '258347330aefca1c2387583680f812c9d6a8a66c', 'v0.0.305'),
('resnetbc26b', '0797', '7af52a73b234dc56ab4b0757cf3ea772d0699622', 'v0.0.313'),
('resnet34', '0780', '3f775482a327e5fc4850fbb77785bfc55e171e5f', 'v0.0.291'),
('resnetbc38b', '0700', '3fbac61d86810d489988a92f425f1a6bfe46f155', 'v0.0.328'),
('resnet50', '0633', 'b00d1c8e52aa7a2badc705b1545aaf6ccece6ce9', 'v0.0.329'),
('resnet50b', '0638', '8a5473ef985d65076a3758117ad5700d726bd952', 'v0.0.308'),
('resnet101', '0622', 'ab0cf005bbe9b17e53f9e3c330c6147a8c80b3a5', 'v0.0.1'),
('resnet101b', '0530', 'f059ba3c7fa4a65f2da6e17f3718662d59836637', 'v0.0.357'),
('resnet152', '0550', '800b2cb1959a0d3648483e86917502b8f63dc37e', 'v0.0.144'),
('resnet152b', '0499', '667ea926f3753e0c8336fa78969171d64f819cc4', 'v0.0.378'),
('preresnet10', '1421', 'b3973cd4461287d61df081d6f689d293eacf2248', 'v0.0.249'),
('preresnet12', '1348', '563066fa8fcf8b5f19906b933fea784965d68192', 'v0.0.257'),
('preresnet14', '1239', '4be725fd3f06c99c46817fce3b69caf2ebc62414', 'v0.0.260'),
('preresnetbc14b', '1181', 'a68d31c372e647474ae954e51e5bc2ba9fb3f166', 'v0.0.315'),
('preresnet16', '1108', '06d8c87e29284dac19a9019485e210541532411a', 'v0.0.261'),
('preresnet18_wd4', '1811', '41135c15210390e9a564b14e8ae2ebda1a662ec1', 'v0.0.272'),
('preresnet18_wd2', '1340', 'c1fe4e314188eeb93302432d03731a91ce8bc9f2', 'v0.0.273'),
('preresnet18_w3d4', '1105', 'ed2f9ca434b6910b92657eefc73ad186396578d5', 'v0.0.274'),
('preresnet18', '0972', '5651bc2dbb200382822a6b64375d240f747cc726', 'v0.0.140'),
('preresnet26', '0851', '99e7d6cc5944cd7cf6d4746e6fdf18b477d3d9a0', 'v0.0.316'),
('preresnetbc26b', '0803', 'd7283bdd70e1b75520fe2cdcc273d51715e077b4', 'v0.0.325'),
('preresnet34', '0774', 'fd5bd1e883048e29099768465df2dd9e891803f4', 'v0.0.300'),
('preresnetbc38b', '0657', '9e523bb92dc592ee576a6bb73a328dc024bdc967', 'v0.0.348'),
('preresnet50', '0647', '222ca73b021f893b925c15e24ea2a6bc0fdf2546', 'v0.0.330'),
('preresnet50b', '0655', '8b60378ee3aed878d27a2b4a9ddc596a812c7649', 'v0.0.307'),
('preresnet101', '0591', '4bacff796e113562e1dfdf71cfa7c6ed33e0ba86', 'v0.0.2'),
('preresnet101b', '0556', '76bfe6d020b55f163e77de6b1c27be6b0bed8b7b', 'v0.0.351'),
('preresnet152', '0555', 'c842a030abbcc21a0f2a9a8299fc42204897a611', 'v0.0.14'),
('preresnet152b', '0516', 'f3805f4b8c845798b711171ad6632bcf56259844', 'v0.0.386'),
('preresnet200b', '0588', 'f7104ff306ed5de2c27f3c855051c22bda167981', 'v0.0.45'),
('preresnet269b', '0581', '1a7878bb10923b22bda58d7935dfa6e5e8a7b67d', 'v0.0.239'),
('resnext14_16x4d', '1248', '35ffac2a26374e71b6bf4bc9f90b7a1a1dd47e7d', 'v0.0.370'),
('resnext14_32x2d', '1281', '14521186b8c78c7c07f3904360839f22c180f65e', 'v0.0.371'),
('resnext14_32x4d', '1146', '89aa679393d8356ce5589749b4371714bf4ceac0', 'v0.0.327'),
('resnext26_32x2d', '0887', 'c3bd130747909a8c89546f3b3f5ce08bb4f55731', 'v0.0.373'),
('resnext26_32x4d', '0746', '1011ac35e30d753b79f0600a5376c87a37b67a61', 'v0.0.332'),
('resnext101_32x4d', '0611', 'cf962440f11fe683fd02ec04f2102d9f47ce38a7', 'v0.0.10'),
('resnext101_64x4d', '0575', '651abd029bcc4ce88c62e1d900a710f284a8281e', 'v0.0.10'),
('seresnet10', '1366', '6ec312230962e5f809e2dd77444a2a1bdfbb06f4', 'v0.0.354'),
('seresnet18', '0961', '022123a5e88c9917e63165f5b5a7808a606d452a', 'v0.0.355'),
('seresnet26', '0824', '64fc8759c5bb9b9b40b2e33a46420ee22ae268c9', 'v0.0.363'),
('seresnetbc26b', '0703', 'b98d9d6afca4d79d0347001542162b9fe4071d39', 'v0.0.366'),
('seresnetbc38b', '0595', '03671c05f5f684b44085383b7b89a8b44a7524fe', 'v0.0.374'),
('seresnet50', '0640', '8820f2af62421ce2e1df989d6e0ce7916c78ff86', 'v0.0.11'),
('seresnet50b', '0539', '459e6871e944d1c7102ee9c055ea428b8d9a168c', 'v0.0.387'),
('seresnet101', '0589', '5e6e831b7518b9b8a049dd60ed1ff82ae75ff55e', 'v0.0.11'),
('seresnet152', '0576', '814cf72e0deeab530332b16fb9b609e574afec61', 'v0.0.11'),
('sepreresnet10', '1338', '935ed56009a64c893153cdba8e4a4f87f7184e71', 'v0.0.377'),
('sepreresnet18', '0963', 'c065cd9e1c026d0529526cfc945c137bade6f0c7', 'v0.0.380'),
('sepreresnetbc26b', '0660', 'f750b2f588a27620b30c86f0060a41422d4a0f75', 'v0.0.399'),
('sepreresnetbc38b', '0578', '12827fcd3c8c1a8c8ba1d109e85ffa67e7ab306a', 'v0.0.409'),
('seresnext50_32x4d', '0554', '99e0e9aa4578af9f15045c1ceeb684a2e988628a', 'v0.0.12'),
('seresnext101_32x4d', '0505', '0924f0a2c1de90dc964c482b7aff6232dbef3600', 'v0.0.12'),
('senet16', '0820', '373aeafdc994c3e03bf483a9fa3ecb152353722a', 'v0.0.341'),
('senet28', '0598', '27165b63696061e57c141314d44732aa65f807a8', 'v0.0.356'),
('senet154', '0461', '6512228c820897cd09f877527a553ca99d673956', 'v0.0.13'),
('ibn_resnet50', '0641', 'e48a1fe5f7e448d4b784ef4dc0f33832f3370a9b', 'v0.0.127'),
('ibn_resnet101', '0561', '5279c78a0dbfc722cfcfb788af479b6133920528', 'v0.0.127'),
('ibnb_resnet50', '0686', 'e138995e6acda4b496375beac6d01cd7a9f79876', 'v0.0.127'),
('ibn_resnext101_32x4d', '0542', 'b5233c663a4d207d08c21107d6c951956e910be8', 'v0.0.127'),
('ibn_densenet121', '0725', 'b90b0615e6ec5c9652e3e553e27851c8eaf01adf', 'v0.0.127'),
('ibn_densenet169', '0651', '96dd755e0df8a54349278e0cd23a043a5554de08', 'v0.0.127'),
('airnet50_1x64d_r2', '0590', '3ec422128d17314124c02e3bb0f77e26777fb385', 'v0.0.120'),
('airnet50_1x64d_r16', '0619', '090179e777f47057bedded22d669bf9f9ce3169c', 'v0.0.120'),
('airnext50_32x4d_r2', '0551', 'c68156e5e446a1116b1b42bc94b3f881ab73fe92', 'v0.0.120'),
('bam_resnet50', '0658', '96a37c82bdba821385b29859ad1db83061a0ca5b', 'v0.0.124'),
('cbam_resnet50', '0605', 'a1172fe679622224dcc88c00020936ad381806fb', 'v0.0.125'),
('pyramidnet101_a360', '0620', '3a24427baf21ee6566d7e4c7dee25da0e5744f7f', 'v0.0.104'),
('diracnet18v2', '1170', 'e06737707a1f5a5c7fe4e57da92ed890b034cb9a', 'v0.0.111'),
('diracnet34v2', '0993', 'a6a661c0c3e96af320e5b9bf65a6c8e5e498a474', 'v0.0.111'),
('densenet121', '0704', 'cf90d1394d197fde953f57576403950345bd0a66', 'v0.0.314'),
('densenet161', '0644', 'c0fb22c83e8077a952ce1a0c9703d1a08b2b9e3a', 'v0.0.3'),
('densenet169', '0629', '44974a17309bb378e97c8f70f96f961ffbf9458d', 'v0.0.406'),
('densenet201', '0663', '71ece4ad7be5d1e2aa4bbf6f1a6b32ac2562d847', 'v0.0.3'),
('condensenet74_c4_g4', '0828', '5ba550494cae7081d12c14b02b2a02365539d377', 'v0.0.4'),
('condensenet74_c8_g8', '1006', '3574d874fefc3307f241690bad51f20e61be1542', 'v0.0.4'),
('peleenet', '1151', '9c47b80297ac072a923cda763b78e7218cd52d3a', 'v0.0.141'),
('wrn50_2', '0641', '83897ab9f015f6f988e51108e12518b08e1819dd', 'v0.0.113'),
('drnc26', '0755', '35405bd52a0c721f3dc64f18d433074f263b7339', 'v0.0.116'),
('drnc42', '0657', '7c99c4608a9a5e5f073f657b92f258ba4ba5ac77', 'v0.0.116'),
('drnc58', '0601', '70ec1f56c23da863628d126a6ed0ad10f037a2ac', 'v0.0.116'),
('drnd22', '0823', '5c2c6a0cf992409ab388e04e9fbd06b7141bdf47', 'v0.0.116'),
('drnd38', '0695', '4630f0fb3f721f4a2296e05aacb1231ba7530ae5', 'v0.0.116'),
('drnd54', '0586', 'bfdc1f8826027b247e2757be45b176b3b91b9ea3', 'v0.0.116'),
('drnd105', '0548', 'a643f4dcf9e4b69eab06b76e54ce22169f837592', 'v0.0.116'),
('dpn68', '0679', 'a33c98c783cbf93cca4cc9ce1584da50a6b12077', 'v0.0.310'),
('dpn98', '0553', '52c55969835d56185afa497c43f09df07f58f0d3', 'v0.0.17'),
('dpn131', '0548', '0c53e5b380137ccb789e932775e8bd8a811eeb3e', 'v0.0.17'),
('darknet_tiny', '1784', '4561e1ada619e33520d1f765b3321f7f8ea6196b', 'v0.0.69'),
('darknet_ref', '1718', '034595b49113ee23de72e36f7d8a3dbb594615f6', 'v0.0.64'),
('darknet53', '0564', 'b36bef6b297055dda3d17a3f79596511730e1963', 'v0.0.150'),
('irevnet301', '0841', '95dc8d94257bf16027edd7077b785a8676369fca', 'v0.0.251'),
('bagnet9', '2961', 'cab1179284e9749697f38c1c7e5f0e172be12c89', 'v0.0.255'),
('bagnet17', '1884', '6b2a100f8d14d4616709586483f625743ed04769', 'v0.0.255'),
('bagnet33', '1301', '4f17b6e837dacd978b15708ffbb2c1e6be3c371a', 'v0.0.255'),
('dla34', '0794', '04698d78b16f2d08e4396b5b0c9f46cb42542242', 'v0.0.202'),
('dla46c', '1323', 'efcd363642a4b479892f47edae7440f0eea05edb', 'v0.0.282'),
('dla46xc', '1269', '00d3754ad0ff22636bb1f4b4fb8baebf4751a1ee', 'v0.0.293'),
('dla60', '0669', 'b2cd6e51a322512a6cb45414982a2ec71285daad', 'v0.0.202'),
('dla60x', '0598', '88547d3f81c4df711b15457cfcf37e2b703ed895', 'v0.0.202'),
('dla60xc', '1091', '0f6381f335e5bbb4c69b360be61a4a08e5c7a9de', 'v0.0.289'),
('dla102', '0605', '11df13220b44f51dc8c925fbd9fc334bc8d115b4', 'v0.0.202'),
('dla102x', '0577', '58331655844f9d95bcf2bb90de6ac9cf3b66bd5e', 'v0.0.202'),
('dla102x2', '0536', '079361117045dc661b63ce4b14408d403bc91844', 'v0.0.202'),
('dla169', '0566', 'ae0c6a82acfaf9dc459ac5a032106c2727b71d4f', 'v0.0.202'),
('fishnet150', '0604', 'f5af4873ff5730f589a6c4a505ede8268e6ce3e3', 'v0.0.168'),
('espnetv2_wd2', '2015', 'd234781f81e5d1b5ae6070fc851e3f7bb860b9fd', 'v0.0.238'),
('espnetv2_w1', '1345', '550d54229d7fd8f7c090601c2123ab3ca106393b', 'v0.0.238'),
('espnetv2_w5d4', '1218', '85d97b2b1c9ebb176f634949ef5ca6d7fe70f09c', 'v0.0.238'),
('espnetv2_w3d2', '1129', '3bbb49adaa4fa984a67f82862db7dcfc4998429e', 'v0.0.238'),
('espnetv2_w2', '0961', '13ba0f7200eb745bacdf692905fde711236448ef', 'v0.0.238'),
('squeezenet_v1_0', '1766', 'afdbcf1aef39237300656d2c5a7dba19230e29fc', 'v0.0.128'),
('squeezenet_v1_1', '1772', '25b77bc39e35612abbe7c2344d2c3e1e6756c2f8', 'v0.0.88'),
('squeezeresnet_v1_0', '1809', '25bfc02edeffb279010242614e7d73bbeacc0170', 'v0.0.178'),
('squeezeresnet_v1_1', '1821', 'c27ed88f1b19eb233d3925efc71c71d25e4c434e', 'v0.0.70'),
('sqnxt23_w1', '1906', '97b74e0c4d6bf9fc939771d94b2f6dd97de34024', 'v0.0.171'),
('sqnxt23v5_w1', '1785', '2fe3ad67d73313193a77690b10c17cbceef92340', 'v0.0.172'),
('sqnxt23_w3d2', '1350', 'c2f21bce669dbe50fba544bcc39bc1302f63e1e8', 'v0.0.210'),
('sqnxt23v5_w3d2', '1301', 'c244844ba2f02dadd350dddd74e21360b452f9dd', 'v0.0.212'),
('sqnxt23_w2', '1100', 'b9bb7302824f89f16e078f0a506e3a8c0ad9c74e', 'v0.0.240'),
('sqnxt23v5_w2', '1066', '229b0d3de06197e399eeebf42dc826b78f0aba86', 'v0.0.216'),
('shufflenet_g1_wd4', '3729', '47dbd0f279da6d3056079bb79ad39cabbb3b9415', 'v0.0.134'),
('shufflenet_g3_wd4', '3653', '6abdd65e087e71f80345415cdf7ada6ed2762d60', 'v0.0.135'),
('shufflenet_g1_wd2', '2261', 'dae4bdadd7d48bee791dff2a08cd697cff0e9320', 'v0.0.174'),
('shufflenet_g3_wd2', '2080', 'ccaacfc8d9ac112c6143269df6e258fd55b662a7', 'v0.0.167'),
('shufflenet_g1_w3d4', '1711', '161cd24aa0b2e2afadafa69b44a28af222f2ec7a', 'v0.0.218'),
('shufflenet_g3_w3d4', '1650', '3f3b0aef0ce3174c78ff42cf6910c6e34540fc41', 'v0.0.219'),
('shufflenet_g1_w1', '1389', '4cfb65a30761fe548e0b5afbb5d89793ec41e4e9', 'v0.0.223'),
('shufflenet_g2_w1', '1363', '07256203e217a7b31f1c69a5bd38a6674bce75bc', 'v0.0.241'),
('shufflenet_g3_w1', '1348', 'ce54f64ecff87556a4303380f46abaaf649eb308', 'v0.0.244'),
('shufflenet_g4_w1', '1335', 'e2415f8270a4b6cbfe7dc97044d497edbc898577', 'v0.0.245'),
('shufflenet_g8_w1', '1342', '9a979b365424addba75c559a61a77ac7154b26eb', 'v0.0.250'),
('shufflenetv2_wd2', '1865', '9c22238b5fa9c09541564e8ed7f357a5f7e8cd7c', 'v0.0.90'),
('shufflenetv2_w1', '1163', 'c71dfb7a814c8d8ef704bdbd80995e9ea49ff4ff', 'v0.0.133'),
('shufflenetv2_w3d2', '0942', '26a9230405d956643dcd563a5a383844c49b5907', 'v0.0.288'),
('shufflenetv2_w2', '0845', '337255f6ad40a93c2f23fc593bad4b2755a327fa', 'v0.0.301'),
('shufflenetv2b_wd2', '1822', '01d18d6fa1a6136f605a4277f47c9a757f9ede3b', 'v0.0.157'),
('shufflenetv2b_w1', '1125', '6a5d3dc446e6a00cf60fe8aa2f4139d74d766305', 'v0.0.161'),
('shufflenetv2b_w3d2', '0911', 'f2106fee0748d7f0d40db16b228782b6d7636737', 'v0.0.203'),
('shufflenetv2b_w2', '0834', 'cb36b92ca4ca3bee470b739021d01177e0601c5f', 'v0.0.242'),
('menet108_8x1_g3', '2076', '6acc82e46dfc1ce0dd8c59668aed4a464c8cbdb5', 'v0.0.89'),
('menet128_8x1_g4', '1959', '48fa80fc363adb88ff580788faa8053c9d7507f3', 'v0.0.103'),
('menet160_8x1_g8', '2084', '0f4fce43b4234c5bca5dd76450b698c2d4daae65', 'v0.0.154'),
('menet228_12x1_g3', '1316', '5b670c42031d0078e2ae981829358d7c1b92ee30', 'v0.0.131'),
('menet256_12x1_g4', '1252', '14c6c86df96435c693eb7d0fcd8d3bf4079dd621', 'v0.0.152'),
('menet348_12x1_g3', '0958', 'ad50f635a1f7b799a19a0a9c71aa9939db8ffe77', 'v0.0.173'),
('menet352_12x1_g8', '1200', '4ee200c5c98c64a2503cea82ebf62d1d3c07fb91', 'v0.0.198'),
('menet456_24x1_g3', '0799', '826c002244f1cdc945a95302b1ce5c66d949db74', 'v0.0.237'),
('mobilenet_wd4', '2249', '1ad5e8fe8674cdf7ffda8450095eb96d227397e0', 'v0.0.62'),
('mobilenet_wd2', '1355', '41a21242c95050407df876cfa44bb5d3676aa751', 'v0.0.156'),
('mobilenet_w3d4', '1076', 'd801bcaea83885b16a0306b8b77fe314bbc585c3', 'v0.0.130'),
('mobilenet_w1', '0895', '7e1d739f0fd4b95c16eef077c5dc0a5bb1da8ad5', 'v0.0.155'),
('fdmobilenet_wd4', '3098', '2b22b709a05d7ca6e43acc6f3a9f27d0eb2e01cd', 'v0.0.177'),
('fdmobilenet_wd2', '2015', '414dbeedb2f829dcd8f94cd7fef10aae6829f06f', 'v0.0.83'),
('fdmobilenet_w3d4', '1641', '5561d58aa8889d8d93f2062a2af4e4b35ad7e769', 'v0.0.159'),
('fdmobilenet_w1', '1338', '9d026c04112de9f40e15fa40457d77941443c327', 'v0.0.162'),
('mobilenetv2_wd4', '2451', '05e1e3a286b27c17ea11928783c4cd48b1e7a9b2', 'v0.0.137'),
('mobilenetv2_wd2', '1493', 'b82d79f6730eac625e6b55b0618bff8f7a1ed86d', 'v0.0.170'),
('mobilenetv2_w3d4', '1082', '8656de5a8d90b29779c35c5ce521267c841fd717', 'v0.0.230'),
('mobilenetv2_w1', '0887', '13a021bca5b679b76156829743f7182da42e8bb6', 'v0.0.213'),
('mobilenetv3_large_w1', '0779', '38e392f58bdf99b2832b26341bc9704ac63a3672', 'v0.0.411'),
('igcv3_wd4', '2871', 'c9f28301391601e5e8ae93139431a9e0d467317c', 'v0.0.142'),
('igcv3_wd2', '1732', '8c504f443283d8a32787275b23771082fcaab61b', 'v0.0.132'),
('igcv3_w3d4', '1140', '63f43cf8d334111d55d06f2f9bf7e1e4871d162c', 'v0.0.207'),
('igcv3_w1', '0920', '12385791681f09adb3a08926c95471f332f538b6', 'v0.0.243'),
('mnasnet', '1174', 'e8ec017ca396dc7d39e03b383776b8cf9ad20a4d', 'v0.0.117'),
('darts', '0874', '74f0c7b690cf8bef9b54cc5afc2cb0f2a2a83630', 'v0.0.118'),
('proxylessnas_cpu', '0761', 'fe9572b11899395acbeef9374827dcc04e103ce3', 'v0.0.304'),
('proxylessnas_gpu', '0745', 'acca5941c454d896410060434b8f983d2db80727', 'v0.0.333'),
('proxylessnas_mobile', '0780', '639a90c27de088402db76b09e410326795b6fbdd', 'v0.0.304'),
('proxylessnas_mobile14', '0662', '0c0ad983f4fb88470d0f3e557d0b23f15e16624f', 'v0.0.331'),
('fbnet_cb', '0762', '2edb61f8e4b5c45d958d0e57beff41fbfacd6061', 'v0.0.415'),
('xception', '0549', 'e4f0232c99fa776e630189d62fea18e248a858b2', 'v0.0.115'),
('inceptionv3', '0565', 'cf4061800bc1dc3b090920fc9536d8ccc15bb86e', 'v0.0.92'),
('inceptionv4', '0529', '5cb7b4e4b8f62d6b4346855d696b06b426b44f3d', 'v0.0.105'),
('inceptionresnetv2', '0490', '1d1b4d184e6d41091c5ac3321d99fa554b498dbe', 'v0.0.107'),
('polynet', '0452', '6a1b295dad3f261b48e845f1b283e4eef3ab5a0b', 'v0.0.96'),
('nasnet_4a1056', '0816', 'd21bbaf5e937c2e06134fa40e7bdb1f501423b86', 'v0.0.97'),
('nasnet_6a4032', '0421', 'f354d28f4acdde399e081260c3f46152eca5d27e', 'v0.0.101'),
('pnasnet5large', '0428', '65de46ebd049e494c13958d5671aba5abf803ff3', 'v0.0.114'),
('spnasnet', '0817', '290a4fd99674b8f32d5143774ca0141f1b511733', 'v0.0.416'),
('efficientnet_b0', '0752', '0e3861300b8f1d1d0fb1bd15f0e06bba1ad6309b', 'v0.0.364'),
('efficientnet_b1', '0638', 'ac77bcd722dc4f3edfa24b9fb7b8f9cece3d85ab', 'v0.0.376'),
('efficientnet_b0b', '0702', 'ecf61b9b50666a6b444a9d789a5ff1087c65d0d8', 'v0.0.403'),
('efficientnet_b1b', '0594', '614e81663902850a738fa6c862fe406ecf205f73', 'v0.0.403'),
('efficientnet_b2b', '0527', '531f10e6898778b7c3a82c2c149f8b3e6393a892', 'v0.0.403'),
('efficientnet_b3b', '0445', '3c5fbba8c86121d4bc3bbc169804f24dd4c3d1f6', 'v0.0.403'),
('efficientnet_b4b', '0389', '6305bfe688b261f0d4fef6829f520d5c98c46301', 'v0.0.403'),
('efficientnet_b5b', '0337', 'e1c2ffcf710cbd3c53b9c08723282a370906731c', 'v0.0.403'),
('efficientnet_b6b', '0323', 'e5c1d7c35fcff5fac07921a7696f7c04aba84012', 'v0.0.403'),
('efficientnet_b7b', '0322', 'b9c5965a1e2572aaa772e20e8a2e3af7b4bee9a6', 'v0.0.403'),
('mixnet_s', '0719', 'aeafe8432c11ffafbe72b9456d0c040151a5465c', 'v0.0.412'),
('mixnet_m', '0660', '5aab9fbd5a1d53cca58cdab4e1c644cacb6e0d8c', 'v0.0.413'),
('mixnet_l', '0582', '6cf2c97538d4173d9f6bc80a6ec299463df2d1f3', 'v0.0.414'),
('resnetd50b', '0565', 'ec03d815c0f016c6517ed7b4b40126af46ceb8a4', 'v0.0.296'),
('resnetd101b', '0473', 'f851c920ec1fe4f729d339c933535d038bf2903c', 'v0.0.296'),
('resnetd152b', '0482', '112e216da50eb20d52c509a28c97b05ef819cefe', 'v0.0.296'),
('nin_cifar10', '0743', '795b082470b58c1aa94e2f861514b7914f6e2f58', 'v0.0.175'),
('nin_cifar100', '2839', '627a11c064eb44c6451fe53e0becfc21a6d57d7f', 'v0.0.183'),
('nin_svhn', '0376', '1205dc06a4847bece8159754033f325f75565c02', 'v0.0.270'),
('resnet20_cifar10', '0597', '9b0024ac4c2f374cde2c5052e0d0344a75871cdb', 'v0.0.163'),
('resnet20_cifar100', '2964', 'a5322afed92fa96cb7b3453106f73cf38e316151', 'v0.0.180'),
('resnet20_svhn', '0343', '8232e6e4c2c9fac1200386b68311c3bd56f483f5', 'v0.0.265'),
('resnet56_cifar10', '0452', '628c42a26fe347b84060136212e018df2bb35e0f', 'v0.0.163'),
('resnet56_cifar100', '2488', 'd65f53b10ad5d124698e728432844c65261c3107', 'v0.0.181'),
('resnet56_svhn', '0275', '6e08ed929b8f0ee649f75464f06b557089023290', 'v0.0.265'),
('resnet110_cifar10', '0369', '4d6ca1fc02eaeed724f4f596011e391528536049', 'v0.0.163'),
('resnet110_cifar100', '2280', 'd8d397a767db6d22af040223ec8ae342a088c3e5', 'v0.0.190'),
('resnet110_svhn', '0245', 'c971f0a38943d8a75386a60c835cc0843c2f6c1c', 'v0.0.265'),
('resnet164bn_cifar10', '0368', '74ae9f4bccb7fb6a8f3f603fdabe8d8632c46b2f', 'v0.0.179'),
('resnet164bn_cifar100', '2044', '8fa07b7264a075fa5add58f4c676b99a98fb1c89', 'v0.0.182'),
('resnet164bn_svhn', '0242', '549413723d787cf7e96903427a7a14fb3ea1a4c1', 'v0.0.267'),
('resnet272bn_cifar10', '0333', '84f28e0ca97eaeae0eb07e9f76054c1ba0c77c0e', 'v0.0.368'),
('resnet272bn_cifar100', '2007', 'a80d2b3ce14de6c90bf22d210d76ebd4a8c91928', 'v0.0.368'),
('resnet272bn_svhn', '0243', 'ab1d7da51f52cc6acb2e759736f2d58a77ce895e', 'v0.0.368'),
('resnet542bn_cifar10', '0343', '0fd36dd16587f49d33e0e36f1e8596d021a11439', 'v0.0.369'),
('resnet542bn_cifar100', '1932', 'a631d3ce5f12e145637a7b2faee663cddc94c354', 'v0.0.369'),
('resnet542bn_svhn', '0234', '04396c973121e356f2efda9a28c4e4086f1511b2', 'v0.0.369'),
('resnet1001_cifar10', '0328', '77a179e240808b7aa3534230d39b845a62413ca2', 'v0.0.201'),
('resnet1001_cifar100', '1979', '2728b558748f9c3e70db179afb6c62358020858b', 'v0.0.254'),
('resnet1001_svhn', '0241', '9e3d4bb55961db4c0f46a961b5323a4e03aea602', 'v0.0.408'),
('resnet1202_cifar10', '0353', '1d5a21290117903fb5fd6ba59f3f7e7da7c08836', 'v0.0.214'),
('resnet1202_cifar100', '2156', '86ecd091e5ac9677bf4518c644d08eb3e1d1708a', 'v0.0.410'),
('preresnet20_cifar10', '0651', '76cec68d11de5b25be2ea5935681645b76195f1d', 'v0.0.164'),
('preresnet20_cifar100', '3022', '3dbfa6a2b850572bccb28cc2477a0e46c24abcb8', 'v0.0.187'),
('preresnet20_svhn', '0322', 'c3c00fed49c1d6d9deda6436d041c5788d549299', 'v0.0.269'),
('preresnet56_cifar10', '0449', 'e9124fcf167d8ca50addef00c3afa4da9f828f29', 'v0.0.164'),
('preresnet56_cifar100', '2505', 'ca90a2be6002cd378769b9d4e7c497dd883d31d9', 'v0.0.188'),
('preresnet56_svhn', '0280', 'b51b41476710c0e2c941356ffe992ff883a3ee87', 'v0.0.269'),
('preresnet110_cifar10', '0386', 'cc08946a2126a1224d1d2560a47cf766a763c52c', 'v0.0.164'),
('preresnet110_cifar100', '2267', '3954e91581b7f3e5f689385d15f618fe16e995af', 'v0.0.191'),
('preresnet110_svhn', '0279', 'aa49e0a3c4a918e227ca2d5a5608704f026134c3', 'v0.0.269'),
('preresnet164bn_cifar10', '0364', '429012d412e82df7961fa071f97c938530e1b005', 'v0.0.196'),
('preresnet164bn_cifar100', '2018', 'a8e67ca6e14f88b009d618b0e9b554312d862174', 'v0.0.192'),
('preresnet164bn_svhn', '0258', '94d42de440d5f057a38f4c8cdbdb24acfee3981c', 'v0.0.269'),
('preresnet272bn_cifar10', '0325', '1a6a016eb4e4a5549c1fcb89ed5af4c1e5715b72', 'v0.0.389'),
('preresnet272bn_cifar100', '1963', '6fe0d2e24a60d12ab6b3d0e46065e2f14a46bc0b', 'v0.0.389'),
('preresnet272bn_svhn', '0234', 'c04ef5c20a53f76824339fe75185d181be4bce61', 'v0.0.389'),
('preresnet542bn_cifar10', '0314', '66fd6f2033dff08428e586bcce3e5151ed4274f9', 'v0.0.391'),
('preresnet542bn_cifar100', '1871', '07f1fb258207d295789981519e8dab892fc08f8d', 'v0.0.391'),
('preresnet542bn_svhn', '0236', '6bdf92368873ce1288526dc405f15e689a1d3117', 'v0.0.391'),
('preresnet1001_cifar10', '0265', '9fedfe5fd643e7355f1062a6db68da310c8962be', 'v0.0.209'),
('preresnet1001_cifar100', '1841', '88f14ed9df1573e98b0ec2a07009a15066855fda', 'v0.0.283'),
('preresnet1202_cifar10', '0339', '6fc686b02191226f39e25a76fc5da26857f7acd9', 'v0.0.246'),
('resnext29_32x4d_cifar10', '0315', '30413525cd4466dbef759294eda9b702bc39648f', 'v0.0.169'),
('resnext29_32x4d_cifar100', '1950', '13ba13d92f6751022549a3b370ae86d3b13ae2d1', 'v0.0.200'),
('resnext29_32x4d_svhn', '0280', 'e85c5217944cdfafb0a538dd7cc817cffaada7c4', 'v0.0.275'),
('resnext29_16x64d_cifar10', '0241', '4133d3d04f9b10b132dcb959601d36f10123f8c2', 'v0.0.176'),
('resnext29_16x64d_cifar100', '1693', '05e9a7f113099a98b219cad622ecfad5517a3b54', 'v0.0.322'),
('resnext29_16x64d_svhn', '0268', '74332b714cd278bfca3f09dafe2a9d117510e9a4', 'v0.0.358'),
('resnext272_1x64d_cifar10', '0255', '070ccc35c2841b7715b9eb271197c9bb316f3093', 'v0.0.372'),
('resnext272_1x64d_cifar100', '1911', '114eb0f8a0d471487e819b8fd156c1286ef91b7a', 'v0.0.372'),
('resnext272_1x64d_svhn', '0235', 'ab0448469bbd7d476f8bed1bf86403304b028e7c', 'v0.0.372'),
('resnext272_2x32d_cifar10', '0274', 'd2ace03c413be7e42c839c84db8dd0ebb5d69512', 'v0.0.375'),
('resnext272_2x32d_cifar100', '1834', '0b30c4701a719995412882409339f3553a54c9d1', 'v0.0.375'),
('resnext272_2x32d_svhn', '0244', '39b8a33612d335a0193b867b38c0b09d168de6c3', 'v0.0.375'),
('seresnet20_cifar10', '0601', '935d89433e803c8a3027c81f1267401e7caccce6', 'v0.0.362'),
('seresnet20_cifar100', '2854', '8c7abf66d8c1418cb3ca760f5d1efbb42738036b', 'v0.0.362'),
('seresnet20_svhn', '0323', 'd77df31c62d1504209a5ba47e59ccb0ae84500b2', 'v0.0.362'),
('seresnet56_cifar10', '0413', 'b61c143989cb2901bec48dded4c6ddcae91aabc4', 'v0.0.362'),
('seresnet56_cifar100', '2294', '7fa54f4593f364c2363cb3ee8d5bc1285af1ade5', 'v0.0.362'),
('seresnet56_svhn', '0264', '93839c762a97bd0b5bd27c71fd64c227afdae3ed', 'v0.0.362'),
('seresnet110_cifar10', '0363', '1ddec2309ff61c2c0e14c96d51a1b846afdc2acc', 'v0.0.362'),
('seresnet110_cifar100', '2086', 'a82c30938028a172dd6a124152bc0952b55a2f49', 'v0.0.362'),
('seresnet110_svhn', '0235', '9572ba7394c774b8d056b24a7631ef47e53024b8', 'v0.0.362'),
('seresnet164bn_cifar10', '0339', '1085dab6467cb18e554123663816094f080fc626', 'v0.0.362'),
('seresnet164bn_cifar100', '1995', '97dd4ab630f6277cf7b07cbdcbf4ae8ddce4d401', 'v0.0.362'),
('seresnet164bn_svhn', '0245', 'af0a90a50fb3c91eef039178a681e69aae703f3a', 'v0.0.362'),
('seresnet272bn_cifar10', '0339', '812db5187bab9aa5203611c1c174d0e51c81761c', 'v0.0.390'),
('seresnet272bn_cifar100', '1907', '179e1c38ba714e1babf6c764ca735f256d4cd122', 'v0.0.390'),
('seresnet272bn_svhn', '0238', '0e16badab35b483b1a1b0e7ea2a615de714f7424', 'v0.0.390'),
('seresnet542bn_cifar10', '0347', 'd1542214765f1923f2fdce810aef5dc2e523ffd2', 'v0.0.385'),
('seresnet542bn_cifar100', '1887', '9c4e7623dc06a56edabf04f4427286916843df85', 'v0.0.385'),
('seresnet542bn_svhn', '0226', '71a8f2986cbc1146f9a41d1a08ecba52649b8efd', 'v0.0.385'),
('sepreresnet20_cifar10', '0618', 'eabb3fce8373cbeb412ced9a79a1e2f9c6c3689c', 'v0.0.379'),
('sepreresnet20_cifar100', '2831', 'fe7558e0ae554d39d8761f234e8328262ee31efd', 'v0.0.379'),
('sepreresnet20_svhn', '0324', '061daa587dd483744d5b60d2fd3b2750130dd8a1', 'v0.0.379'),
('sepreresnet56_cifar10', '0451', 'fc23e153ccfaddd52de61d77570a0befeee1e687', 'v0.0.379'),
('sepreresnet56_cifar100', '2305', 'c4bdc5d7bbaa0d9f6e2ffdf2abe4808ad26d0f66', 'v0.0.379'),
('sepreresnet56_svhn', '0271', 'c91e922f1b3d0ea634db8e467e9ab4a6b8dc7722', 'v0.0.379'),
('sepreresnet110_cifar10', '0454', '418daea9d2253a3e9fbe4eb80eb4dcc6f29d5925', 'v0.0.379'),
('sepreresnet110_cifar100', '2261', 'ed7d3c3e51ed2ea9a827ed942e131c78784813b7', 'v0.0.379'),
('sepreresnet110_svhn', '0259', '556909fd942d3a42e424215374b340680b705424', 'v0.0.379'),
('sepreresnet164bn_cifar10', '0373', 'ff353a2910f85db66d8afca0a4150176bcdc7a69', 'v0.0.379'),
('sepreresnet164bn_cifar100', '2005', 'df1163c4d9de72c53efc37758773cc943be7f055', 'v0.0.379'),
('sepreresnet164bn_svhn', '0256', 'f8dd4e06596841f0c7f9979fb566b9e57611522f', 'v0.0.379'),
('sepreresnet272bn_cifar10', '0339', '606d096422394857cb1f45ecd7eed13508158a60', 'v0.0.379'),
('sepreresnet272bn_cifar100', '1913', 'cb71511346e441cbd36bacc93c821e8b6101456a', 'v0.0.379'),
('sepreresnet272bn_svhn', '0249', '904d74a2622d870f8a2384f9e50a84276218acc3', 'v0.0.379'),
('sepreresnet542bn_cifar10', '0308', '652bc8846cfac7a2ec6625789531897339800202', 'v0.0.382'),
('sepreresnet542bn_cifar100', '1945', '9180f8632657bb8f7b6583e47d04ce85defa956c', 'v0.0.382'),
('sepreresnet542bn_svhn', '0247', '318a8325afbfbaa8a35d54cbd1fa7da668ef1389', 'v0.0.382'),
('pyramidnet110_a48_cifar10', '0372', 'eb185645cda89e0c3c47b11c4b2d14ff18fa0ae1', 'v0.0.184'),
('pyramidnet110_a48_cifar100', '2095', '95da1a209916b3cf4af7e8dc44374345a88c60f4', 'v0.0.186'),
('pyramidnet110_a48_svhn', '0247', 'd48bafbebaabe9a68e5924571752b3d7cd95d311', 'v0.0.281'),
('pyramidnet110_a84_cifar10', '0298', '7b835a3cf19794478d478aced63ca9e855c3ffeb', 'v0.0.185'),
('pyramidnet110_a84_cifar100', '1887', 'ff711084381f217f84646c676e4dcc90269dc516', 'v0.0.199'),
('pyramidnet110_a84_svhn', '0243', '971576c61cf30e02f13da616afc9848b2a609e0e', 'v0.0.392'),
('pyramidnet110_a270_cifar10', '0251', '31bdd9d51ec01388cbb2adfb9f822c942de3c4ff', 'v0.0.194'),
('pyramidnet110_a270_cifar100', '1710', '7417dd99069d6c8775454475968ae226b9d5ac83', 'v0.0.319'),
('pyramidnet110_a270_svhn', '0238', '3047a9bb7c92a09adf31590e3fe6c9bcd36c7a67', 'v0.0.393'),
('pyramidnet164_a270_bn_cifar10', '0242', 'daa2a402c1081323b8f2239f2201246953774e84', 'v0.0.264'),
('pyramidnet164_a270_bn_cifar100', '1670', '54d99c834bee0ed7402ba46e749e48182ad1599a', 'v0.0.312'),
('pyramidnet164_a270_bn_svhn', '0233', '42d4c03374f32645924fc091d599ef7b913e2d32', 'v0.0.396'),
('pyramidnet200_a240_bn_cifar10', '0244', '44433afdd2bc32c55dfb1e8347bc44d1c2bf82c7', 'v0.0.268'),
('pyramidnet200_a240_bn_cifar100', '1609', '087c02d6882e274054f44482060f193b9fc208bb', 'v0.0.317'),
('pyramidnet200_a240_bn_svhn', '0232', 'f9660c25f1bcff9d361aeca8fb3efaccdc0546e7', 'v0.0.397'),
('pyramidnet236_a220_bn_cifar10', '0247', 'daa91d74979c451ecdd8b59e4350382966f25831', 'v0.0.285'),
('pyramidnet236_a220_bn_cifar100', '1634', 'a45816ebe1d6a67468b78b7a93334a41aca1c64b', 'v0.0.312'),
('pyramidnet236_a220_bn_svhn', '0235', 'f74fe248b6189699174c90bc21e7949d3cca8130', 'v0.0.398'),
('pyramidnet272_a200_bn_cifar10', '0239', '586b1ecdc8b34b69dcae4ba57f71c24583cca9b1', 'v0.0.284'),
('pyramidnet272_a200_bn_cifar100', '1619', '98bc2f48da0f2c68bc5376c17b0aefc734a64881', 'v0.0.312'),
('pyramidnet272_a200_bn_svhn', '0240', '96f6e740dcdc917d776f6df855e3437c93d0da4f', 'v0.0.404'),
('densenet40_k12_cifar10', '0561', '8b8e819467a2e4c450e4ff72ced80582d0628b68', 'v0.0.193'),
('densenet40_k12_cifar100', '2490', 'd182c224d6df2e289eef944d54fea9fd04890961', 'v0.0.195'),
('densenet40_k12_svhn', '0305', 'ac0de84a1a905b768c66f0360f1fb9bd918833bf', 'v0.0.278'),
('densenet40_k12_bc_cifar10', '0643', '6dc86a2ea1d088f088462f5cbac06cc0f37348c0', 'v0.0.231'),
('densenet40_k12_bc_cifar100', '2841', '1e9db7651a21e807c363c9f366bd9e91ce2f296f', 'v0.0.232'),
('densenet40_k12_bc_svhn', '0320', '320760528b009864c68ff6c5b874e9f351ea7a07', 'v0.0.279'),
('densenet40_k24_bc_cifar10', '0452', '669c525548a4a2392c5e3c380936ad019f2be7f9', 'v0.0.220'),
('densenet40_k24_bc_cifar100', '2267', '411719c0177abf58eddaddd05511c86db0c9d548', 'v0.0.221'),
('densenet40_k24_bc_svhn', '0290', 'f4440d3b8c974c9e1014969f4d5832c6c90195d5', 'v0.0.280'),
('densenet40_k36_bc_cifar10', '0404', 'b1a4cc7e67db1ed8c5583a59dc178cc7dc2c572e', 'v0.0.224'),
('densenet40_k36_bc_cifar100', '2050', 'cde836fafec1e5d6c8ed69fd3cfe322e8e71ef1d', 'v0.0.225'),
('densenet40_k36_bc_svhn', '0260', '8c7db0a291a0797a8bc3c709bff7917bc41471cc', 'v0.0.311'),
('densenet100_k12_cifar10', '0366', '26089c6e70236e8f25359de6fda67b84425888ab', 'v0.0.205'),
('densenet100_k12_cifar100', '1964', '5e10cd830c06f6ab178e9dd876c83c754ca63f00', 'v0.0.206'),
('densenet100_k12_svhn', '0260', '57fde50e9f44edc0486b62a1144565bc77d5bdfe', 'v0.0.311'),
('densenet100_k24_cifar10', '0313', '397f0e39b517c05330221d4f3a9755eb5e561be1', 'v0.0.252'),
('densenet100_k24_cifar100', '1808', '1c0a8067283952709d8e09c774c3a404f51e0079', 'v0.0.318'),
('densenet100_k12_bc_cifar10', '0416', 'b9232829b13c3f3f2ea15f4be97f500b7912c3c2', 'v0.0.189'),
('densenet100_k12_bc_cifar100', '2119', '05a6f02772afda51a612f5b92aadf19ffb60eb72', 'v0.0.208'),
('densenet190_k40_bc_cifar10', '0252', '2896fa088aeaef36fcf395d404d97ff172d78943', 'v0.0.286'),
('densenet250_k24_bc_cifar10', '0267', 'f8f9d3052bae1fea7e33bb1ce143c38b4aa5622b', 'v0.0.290'),
('densenet250_k24_bc_cifar100', '1739', '09ac3e7d9fbe6b97b170bd838dac20ec144b4e49', 'v0.0.303'),
('xdensenet40_2_k24_bc_cifar10', '0531', 'b91a9dc35877c4285fe86f49953d1118f6b69e57', 'v0.0.226'),
('xdensenet40_2_k24_bc_cifar100', '2396', '0ce8f78ab9c6a4786829f816ae0615c7905f292c', 'v0.0.227'),
('xdensenet40_2_k24_bc_svhn', '0287', 'fd9b6def10f154378a76383cf023d7f2f5ae02ab', 'v0.0.306'),
('xdensenet40_2_k36_bc_cifar10', '0437', 'ed264a2060836c7440f0ccde57315e1ec6263ff0', 'v0.0.233'),
('xdensenet40_2_k36_bc_cifar100', '2165', '6f68f83dc31dea5237e6362e6c6cfeed48a8d9e3', 'v0.0.234'),
('xdensenet40_2_k36_bc_svhn', '0274', '540a69f13a6ce70bfef13657e70dfa414d966581', 'v0.0.306'),
('wrn16_10_cifar10', '0293', 'ce810d8a17a2deb73eddb5bec8709f93278bc53e', 'v0.0.166'),
('wrn16_10_cifar100', '1895', 'bef9809c845deb1b2bb0c9aaaa7c58bd97740504', 'v0.0.204'),
('wrn16_10_svhn', '0278', '5ab2a4edd5398a03d2e28db1b075bf0313ae5828', 'v0.0.271'),
('wrn28_10_cifar10', '0239', 'fe97dcd6d0dd8dda8e9e38e6cfa320cffb9955ce', 'v0.0.166'),
('wrn28_10_cifar100', '1788', '8c3fe8185d3af9cc3813fe376cab895f6780ac18', 'v0.0.320'),
('wrn28_10_svhn', '0271', 'd62b6bbaef7228706a67c2c8416681f97c6d4688', 'v0.0.276'),
('wrn40_8_cifar10', '0237', '8dc84ec730f35c4b8968a022bc045c0665410840', 'v0.0.166'),
('wrn40_8_cifar100', '1803', '0d18bfbff85951d88a881dc6a15ad46f56ea8c28', 'v0.0.321'),
('wrn40_8_svhn', '0254', 'dee59602c10e5d56bd9c168e8e8400792b9a8b08', 'v0.0.277'),
('wrn20_10_1bit_cifar10', '0326', 'e6140f8a5eacd5227e8748457b5ee9f5f519d2d5', 'v0.0.302'),
('wrn20_10_1bit_cifar100', '1904', '149860c829a812224dbf2086c8ce95c2eba322fe', 'v0.0.302'),
('wrn20_10_1bit_svhn', '0273', 'ffe96cb78cd304d5207fff0cf08835ba2a71f666', 'v0.0.302'),
('wrn20_10_32bit_cifar10', '0314', 'a18146e8b0f99a900c588eb8995547393c2d9d9e', 'v0.0.302'),
('wrn20_10_32bit_cifar100', '1812', '70d8972c7455297bc21fdbe4fc040c2f6b3593a3', 'v0.0.302'),
('wrn20_10_32bit_svhn', '0259', 'ce402a58887cbae3a38da1e845a1c1479a6d7213', 'v0.0.302'),
('ror3_56_cifar10', '0543', '44f0f47d2e1b609880ee1b623014c52a9276e2ea', 'v0.0.228'),
('ror3_56_cifar100', '2549', '34be6719cd128cfe60ba93ac6d250ac4c1acf0a5', 'v0.0.229'),
('ror3_56_svhn', '0269', '5a9ad66c8747151be1d2fb9bc854ae382039bdb9', 'v0.0.287'),
('ror3_110_cifar10', '0435', 'fb2a2b0499e4a4d92bdc1d6792bd5572256d5165', 'v0.0.235'),
('ror3_110_cifar100', '2364', 'd599e3a93cd960c8bfc5d05c721cd48fece5fa6f', 'v0.0.236'),
('ror3_110_svhn', '0257', '155380add8d351d2c12026d886a918f1fc3f9fd0', 'v0.0.287'),
('ror3_164_cifar10', '0393', 'de7b6dc60ad6a297bd55ab65b6d7b1225b0ef6d1', 'v0.0.294'),
('ror3_164_cifar100', '2234', 'd37483fccc7fc1a25ff90ef05ecf1b8eab3cc1c4', 'v0.0.294'),
('ror3_164_svhn', '0273', 'ff0d9af0d40ef204393ecc904b01a11aa63acc01', 'v0.0.294'),
('rir_cifar10', '0328', '414c3e6088ae1e83aa1a77c43e38f940c18a0ce2', 'v0.0.292'),
('rir_cifar100', '1923', 'de8ec24a232b94be88f4208153441f66098a681c', 'v0.0.292'),
('rir_svhn', '0268', '12fcbd3bfc6b4165e9b23f3339a1b751b4b8f681', 'v0.0.292'),
('shakeshakeresnet20_2x16d_cifar10', '0515', 'ef71ec0d5ef928ef8654294114a013895abe3f9a', 'v0.0.215'),
('shakeshakeresnet20_2x16d_cifar100', '2922', '4d07f14234b1c796b3c1dfb24d4a3220a1b6b293', 'v0.0.247'),
('shakeshakeresnet20_2x16d_svhn', '0317', 'a693ec24fb8fe2c9f15bcc6b1050943c0c5d595a', 'v0.0.295'),
('shakeshakeresnet26_2x32d_cifar10', '0317', 'ecd1f8337cc90b5378b4217fb2591f2ed0f02bdf', 'v0.0.217'),
('shakeshakeresnet26_2x32d_cifar100', '1880', 'b47e371f60c9fed9eaac960568783fb6f83a362f', 'v0.0.222'),
('shakeshakeresnet26_2x32d_svhn', '0262', 'c1b8099ece97e17ce85213e4ecc6e50a064050cf', 'v0.0.295'),
('diaresnet20_cifar10', '0622', '5e1a02bf2347d48651a5feabe97f7caf215bacc9', 'v0.0.340'),
('diaresnet20_cifar100', '2771', '28aa1a18d91334e274d3157114fc5c72e47c6c65', 'v0.0.342'),
('diaresnet20_svhn', '0323', 'b8ee92c9d86de6a6adc80988518fe0544759ca4f', 'v0.0.342'),
('diaresnet56_cifar10', '0505', '8ac8680448b2999bd1e03eed60373ea78eba9a44', 'v0.0.340'),
('diaresnet56_cifar100', '2435', '19085975afc7ee902a6d663eb371554c9519b467', 'v0.0.342'),
('diaresnet56_svhn', '0268', 'bd2ec7558697aff1e0fd229d3e933a08c4c302e9', 'v0.0.342'),
('diaresnet110_cifar10', '0410', '0c00a7daec69b57ab41d4a55e1026da33ecf4539', 'v0.0.340'),
('diaresnet110_cifar100', '2211', '7096ddb3a393ad28b27ece19263c203068a11b6d', 'v0.0.342'),
('diaresnet110_svhn', '0247', '635e42cfac6ed67e15b8a5526c8232f768d11201', 'v0.0.342'),
('diaresnet164bn_cifar10', '0350', 'd31f2ebce3acb419b07dc4d298018ffea2599fea', 'v0.0.340'),
('diaresnet164bn_cifar100', '1953', 'b1c474d27de3a291a45856a3e3d256b7fda90dd0', 'v0.0.342'),
('diaresnet164bn_svhn', '0244', '0b8f67132b3911e6328733b666bf6a0fed133eeb', 'v0.0.342'),
('diapreresnet20_cifar10', '0642', '14a1eb85c6346c81336b490cc49f2e6b809c193e', 'v0.0.343'),
('diapreresnet20_cifar100', '2837', 'f7675c09ca5f742376a102e3c8c5156aea4e24b9', 'v0.0.343'),
('diapreresnet20_svhn', '0303', 'dc3e3a453ffc8aff7d014bc15867db4ce2d8e1e9', 'v0.0.343'),
('diapreresnet56_cifar10', '0483', '41cae958be1bec3f839126cd167051de6a981d0a', 'v0.0.343'),
('diapreresnet56_cifar100', '2505', '5d357985236c021ab965101b94980cdc4722a70d', 'v0.0.343'),
('diapreresnet56_svhn', '0280', '537ebc66fe32f9bb6fb6bb8f9ac6402f8ec93e09', 'v0.0.343'),
('diapreresnet110_cifar10', '0425', '5638501600355b8b195179fb2be5d5989e93b0e0', 'v0.0.343'),
('diapreresnet110_cifar100', '2269', 'c993cc296c39bc9c8c0fc6115bfe6c7d720a0903', 'v0.0.343'),
('diapreresnet110_svhn', '0242', 'a156cfb58ffda89c0e87cd8aef82f56f79b40ea5', 'v0.0.343'),
('diapreresnet164bn_cifar10', '0356', '6ec898c89c66eb32b0e42b78a027af4920b24366', 'v0.0.343'),
('diapreresnet164bn_cifar100', '1999', '00872f989c33321f7938a40c0fd9f44669c4c483', 'v0.0.343'),
('diapreresnet164bn_svhn', '0256', '134048810bd2e12dc68035d4ecad6af525639db0', 'v0.0.343'),
('resnet10_cub', '2777', '4525b5932665698b3f4551dde99d22ce03878172', 'v0.0.335'),
('resnet12_cub', '2727', 'c15248832d2fe88c58fb603df3925e09b3d797e7', 'v0.0.336'),
('resnet14_cub', '2477', '5051bbc659c0303c1860114f1a32a18942de9099', 'v0.0.337'),
('resnet16_cub', '2365', 'b831356c696db80fec8deb2381875f37bf60dd93', 'v0.0.338'),
('resnet18_cub', '2333', '200d8b9c48baf073a4c2ea0cbba4d7f81288e684', 'v0.0.344'),
('resnet26_cub', '2316', '599ab467f396e979028f2ae5d65330949c9ddc86', 'v0.0.345'),
('seresnet10_cub', '2772', 'f52526ec21bbb534a6d51be42bdb5322fbda919b', 'v0.0.361'),
('seresnet12_cub', '2651', '5c0e7f835c65d1f2f85048d0169788377490b819', 'v0.0.361'),
('seresnet14_cub', '2416', 'a4cda9012ec2380fa74f3d74879f0d206fcaf5b5', 'v0.0.361'),
('seresnet16_cub', '2332', '43a819b7e226d65aa77a4c90fdb7c70eb5093505', 'v0.0.361'),
('seresnet18_cub', '2352', '414fa2775de28ce3a1a0bc142ab674fa3a6638e3', 'v0.0.361'),
('seresnet26_cub', '2299', '5aa0a7d1ef9c33f8dbf3ff1cb1a1a855627163f4', 'v0.0.361'),
('mobilenet_w1_cub', '2377', '8428471f4ae08709b71ff2f69cf1a6fd286004c9', 'v0.0.346'),
('proxylessnas_mobile_cub', '2266', 'e4b5098a17425c97740fc564460aa95d9eb2a41e', 'v0.0.347'),
('ntsnet_cub', '1277', 'f6f330abfabcc2ea17a8d4b8977a6ea322ddf532', 'v0.0.334'),
('pspnet_resnetd101b_voc', '8144', 'c22f021948461a7b7ab1ef1265a7948762770c83', 'v0.0.297'),
('pspnet_resnetd50b_ade20k', '3687', '13f22137d7dd06c6de2ffc47e6ed33403d3dd2cf', 'v0.0.297'),
('pspnet_resnetd101b_ade20k', '3797', '115d62bf66477221b83337208aefe0f2f0266da2', 'v0.0.297'),
('pspnet_resnetd101b_cityscapes', '7172', '0a6efb497bd4fc763d27e2121211e06f72ada7ed', 'v0.0.297'),
('pspnet_resnetd101b_coco', '6741', 'c8b13be65cb43402fce8bae945f6e0d0a3246b92', 'v0.0.297'),
('deeplabv3_resnetd101b_voc', '8024', 'fd8bf74ffc96c97b30bcd3b6ce194a2daed68098', 'v0.0.298'),
('deeplabv3_resnetd152b_voc', '8120', 'f2dae198b3cdc41920ea04f674b665987c68d7dc', 'v0.0.298'),
('deeplabv3_resnetd50b_ade20k', '3713', 'bddbb458e362e18f5812c2307b322840394314bc', 'v0.0.298'),
('deeplabv3_resnetd101b_ade20k', '3784', '977446a5fb32b33f168f2240fb6b7ef9f561fc1e', 'v0.0.298'),
('deeplabv3_resnetd101b_coco', '6773', 'e59c1d8f7ed5bcb83f927d2820580a2f4970e46f', 'v0.0.298'),
('deeplabv3_resnetd152b_coco', '6899', '7e946d7a63ed255dd38afacebb0a0525e735da64', 'v0.0.298'),
('fcn8sd_resnetd101b_voc', '8040', '66edc0b073f0dec66c18bb163c7d6de1ddbc32a3', 'v0.0.299'),
('fcn8sd_resnetd50b_ade20k', '3339', 'e1dad8a15c2a1be1138bd3ec51ba1b100bb8d9c9', 'v0.0.299'),
('fcn8sd_resnetd101b_ade20k', '3588', '30d05ca42392a164ea7c93a9cbd7f33911d3c1af', 'v0.0.299'),
('fcn8sd_resnetd101b_coco', '6011', 'ebe2ad0bc1de5b4cecade61d17d269aa8bf6df7f', 'v0.0.299'),
]}
imgclsmob_repo_url = 'https://github.com/osmr/imgclsmob'
def get_model_name_suffix_data(model_name):
if model_name not in _model_sha1:
raise ValueError("Pretrained model for {name} is not available.".format(name=model_name))
error, sha1_hash, repo_release_tag = _model_sha1[model_name]
return error, sha1_hash, repo_release_tag
def get_model_file(model_name,
local_model_store_dir_path=os.path.join("~", ".torch", "models")):
"""
Return location for the pretrained on local file system. This function will download from online model zoo when
model cannot be found or has mismatch. The root directory will be created if it doesn't exist.
Parameters
----------
model_name : str
Name of the model.
local_model_store_dir_path : str, default $TORCH_HOME/models
Location for keeping the model parameters.
Returns
-------
file_path
Path to the requested pretrained model file.
"""
error, sha1_hash, repo_release_tag = get_model_name_suffix_data(model_name)
short_sha1 = sha1_hash[:8]
file_name = "{name}-{error}-{short_sha1}.pth".format(
name=model_name,
error=error,
short_sha1=short_sha1)
local_model_store_dir_path = os.path.expanduser(local_model_store_dir_path)
file_path = os.path.join(local_model_store_dir_path, file_name)
if os.path.exists(file_path):
if _check_sha1(file_path, sha1_hash):
return file_path
else:
logging.warning("Mismatch in the content of model file detected. Downloading again.")
else:
logging.info("Model file not found. Downloading to {}.".format(file_path))
if not os.path.exists(local_model_store_dir_path):
os.makedirs(local_model_store_dir_path)
zip_file_path = file_path + ".zip"
_download(
url="{repo_url}/releases/download/{repo_release_tag}/{file_name}.zip".format(
repo_url=imgclsmob_repo_url,
repo_release_tag=repo_release_tag,
file_name=file_name),
path=zip_file_path,
overwrite=True)
with zipfile.ZipFile(zip_file_path) as zf:
zf.extractall(local_model_store_dir_path)
os.remove(zip_file_path)
if _check_sha1(file_path, sha1_hash):
return file_path
else:
raise ValueError("Downloaded file has different hash. Please try again.")
def _download(url, path=None, overwrite=False, sha1_hash=None, retries=5, verify_ssl=True):
"""
Download an given URL
Parameters
----------
url : str
URL to download
path : str, optional
Destination path to store downloaded file. By default stores to the
current directory with same name as in url.
overwrite : bool, optional
Whether to overwrite destination file if already exists.
sha1_hash : str, optional
Expected sha1 hash in hexadecimal digits. Will ignore existing file when hash is specified
but doesn't match.
retries : integer, default 5
The number of times to attempt the download in case of failure or non 200 return codes
verify_ssl : bool, default True
Verify SSL certificates.
Returns
-------
str
The file path of the downloaded file.
"""
import warnings
try:
import requests
except ImportError:
class requests_failed_to_import(object):
pass
requests = requests_failed_to_import
if path is None:
fname = url.split("/")[-1]
# Empty filenames are invalid
assert fname, "Can't construct file-name from this URL. " \
"Please set the `path` option manually."
else:
path = os.path.expanduser(path)
if os.path.isdir(path):
fname = os.path.join(path, url.split('/')[-1])
else:
fname = path
assert retries >= 0, "Number of retries should be at least 0"
if not verify_ssl:
warnings.warn(
"Unverified HTTPS request is being made (verify_ssl=False). "
"Adding certificate verification is strongly advised.")
if overwrite or not os.path.exists(fname) or (sha1_hash and not _check_sha1(fname, sha1_hash)):
dirname = os.path.dirname(os.path.abspath(os.path.expanduser(fname)))
if not os.path.exists(dirname):
os.makedirs(dirname)
while retries + 1 > 0:
# Disable pyling too broad Exception
# pylint: disable=W0703
try:
print("Downloading {} from {}...".format(fname, url))
r = requests.get(url, stream=True, verify=verify_ssl)
if r.status_code != 200:
raise RuntimeError("Failed downloading url {}".format(url))
with open(fname, "wb") as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
if sha1_hash and not _check_sha1(fname, sha1_hash):
raise UserWarning("File {} is downloaded but the content hash does not match."
" The repo may be outdated or download may be incomplete. "
"If the `repo_url` is overridden, consider switching to "
"the default repo.".format(fname))
break
except Exception as e:
retries -= 1
if retries <= 0:
raise e
else:
print("download failed, retrying, {} attempt{} left"
.format(retries, "s" if retries > 1 else ""))
return fname
def _check_sha1(file_name, sha1_hash):
"""
Check whether the sha1 hash of the file content matches the expected hash.
Parameters
----------
file_name : str
Path to the file.
sha1_hash : str
Expected sha1 hash in hexadecimal digits.
Returns
-------
bool
Whether the file content matches the expected hash.
"""
sha1 = hashlib.sha1()
with open(file_name, "rb") as f:
while True:
data = f.read(1048576)
if not data:
break
sha1.update(data)
return sha1.hexdigest() == sha1_hash
def load_model(net,
file_path,
ignore_extra=True):
"""
Load model state dictionary from a file.
Parameters
----------
net : Module
Network in which weights are loaded.
file_path : str
Path to the file.
ignore_extra : bool, default True
Whether to silently ignore parameters from the file that are not present in this Module.
"""
import torch
if ignore_extra:
pretrained_state = torch.load(file_path)
model_dict = net.state_dict()
pretrained_state = {k: v for k, v in pretrained_state.items() if k in model_dict}
net.load_state_dict(pretrained_state)
else:
net.load_state_dict(torch.load(file_path))
def download_model(net,
model_name,
local_model_store_dir_path=os.path.join("~", ".torch", "models"),
ignore_extra=True):
"""
Load model state dictionary from a file with downloading it if necessary.
Parameters
----------
net : Module
Network in which weights are loaded.
model_name : str
Name of the model.
local_model_store_dir_path : str, default $TORCH_HOME/models
Location for keeping the model parameters.
ignore_extra : bool, default True
Whether to silently ignore parameters from the file that are not present in this Module.
"""
load_model(
net=net,
file_path=get_model_file(
model_name=model_name,
local_model_store_dir_path=local_model_store_dir_path),
ignore_extra=ignore_extra)
def calc_num_params(net):
"""
Calculate the count of trainable parameters for a model.
Parameters
----------
net : Module
Analyzed model.
"""
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
| 49,720 | 68.734923 | 115 | py |
null | qimera-main/pytorchcv/models/msdnet.py | """
MSDNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'Multi-Scale Dense Networks for Resource Efficient Image Classification,'
https://arxiv.org/abs/1703.09844.
"""
__all__ = ['MSDNet', 'msdnet22', 'MultiOutputSequential', 'MSDFeatureBlock']
import os
import math
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, conv3x3_block
from .resnet import ResInitBlock
class MultiOutputSequential(nn.Sequential):
"""
A sequential container for modules. Modules will be executed in the order they are added. Output value contains
results from all modules.
"""
def __init__(self, *args):
super(MultiOutputSequential, self).__init__(*args)
def forward(self, x):
outs = []
for module in self._modules.values():
x = module(x)
outs.append(x)
return outs
class MultiBlockSequential(nn.Sequential):
"""
A sequential container for modules. Modules will be executed in the order they are added. Input is a list with
length equal to number of modules.
"""
def __init__(self, *args):
super(MultiBlockSequential, self).__init__(*args)
def forward(self, x):
outs = []
for module, x_i in zip(self._modules.values(), x):
y = module(x_i)
outs.append(y)
return outs
class MSDBaseBlock(nn.Module):
"""
MSDNet base block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
use_bottleneck : bool
Whether to use a bottleneck.
bottleneck_factor : int
Bottleneck factor.
"""
def __init__(self,
in_channels,
out_channels,
stride,
use_bottleneck,
bottleneck_factor):
super(MSDBaseBlock, self).__init__()
self.use_bottleneck = use_bottleneck
mid_channels = min(in_channels, bottleneck_factor * out_channels) if use_bottleneck else in_channels
if self.use_bottleneck:
self.bn_conv = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels)
self.conv = conv3x3_block(
in_channels=mid_channels,
out_channels=out_channels,
stride=stride)
def forward(self, x):
if self.use_bottleneck:
x = self.bn_conv(x)
x = self.conv(x)
return x
class MSDFirstScaleBlock(nn.Module):
"""
MSDNet first scale dense block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
use_bottleneck : bool
Whether to use a bottleneck.
bottleneck_factor : int
Bottleneck factor.
"""
def __init__(self,
in_channels,
out_channels,
use_bottleneck,
bottleneck_factor):
super(MSDFirstScaleBlock, self).__init__()
assert (out_channels > in_channels)
inc_channels = out_channels - in_channels
self.block = MSDBaseBlock(
in_channels=in_channels,
out_channels=inc_channels,
stride=1,
use_bottleneck=use_bottleneck,
bottleneck_factor=bottleneck_factor)
def forward(self, x):
y = self.block(x)
y = torch.cat((x, y), dim=1)
return y
class MSDScaleBlock(nn.Module):
"""
MSDNet ordinary scale dense block.
Parameters:
----------
in_channels_prev : int
Number of input channels for the previous scale.
in_channels : int
Number of input channels for the current scale.
out_channels : int
Number of output channels.
use_bottleneck : bool
Whether to use a bottleneck.
bottleneck_factor_prev : int
Bottleneck factor for the previous scale.
bottleneck_factor : int
Bottleneck factor for the current scale.
"""
def __init__(self,
in_channels_prev,
in_channels,
out_channels,
use_bottleneck,
bottleneck_factor_prev,
bottleneck_factor):
super(MSDScaleBlock, self).__init__()
assert (out_channels > in_channels)
assert (out_channels % 2 == 0)
inc_channels = out_channels - in_channels
mid_channels = inc_channels // 2
self.down_block = MSDBaseBlock(
in_channels=in_channels_prev,
out_channels=mid_channels,
stride=2,
use_bottleneck=use_bottleneck,
bottleneck_factor=bottleneck_factor_prev)
self.curr_block = MSDBaseBlock(
in_channels=in_channels,
out_channels=mid_channels,
stride=1,
use_bottleneck=use_bottleneck,
bottleneck_factor=bottleneck_factor)
def forward(self, x_prev, x):
y_prev = self.down_block(x_prev)
y = self.curr_block(x)
x = torch.cat((x, y_prev, y), dim=1)
return x
class MSDInitLayer(nn.Module):
"""
MSDNet initial (so-called first) layer.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : list/tuple of int
Number of output channels for each scale.
"""
def __init__(self,
in_channels,
out_channels):
super(MSDInitLayer, self).__init__()
self.scale_blocks = MultiOutputSequential()
for i, out_channels_per_scale in enumerate(out_channels):
if i == 0:
self.scale_blocks.add_module('scale_block{}'.format(i + 1), ResInitBlock(
in_channels=in_channels,
out_channels=out_channels_per_scale))
else:
self.scale_blocks.add_module('scale_block{}'.format(i + 1), conv3x3_block(
in_channels=in_channels,
out_channels=out_channels_per_scale,
stride=2))
in_channels = out_channels_per_scale
def forward(self, x):
y = self.scale_blocks(x)
return y
class MSDLayer(nn.Module):
"""
MSDNet ordinary layer.
Parameters:
----------
in_channels : list/tuple of int
Number of input channels for each input scale.
out_channels : list/tuple of int
Number of output channels for each output scale.
use_bottleneck : bool
Whether to use a bottleneck.
bottleneck_factors : list/tuple of int
Bottleneck factor for each input scale.
"""
def __init__(self,
in_channels,
out_channels,
use_bottleneck,
bottleneck_factors):
super(MSDLayer, self).__init__()
in_scales = len(in_channels)
out_scales = len(out_channels)
self.dec_scales = in_scales - out_scales
assert (self.dec_scales >= 0)
self.scale_blocks = nn.Sequential()
for i in range(out_scales):
if (i == 0) and (self.dec_scales == 0):
self.scale_blocks.add_module('scale_block{}'.format(i + 1), MSDFirstScaleBlock(
in_channels=in_channels[self.dec_scales + i],
out_channels=out_channels[i],
use_bottleneck=use_bottleneck,
bottleneck_factor=bottleneck_factors[self.dec_scales + i]))
else:
self.scale_blocks.add_module('scale_block{}'.format(i + 1), MSDScaleBlock(
in_channels_prev=in_channels[self.dec_scales + i - 1],
in_channels=in_channels[self.dec_scales + i],
out_channels=out_channels[i],
use_bottleneck=use_bottleneck,
bottleneck_factor_prev=bottleneck_factors[self.dec_scales + i - 1],
bottleneck_factor=bottleneck_factors[self.dec_scales + i]))
def forward(self, x):
outs = []
for i in range(len(self.scale_blocks)):
if (i == 0) and (self.dec_scales == 0):
y = self.scale_blocks[i](x[i])
else:
y = self.scale_blocks[i](
x_prev=x[self.dec_scales + i - 1],
x=x[self.dec_scales + i])
outs.append(y)
return outs
class MSDTransitionLayer(nn.Module):
"""
MSDNet transition layer.
Parameters:
----------
in_channels : list/tuple of int
Number of input channels for each scale.
out_channels : list/tuple of int
Number of output channels for each scale.
"""
def __init__(self,
in_channels,
out_channels):
super(MSDTransitionLayer, self).__init__()
assert (len(in_channels) == len(out_channels))
self.scale_blocks = MultiBlockSequential()
for i in range(len(out_channels)):
self.scale_blocks.add_module('scale_block{}'.format(i + 1), conv1x1_block(
in_channels=in_channels[i],
out_channels=out_channels[i]))
def forward(self, x):
y = self.scale_blocks(x)
return y
class MSDFeatureBlock(nn.Module):
"""
MSDNet feature block (stage of cascade, so-called block).
Parameters:
----------
in_channels : list of list of int
Number of input channels for each layer and for each input scale.
out_channels : list of list of int
Number of output channels for each layer and for each output scale.
use_bottleneck : bool
Whether to use a bottleneck.
bottleneck_factors : list of list of int
Bottleneck factor for each layer and for each input scale.
"""
def __init__(self,
in_channels,
out_channels,
use_bottleneck,
bottleneck_factors):
super(MSDFeatureBlock, self).__init__()
self.blocks = nn.Sequential()
for i, out_channels_per_layer in enumerate(out_channels):
if len(bottleneck_factors[i]) == 0:
self.blocks.add_module('trans{}'.format(i + 1), MSDTransitionLayer(
in_channels=in_channels,
out_channels=out_channels_per_layer))
else:
self.blocks.add_module('layer{}'.format(i + 1), MSDLayer(
in_channels=in_channels,
out_channels=out_channels_per_layer,
use_bottleneck=use_bottleneck,
bottleneck_factors=bottleneck_factors[i]))
in_channels = out_channels_per_layer
def forward(self, x):
x = self.blocks(x)
return x
class MSDClassifier(nn.Module):
"""
MSDNet classifier.
Parameters:
----------
in_channels : int
Number of input channels.
num_classes : int
Number of classification classes.
"""
def __init__(self,
in_channels,
num_classes):
super(MSDClassifier, self).__init__()
self.features = nn.Sequential()
self.features.add_module("conv1", conv3x3_block(
in_channels=in_channels,
out_channels=in_channels,
stride=2))
self.features.add_module("conv2", conv3x3_block(
in_channels=in_channels,
out_channels=in_channels,
stride=2))
self.features.add_module("pool", nn.AvgPool2d(
kernel_size=2,
stride=2))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
class MSDNet(nn.Module):
"""
MSDNet model from 'Multi-Scale Dense Networks for Resource Efficient Image Classification,'
https://arxiv.org/abs/1703.09844.
Parameters:
----------
channels : list of list of list of int
Number of output channels for each unit.
init_layer_channels : list of int
Number of output channels for the initial layer.
num_feature_blocks : int
Number of subnets.
use_bottleneck : bool
Whether to use a bottleneck.
bottleneck_factors : list of list of int
Bottleneck factor for each layers and for each input scale.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_layer_channels,
num_feature_blocks,
use_bottleneck,
bottleneck_factors,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(MSDNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.init_layer = MSDInitLayer(
in_channels=in_channels,
out_channels=init_layer_channels)
in_channels = init_layer_channels
self.feature_blocks = nn.Sequential()
self.classifiers = nn.Sequential()
for i in range(num_feature_blocks):
self.feature_blocks.add_module("block{}".format(i + 1), MSDFeatureBlock(
in_channels=in_channels,
out_channels=channels[i],
use_bottleneck=use_bottleneck,
bottleneck_factors=bottleneck_factors[i]))
in_channels = channels[i][-1]
self.classifiers.add_module("classifier{}".format(i + 1), MSDClassifier(
in_channels=in_channels[-1],
num_classes=num_classes))
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x, only_last=True):
x = self.init_layer(x)
outs = []
for feature_block, classifier in zip(self.feature_blocks, self.classifiers):
x = feature_block(x)
y = classifier(x[-1])
outs.append(y)
if only_last:
return outs[-1]
else:
return outs
def get_msdnet(blocks,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create MSDNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
assert (blocks == 22)
num_scales = 4
num_feature_blocks = 10
base = 4
step = 2
reduction_rate = 0.5
growth = 6
growth_factor = [1, 2, 4, 4]
use_bottleneck = True
bottleneck_factor_per_scales = [1, 2, 4, 4]
assert (reduction_rate > 0.0)
init_layer_channels = [64 * c for c in growth_factor[:num_scales]]
step_mode = "even"
layers_per_subnets = [base]
for i in range(num_feature_blocks - 1):
layers_per_subnets.append(step if step_mode == 'even' else step * i + 1)
total_layers = sum(layers_per_subnets)
interval = math.ceil(total_layers / num_scales)
global_layer_ind = 0
channels = []
bottleneck_factors = []
in_channels_tmp = init_layer_channels
in_scales = num_scales
for i in range(num_feature_blocks):
layers_per_subnet = layers_per_subnets[i]
scales_i = []
channels_i = []
bottleneck_factors_i = []
for j in range(layers_per_subnet):
out_scales = int(num_scales - math.floor(global_layer_ind / interval))
global_layer_ind += 1
scales_i += [out_scales]
scale_offset = num_scales - out_scales
in_dec_scales = num_scales - len(in_channels_tmp)
out_channels = [in_channels_tmp[scale_offset - in_dec_scales + k] + growth * growth_factor[scale_offset + k]
for k in range(out_scales)]
in_dec_scales = num_scales - len(in_channels_tmp)
bottleneck_factors_ij = bottleneck_factor_per_scales[in_dec_scales:][:len(in_channels_tmp)]
in_channels_tmp = out_channels
channels_i += [out_channels]
bottleneck_factors_i += [bottleneck_factors_ij]
if in_scales > out_scales:
assert (in_channels_tmp[0] % growth_factor[scale_offset] == 0)
out_channels1 = int(math.floor(in_channels_tmp[0] / growth_factor[scale_offset] * reduction_rate))
out_channels = [out_channels1 * growth_factor[scale_offset + k] for k in range(out_scales)]
in_channels_tmp = out_channels
channels_i += [out_channels]
bottleneck_factors_i += [[]]
in_scales = out_scales
in_scales = scales_i[-1]
channels += [channels_i]
bottleneck_factors += [bottleneck_factors_i]
net = MSDNet(
channels=channels,
init_layer_channels=init_layer_channels,
num_feature_blocks=num_feature_blocks,
use_bottleneck=use_bottleneck,
bottleneck_factors=bottleneck_factors,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def msdnet22(**kwargs):
"""
MSDNet-22 model from 'Multi-Scale Dense Networks for Resource Efficient Image Classification,'
https://arxiv.org/abs/1703.09844.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_msdnet(blocks=22, model_name="msdnet22", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
msdnet22,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != msdnet22 or weight_count == 20106676)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 19,529 | 30.65316 | 120 | py |
null | qimera-main/pytorchcv/models/msdnet_cifar10.py | """
MSDNet for CIFAR-10, implemented in PyTorch.
Original paper: 'Multi-Scale Dense Networks for Resource Efficient Image Classification,'
https://arxiv.org/abs/1703.09844.
"""
__all__ = ['CIFAR10MSDNet', 'msdnet22_cifar10']
import os
import math
import torch.nn as nn
import torch.nn.init as init
from .common import conv3x3_block
from .msdnet import MultiOutputSequential, MSDFeatureBlock
class CIFAR10MSDInitLayer(nn.Module):
"""
MSDNet initial (so-called first) layer for CIFAR-10.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : list/tuple of int
Number of output channels for each scale.
"""
def __init__(self,
in_channels,
out_channels):
super(CIFAR10MSDInitLayer, self).__init__()
self.scale_blocks = MultiOutputSequential()
for i, out_channels_per_scale in enumerate(out_channels):
stride = 1 if i == 0 else 2
self.scale_blocks.add_module('scale_block{}'.format(i + 1), conv3x3_block(
in_channels=in_channels,
out_channels=out_channels_per_scale,
stride=stride))
in_channels = out_channels_per_scale
def forward(self, x):
y = self.scale_blocks(x)
return y
class CIFAR10MSDClassifier(nn.Module):
"""
MSDNet classifier for CIFAR-10.
Parameters:
----------
in_channels : int
Number of input channels.
num_classes : int
Number of classification classes.
"""
def __init__(self,
in_channels,
num_classes):
super(CIFAR10MSDClassifier, self).__init__()
mid_channels = 128
self.features = nn.Sequential()
self.features.add_module("conv1", conv3x3_block(
in_channels=in_channels,
out_channels=mid_channels,
stride=2))
self.features.add_module("conv2", conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
stride=2))
self.features.add_module("pool", nn.AvgPool2d(
kernel_size=2,
stride=2))
self.output = nn.Linear(
in_features=mid_channels,
out_features=num_classes)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
class CIFAR10MSDNet(nn.Module):
"""
MSDNet model for CIFAR-10 from 'Multi-Scale Dense Networks for Resource Efficient Image Classification,'
https://arxiv.org/abs/1703.09844.
Parameters:
----------
channels : list of list of list of int
Number of output channels for each unit.
init_layer_channels : list of int
Number of output channels for the initial layer.
num_feature_blocks : int
Number of subnets.
use_bottleneck : bool
Whether to use a bottleneck.
bottleneck_factors : list of list of int
Bottleneck factor for each layers and for each input scale.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
num_classes : int, default 10
Number of classification classes.
"""
def __init__(self,
channels,
init_layer_channels,
num_feature_blocks,
use_bottleneck,
bottleneck_factors,
in_channels=3,
in_size=(32, 32),
num_classes=10):
super(CIFAR10MSDNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.init_layer = CIFAR10MSDInitLayer(
in_channels=in_channels,
out_channels=init_layer_channels)
in_channels = init_layer_channels
self.feature_blocks = nn.Sequential()
self.classifiers = nn.Sequential()
for i in range(num_feature_blocks):
self.feature_blocks.add_module("block{}".format(i + 1), MSDFeatureBlock(
in_channels=in_channels,
out_channels=channels[i],
use_bottleneck=use_bottleneck,
bottleneck_factors=bottleneck_factors[i]))
in_channels = channels[i][-1]
self.classifiers.add_module("classifier{}".format(i + 1), CIFAR10MSDClassifier(
in_channels=in_channels[-1],
num_classes=num_classes))
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x, only_last=True):
x = self.init_layer(x)
outs = []
for feature_block, classifier in zip(self.feature_blocks, self.classifiers):
x = feature_block(x)
y = classifier(x[-1])
outs.append(y)
if only_last:
return outs[-1]
else:
return outs
def get_msdnet_cifar10(blocks,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create MSDNet model for CIFAR-10 with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
assert (blocks == 22)
num_scales = 3
num_feature_blocks = 10
base = 4
step = 2
reduction_rate = 0.5
growth = 6
growth_factor = [1, 2, 4, 4]
use_bottleneck = True
bottleneck_factor_per_scales = [1, 2, 4, 4]
assert (reduction_rate > 0.0)
init_layer_channels = [16 * c for c in growth_factor[:num_scales]]
step_mode = "even"
layers_per_subnets = [base]
for i in range(num_feature_blocks - 1):
layers_per_subnets.append(step if step_mode == 'even' else step * i + 1)
total_layers = sum(layers_per_subnets)
interval = math.ceil(total_layers / num_scales)
global_layer_ind = 0
channels = []
bottleneck_factors = []
in_channels_tmp = init_layer_channels
in_scales = num_scales
for i in range(num_feature_blocks):
layers_per_subnet = layers_per_subnets[i]
scales_i = []
channels_i = []
bottleneck_factors_i = []
for j in range(layers_per_subnet):
out_scales = int(num_scales - math.floor(global_layer_ind / interval))
global_layer_ind += 1
scales_i += [out_scales]
scale_offset = num_scales - out_scales
in_dec_scales = num_scales - len(in_channels_tmp)
out_channels = [in_channels_tmp[scale_offset - in_dec_scales + k] + growth * growth_factor[scale_offset + k]
for k in range(out_scales)]
in_dec_scales = num_scales - len(in_channels_tmp)
bottleneck_factors_ij = bottleneck_factor_per_scales[in_dec_scales:][:len(in_channels_tmp)]
in_channels_tmp = out_channels
channels_i += [out_channels]
bottleneck_factors_i += [bottleneck_factors_ij]
if in_scales > out_scales:
assert (in_channels_tmp[0] % growth_factor[scale_offset] == 0)
out_channels1 = int(math.floor(in_channels_tmp[0] / growth_factor[scale_offset] * reduction_rate))
out_channels = [out_channels1 * growth_factor[scale_offset + k] for k in range(out_scales)]
in_channels_tmp = out_channels
channels_i += [out_channels]
bottleneck_factors_i += [[]]
in_scales = out_scales
in_scales = scales_i[-1]
channels += [channels_i]
bottleneck_factors += [bottleneck_factors_i]
net = CIFAR10MSDNet(
channels=channels,
init_layer_channels=init_layer_channels,
num_feature_blocks=num_feature_blocks,
use_bottleneck=use_bottleneck,
bottleneck_factors=bottleneck_factors,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def msdnet22_cifar10(**kwargs):
"""
MSDNet-22 model for CIFAR-10 from 'Multi-Scale Dense Networks for Resource Efficient Image Classification,'
https://arxiv.org/abs/1703.09844.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_msdnet_cifar10(blocks=22, model_name="msdnet22_cifar10", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
msdnet22_cifar10,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != msdnet22_cifar10 or weight_count == 4839544) # 5440864
x = torch.randn(1, 3, 32, 32)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 10))
if __name__ == "__main__":
_test()
| 10,172 | 30.691589 | 120 | py |
null | qimera-main/pytorchcv/models/nasnet.py | """
NASNet-A for ImageNet-1K, implemented in PyTorch.
Original paper: 'Learning Transferable Architectures for Scalable Image Recognition,'
https://arxiv.org/abs/1707.07012.
"""
__all__ = ['NASNet', 'nasnet_4a1056', 'nasnet_6a4032', 'nasnet_dual_path_sequential']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1, DualPathSequential
class NasDualPathScheme(object):
"""
NASNet specific scheme of dual path response for a module in a DualPathSequential module.
Parameters:
----------
can_skip_input : bool
Whether can skip input for some modules.
"""
def __init__(self,
can_skip_input):
super(NasDualPathScheme, self).__init__()
self.can_skip_input = can_skip_input
"""
Scheme function.
Parameters:
----------
module : nn.Module
A module.
x : Tensor
Current processed tensor.
x_prev : Tensor
Previous processed tensor.
Returns
-------
x_next : Tensor
Next processed tensor.
x : Tensor
Current processed tensor.
"""
def __call__(self,
module,
x,
x_prev):
x_next = module(x, x_prev)
if type(x_next) == tuple:
x_next, x = x_next
if self.can_skip_input and hasattr(module, 'skip_input') and module.skip_input:
x = x_prev
return x_next, x
def nasnet_dual_path_scheme_ordinal(module,
x,
_):
"""
NASNet specific scheme of dual path response for an ordinal module with dual inputs/outputs in a DualPathSequential
module.
Parameters:
----------
module : nn.Module
A module.
x : Tensor
Current processed tensor.
Returns
-------
x_next : Tensor
Next processed tensor.
x : Tensor
Current processed tensor.
"""
return module(x), x
def nasnet_dual_path_sequential(return_two=True,
first_ordinals=0,
last_ordinals=0,
can_skip_input=False):
"""
NASNet specific dual path sequential container.
Parameters:
----------
return_two : bool, default True
Whether to return two output after execution.
first_ordinals : int, default 0
Number of the first modules with single input/output.
last_ordinals : int, default 0
Number of the final modules with single input/output.
dual_path_scheme : function
Scheme of dual path response for a module.
dual_path_scheme_ordinal : function
Scheme of dual path response for an ordinal module.
can_skip_input : bool, default False
Whether can skip input for some modules.
"""
return DualPathSequential(
return_two=return_two,
first_ordinals=first_ordinals,
last_ordinals=last_ordinals,
dual_path_scheme=NasDualPathScheme(can_skip_input=can_skip_input),
dual_path_scheme_ordinal=nasnet_dual_path_scheme_ordinal)
def nasnet_batch_norm(channels):
"""
NASNet specific Batch normalization layer.
Parameters:
----------
channels : int
Number of channels in input data.
"""
return nn.BatchNorm2d(
num_features=channels,
eps=0.001,
momentum=0.1,
affine=True)
def nasnet_avgpool1x1_s2():
"""
NASNet specific 1x1 Average pooling layer with stride 2.
"""
return nn.AvgPool2d(
kernel_size=1,
stride=2,
count_include_pad=False)
def nasnet_avgpool3x3_s1():
"""
NASNet specific 3x3 Average pooling layer with stride 1.
"""
return nn.AvgPool2d(
kernel_size=3,
stride=1,
padding=1,
count_include_pad=False)
def nasnet_avgpool3x3_s2():
"""
NASNet specific 3x3 Average pooling layer with stride 2.
"""
return nn.AvgPool2d(
kernel_size=3,
stride=2,
padding=1,
count_include_pad=False)
class NasMaxPoolBlock(nn.Module):
"""
NASNet specific Max pooling layer with extra padding.
Parameters:
----------
extra_padding : bool, default False
Whether to use extra padding.
"""
def __init__(self,
extra_padding=False):
super(NasMaxPoolBlock, self).__init__()
self.extra_padding = extra_padding
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=1)
if self.extra_padding:
self.pad = nn.ZeroPad2d(padding=(1, 0, 1, 0))
def forward(self, x):
if self.extra_padding:
x = self.pad(x)
x = self.pool(x)
if self.extra_padding:
x = x[:, :, 1:, 1:].contiguous()
return x
class NasAvgPoolBlock(nn.Module):
"""
NASNet specific 3x3 Average pooling layer with extra padding.
Parameters:
----------
extra_padding : bool, default False
Whether to use extra padding.
"""
def __init__(self,
extra_padding=False):
super(NasAvgPoolBlock, self).__init__()
self.extra_padding = extra_padding
self.pool = nn.AvgPool2d(
kernel_size=3,
stride=2,
padding=1,
count_include_pad=False)
if self.extra_padding:
self.pad = nn.ZeroPad2d(padding=(1, 0, 1, 0))
def forward(self, x):
if self.extra_padding:
x = self.pad(x)
x = self.pool(x)
if self.extra_padding:
x = x[:, :, 1:, 1:].contiguous()
return x
class NasConv(nn.Module):
"""
NASNet specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
groups : int
Number of groups.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
groups):
super(NasConv, self).__init__()
self.activ = nn.ReLU()
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
groups=groups,
bias=False)
self.bn = nasnet_batch_norm(channels=out_channels)
def forward(self, x):
x = self.activ(x)
x = self.conv(x)
x = self.bn(x)
return x
def nas_conv1x1(in_channels,
out_channels):
"""
1x1 version of the NASNet specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
return NasConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
stride=1,
padding=0,
groups=1)
class DwsConv(nn.Module):
"""
Standard depthwise separable convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
bias : bool, default False
Whether the layers use a bias vector.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
bias=False):
super(DwsConv, self).__init__()
self.dw_conv = nn.Conv2d(
in_channels=in_channels,
out_channels=in_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
groups=in_channels,
bias=bias)
self.pw_conv = conv1x1(
in_channels=in_channels,
out_channels=out_channels,
bias=bias)
def forward(self, x):
x = self.dw_conv(x)
x = self.pw_conv(x)
return x
class NasDwsConv(nn.Module):
"""
NASNet specific depthwise separable convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
extra_padding : bool, default False
Whether to use extra padding.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
extra_padding=False):
super(NasDwsConv, self).__init__()
self.extra_padding = extra_padding
self.activ = nn.ReLU()
self.conv = DwsConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
bias=False)
self.bn = nasnet_batch_norm(channels=out_channels)
if self.extra_padding:
self.pad = nn.ZeroPad2d(padding=(1, 0, 1, 0))
def forward(self, x):
x = self.activ(x)
if self.extra_padding:
x = self.pad(x)
x = self.conv(x)
if self.extra_padding:
x = x[:, :, 1:, 1:].contiguous()
x = self.bn(x)
return x
class DwsBranch(nn.Module):
"""
NASNet specific block with depthwise separable convolution layers.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
extra_padding : bool, default False
Whether to use extra padding.
stem : bool, default False
Whether to use squeeze reduction if False.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
extra_padding=False,
stem=False):
super(DwsBranch, self).__init__()
assert (not stem) or (not extra_padding)
mid_channels = out_channels if stem else in_channels
self.conv1 = NasDwsConv(
in_channels=in_channels,
out_channels=mid_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
extra_padding=extra_padding)
self.conv2 = NasDwsConv(
in_channels=mid_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=1,
padding=padding)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
return x
def dws_branch_k3_s1_p1(in_channels,
out_channels,
extra_padding=False):
"""
3x3/1/1 version of the NASNet specific depthwise separable convolution branch.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
extra_padding : bool, default False
Whether to use extra padding.
"""
return DwsBranch(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=1,
padding=1,
extra_padding=extra_padding)
def dws_branch_k5_s1_p2(in_channels,
out_channels,
extra_padding=False):
"""
5x5/1/2 version of the NASNet specific depthwise separable convolution branch.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
extra_padding : bool, default False
Whether to use extra padding.
"""
return DwsBranch(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=5,
stride=1,
padding=2,
extra_padding=extra_padding)
def dws_branch_k5_s2_p2(in_channels,
out_channels,
extra_padding=False,
stem=False):
"""
5x5/2/2 version of the NASNet specific depthwise separable convolution branch.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
extra_padding : bool, default False
Whether to use extra padding.
stem : bool, default False
Whether to use squeeze reduction if False.
"""
return DwsBranch(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=5,
stride=2,
padding=2,
extra_padding=extra_padding,
stem=stem)
def dws_branch_k7_s2_p3(in_channels,
out_channels,
extra_padding=False,
stem=False):
"""
7x7/2/3 version of the NASNet specific depthwise separable convolution branch.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
extra_padding : bool, default False
Whether to use extra padding.
stem : bool, default False
Whether to use squeeze reduction if False.
"""
return DwsBranch(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=7,
stride=2,
padding=3,
extra_padding=extra_padding,
stem=stem)
class NasPathBranch(nn.Module):
"""
NASNet specific `path` branch (auxiliary block).
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
extra_padding : bool, default False
Whether to use extra padding.
"""
def __init__(self,
in_channels,
out_channels,
extra_padding=False):
super(NasPathBranch, self).__init__()
self.extra_padding = extra_padding
self.avgpool = nasnet_avgpool1x1_s2()
self.conv = conv1x1(
in_channels=in_channels,
out_channels=out_channels)
if self.extra_padding:
self.pad = nn.ZeroPad2d(padding=(0, 1, 0, 1))
def forward(self, x):
if self.extra_padding:
x = self.pad(x)
x = x[:, :, 1:, 1:].contiguous()
x = self.avgpool(x)
x = self.conv(x)
return x
class NasPathBlock(nn.Module):
"""
NASNet specific `path` block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(NasPathBlock, self).__init__()
mid_channels = out_channels // 2
self.activ = nn.ReLU()
self.path1 = NasPathBranch(
in_channels=in_channels,
out_channels=mid_channels)
self.path2 = NasPathBranch(
in_channels=in_channels,
out_channels=mid_channels,
extra_padding=True)
self.bn = nasnet_batch_norm(channels=out_channels)
def forward(self, x):
x = self.activ(x)
x1 = self.path1(x)
x2 = self.path2(x)
x = torch.cat((x1, x2), dim=1)
x = self.bn(x)
return x
class Stem1Unit(nn.Module):
"""
NASNet Stem1 unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(Stem1Unit, self).__init__()
mid_channels = out_channels // 4
self.conv1x1 = nas_conv1x1(
in_channels=in_channels,
out_channels=mid_channels)
self.comb0_left = dws_branch_k5_s2_p2(
in_channels=mid_channels,
out_channels=mid_channels)
self.comb0_right = dws_branch_k7_s2_p3(
in_channels=in_channels,
out_channels=mid_channels,
stem=True)
self.comb1_left = NasMaxPoolBlock(extra_padding=False)
self.comb1_right = dws_branch_k7_s2_p3(
in_channels=in_channels,
out_channels=mid_channels,
stem=True)
self.comb2_left = nasnet_avgpool3x3_s2()
self.comb2_right = dws_branch_k5_s2_p2(
in_channels=in_channels,
out_channels=mid_channels,
stem=True)
self.comb3_right = nasnet_avgpool3x3_s1()
self.comb4_left = dws_branch_k3_s1_p1(
in_channels=mid_channels,
out_channels=mid_channels)
self.comb4_right = NasMaxPoolBlock(extra_padding=False)
def forward(self, x, _=None):
x_left = self.conv1x1(x)
x_right = x
x0 = self.comb0_left(x_left) + self.comb0_right(x_right)
x1 = self.comb1_left(x_left) + self.comb1_right(x_right)
x2 = self.comb2_left(x_left) + self.comb2_right(x_right)
x3 = x1 + self.comb3_right(x0)
x4 = self.comb4_left(x0) + self.comb4_right(x_left)
x_out = torch.cat((x1, x2, x3, x4), dim=1)
return x_out
class Stem2Unit(nn.Module):
"""
NASNet Stem2 unit.
Parameters:
----------
in_channels : int
Number of input channels.
prev_in_channels : int
Number of input channels in previous input.
out_channels : int
Number of output channels.
extra_padding : bool
Whether to use extra padding.
"""
def __init__(self,
in_channels,
prev_in_channels,
out_channels,
extra_padding):
super(Stem2Unit, self).__init__()
mid_channels = out_channels // 4
self.conv1x1 = nas_conv1x1(
in_channels=in_channels,
out_channels=mid_channels)
self.path = NasPathBlock(
in_channels=prev_in_channels,
out_channels=mid_channels)
self.comb0_left = dws_branch_k5_s2_p2(
in_channels=mid_channels,
out_channels=mid_channels,
extra_padding=extra_padding)
self.comb0_right = dws_branch_k7_s2_p3(
in_channels=mid_channels,
out_channels=mid_channels,
extra_padding=extra_padding)
self.comb1_left = NasMaxPoolBlock(extra_padding=extra_padding)
self.comb1_right = dws_branch_k7_s2_p3(
in_channels=mid_channels,
out_channels=mid_channels,
extra_padding=extra_padding)
self.comb2_left = NasAvgPoolBlock(extra_padding=extra_padding)
self.comb2_right = dws_branch_k5_s2_p2(
in_channels=mid_channels,
out_channels=mid_channels,
extra_padding=extra_padding)
self.comb3_right = nasnet_avgpool3x3_s1()
self.comb4_left = dws_branch_k3_s1_p1(
in_channels=mid_channels,
out_channels=mid_channels,
extra_padding=extra_padding)
self.comb4_right = NasMaxPoolBlock(extra_padding=extra_padding)
def forward(self, x, x_prev):
x_left = self.conv1x1(x)
x_right = self.path(x_prev)
x0 = self.comb0_left(x_left) + self.comb0_right(x_right)
x1 = self.comb1_left(x_left) + self.comb1_right(x_right)
x2 = self.comb2_left(x_left) + self.comb2_right(x_right)
x3 = x1 + self.comb3_right(x0)
x4 = self.comb4_left(x0) + self.comb4_right(x_left)
x_out = torch.cat((x1, x2, x3, x4), dim=1)
return x_out
class FirstUnit(nn.Module):
"""
NASNet First unit.
Parameters:
----------
in_channels : int
Number of input channels.
prev_in_channels : int
Number of input channels in previous input.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
prev_in_channels,
out_channels):
super(FirstUnit, self).__init__()
mid_channels = out_channels // 6
self.conv1x1 = nas_conv1x1(
in_channels=in_channels,
out_channels=mid_channels)
self.path = NasPathBlock(
in_channels=prev_in_channels,
out_channels=mid_channels)
self.comb0_left = dws_branch_k5_s1_p2(
in_channels=mid_channels,
out_channels=mid_channels)
self.comb0_right = dws_branch_k3_s1_p1(
in_channels=mid_channels,
out_channels=mid_channels)
self.comb1_left = dws_branch_k5_s1_p2(
in_channels=mid_channels,
out_channels=mid_channels)
self.comb1_right = dws_branch_k3_s1_p1(
in_channels=mid_channels,
out_channels=mid_channels)
self.comb2_left = nasnet_avgpool3x3_s1()
self.comb3_left = nasnet_avgpool3x3_s1()
self.comb3_right = nasnet_avgpool3x3_s1()
self.comb4_left = dws_branch_k3_s1_p1(
in_channels=mid_channels,
out_channels=mid_channels)
def forward(self, x, x_prev):
x_left = self.conv1x1(x)
x_right = self.path(x_prev)
x0 = self.comb0_left(x_left) + self.comb0_right(x_right)
x1 = self.comb1_left(x_right) + self.comb1_right(x_right)
x2 = self.comb2_left(x_left) + x_right
x3 = self.comb3_left(x_right) + self.comb3_right(x_right)
x4 = self.comb4_left(x_left) + x_left
x_out = torch.cat((x_right, x0, x1, x2, x3, x4), dim=1)
return x_out
class NormalUnit(nn.Module):
"""
NASNet Normal unit.
Parameters:
----------
in_channels : int
Number of input channels.
prev_in_channels : int
Number of input channels in previous input.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
prev_in_channels,
out_channels):
super(NormalUnit, self).__init__()
mid_channels = out_channels // 6
self.conv1x1_prev = nas_conv1x1(
in_channels=prev_in_channels,
out_channels=mid_channels)
self.conv1x1 = nas_conv1x1(
in_channels=in_channels,
out_channels=mid_channels)
self.comb0_left = dws_branch_k5_s1_p2(
in_channels=mid_channels,
out_channels=mid_channels)
self.comb0_right = dws_branch_k3_s1_p1(
in_channels=mid_channels,
out_channels=mid_channels)
self.comb1_left = dws_branch_k5_s1_p2(
in_channels=mid_channels,
out_channels=mid_channels)
self.comb1_right = dws_branch_k3_s1_p1(
in_channels=mid_channels,
out_channels=mid_channels)
self.comb2_left = nasnet_avgpool3x3_s1()
self.comb3_left = nasnet_avgpool3x3_s1()
self.comb3_right = nasnet_avgpool3x3_s1()
self.comb4_left = dws_branch_k3_s1_p1(
in_channels=mid_channels,
out_channels=mid_channels)
def forward(self, x, x_prev):
x_left = self.conv1x1(x)
x_right = self.conv1x1_prev(x_prev)
x0 = self.comb0_left(x_left) + self.comb0_right(x_right)
x1 = self.comb1_left(x_right) + self.comb1_right(x_right)
x2 = self.comb2_left(x_left) + x_right
x3 = self.comb3_left(x_right) + self.comb3_right(x_right)
x4 = self.comb4_left(x_left) + x_left
x_out = torch.cat((x_right, x0, x1, x2, x3, x4), dim=1)
return x_out
class ReductionBaseUnit(nn.Module):
"""
NASNet Reduction base unit.
Parameters:
----------
in_channels : int
Number of input channels.
prev_in_channels : int
Number of input channels in previous input.
out_channels : int
Number of output channels.
extra_padding : bool, default True
Whether to use extra padding.
"""
def __init__(self,
in_channels,
prev_in_channels,
out_channels,
extra_padding=True):
super(ReductionBaseUnit, self).__init__()
self.skip_input = True
mid_channels = out_channels // 4
self.conv1x1_prev = nas_conv1x1(
in_channels=prev_in_channels,
out_channels=mid_channels)
self.conv1x1 = nas_conv1x1(
in_channels=in_channels,
out_channels=mid_channels)
self.comb0_left = dws_branch_k5_s2_p2(
in_channels=mid_channels,
out_channels=mid_channels,
extra_padding=extra_padding)
self.comb0_right = dws_branch_k7_s2_p3(
in_channels=mid_channels,
out_channels=mid_channels,
extra_padding=extra_padding)
self.comb1_left = NasMaxPoolBlock(extra_padding=extra_padding)
self.comb1_right = dws_branch_k7_s2_p3(
in_channels=mid_channels,
out_channels=mid_channels,
extra_padding=extra_padding)
self.comb2_left = NasAvgPoolBlock(extra_padding=extra_padding)
self.comb2_right = dws_branch_k5_s2_p2(
in_channels=mid_channels,
out_channels=mid_channels,
extra_padding=extra_padding)
self.comb3_right = nasnet_avgpool3x3_s1()
self.comb4_left = dws_branch_k3_s1_p1(
in_channels=mid_channels,
out_channels=mid_channels,
extra_padding=extra_padding)
self.comb4_right = NasMaxPoolBlock(extra_padding=extra_padding)
def forward(self, x, x_prev):
x_left = self.conv1x1(x)
x_right = self.conv1x1_prev(x_prev)
x0 = self.comb0_left(x_left) + self.comb0_right(x_right)
x1 = self.comb1_left(x_left) + self.comb1_right(x_right)
x2 = self.comb2_left(x_left) + self.comb2_right(x_right)
x3 = x1 + self.comb3_right(x0)
x4 = self.comb4_left(x0) + self.comb4_right(x_left)
x_out = torch.cat((x1, x2, x3, x4), dim=1)
return x_out
class Reduction1Unit(ReductionBaseUnit):
"""
NASNet Reduction1 unit.
Parameters:
----------
in_channels : int
Number of input channels.
prev_in_channels : int
Number of input channels in previous input.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
prev_in_channels,
out_channels):
super(Reduction1Unit, self).__init__(
in_channels=in_channels,
prev_in_channels=prev_in_channels,
out_channels=out_channels,
extra_padding=True)
class Reduction2Unit(ReductionBaseUnit):
"""
NASNet Reduction2 unit.
Parameters:
----------
in_channels : int
Number of input channels.
prev_in_channels : int
Number of input channels in previous input.
out_channels : int
Number of output channels.
extra_padding : bool
Whether to use extra padding.
"""
def __init__(self,
in_channels,
prev_in_channels,
out_channels,
extra_padding):
super(Reduction2Unit, self).__init__(
in_channels=in_channels,
prev_in_channels=prev_in_channels,
out_channels=out_channels,
extra_padding=extra_padding)
class NASNetInitBlock(nn.Module):
"""
NASNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(NASNetInitBlock, self).__init__()
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=2,
padding=0,
bias=False)
self.bn = nasnet_batch_norm(channels=out_channels)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
return x
class NASNet(nn.Module):
"""
NASNet-A model from 'Learning Transferable Architectures for Scalable Image Recognition,'
https://arxiv.org/abs/1707.07012.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
stem_blocks_channels : list of 2 int
Number of output channels for the Stem units.
final_pool_size : int
Size of the pooling windows for final pool.
extra_padding : bool
Whether to use extra padding.
skip_reduction_layer_input : bool
Whether to skip the reduction layers when calculating the previous layer to connect to.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
stem_blocks_channels,
final_pool_size,
extra_padding,
skip_reduction_layer_input,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(NASNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
reduction_units = [Reduction1Unit, Reduction2Unit]
self.features = nasnet_dual_path_sequential(
return_two=False,
first_ordinals=1,
last_ordinals=2)
self.features.add_module("init_block", NASNetInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
out_channels = stem_blocks_channels[0]
self.features.add_module("stem1_unit", Stem1Unit(
in_channels=in_channels,
out_channels=out_channels))
prev_in_channels = in_channels
in_channels = out_channels
out_channels = stem_blocks_channels[1]
self.features.add_module("stem2_unit", Stem2Unit(
in_channels=in_channels,
prev_in_channels=prev_in_channels,
out_channels=out_channels,
extra_padding=extra_padding))
prev_in_channels = in_channels
in_channels = out_channels
for i, channels_per_stage in enumerate(channels):
stage = nasnet_dual_path_sequential(can_skip_input=skip_reduction_layer_input)
for j, out_channels in enumerate(channels_per_stage):
if (j == 0) and (i != 0):
unit = reduction_units[i - 1]
elif ((i == 0) and (j == 0)) or ((i != 0) and (j == 1)):
unit = FirstUnit
else:
unit = NormalUnit
if unit == Reduction2Unit:
stage.add_module("unit{}".format(j + 1), Reduction2Unit(
in_channels=in_channels,
prev_in_channels=prev_in_channels,
out_channels=out_channels,
extra_padding=extra_padding))
else:
stage.add_module("unit{}".format(j + 1), unit(
in_channels=in_channels,
prev_in_channels=prev_in_channels,
out_channels=out_channels))
prev_in_channels = in_channels
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("activ", nn.ReLU())
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=final_pool_size,
stride=1))
self.output = nn.Sequential()
self.output.add_module('dropout', nn.Dropout(p=0.5))
self.output.add_module('fc', nn.Linear(
in_features=in_channels,
out_features=num_classes))
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_nasnet(repeat,
penultimate_filters,
init_block_channels,
final_pool_size,
extra_padding,
skip_reduction_layer_input,
in_size,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create NASNet-A model with specific parameters.
Parameters:
----------
repeat : int
NNumber of cell repeats.
penultimate_filters : int
Number of filters in the penultimate layer of the network.
init_block_channels : int
Number of output channels for the initial unit.
final_pool_size : int
Size of the pooling windows for final pool.
extra_padding : bool
Whether to use extra padding.
skip_reduction_layer_input : bool
Whether to skip the reduction layers when calculating the previous layer to connect to.
in_size : tuple of two ints
Spatial size of the expected input image.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
stem_blocks_channels = [1, 2]
reduct_channels = [[], [8], [16]]
norm_channels = [6, 12, 24]
channels = [rci + [nci] * repeat for rci, nci in zip(reduct_channels, norm_channels)]
base_channel_chunk = penultimate_filters // channels[-1][-1]
stem_blocks_channels = [(ci * base_channel_chunk) for ci in stem_blocks_channels]
channels = [[(cij * base_channel_chunk) for cij in ci] for ci in channels]
net = NASNet(
channels=channels,
init_block_channels=init_block_channels,
stem_blocks_channels=stem_blocks_channels,
final_pool_size=final_pool_size,
extra_padding=extra_padding,
skip_reduction_layer_input=skip_reduction_layer_input,
in_size=in_size,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def nasnet_4a1056(**kwargs):
"""
NASNet-A 4@1056 (NASNet-A-Mobile) model from 'Learning Transferable Architectures for Scalable Image Recognition,'
https://arxiv.org/abs/1707.07012.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_nasnet(
repeat=4,
penultimate_filters=1056,
init_block_channels=32,
final_pool_size=7,
extra_padding=True,
skip_reduction_layer_input=False,
in_size=(224, 224),
model_name="nasnet_4a1056",
**kwargs)
def nasnet_6a4032(**kwargs):
"""
NASNet-A 6@4032 (NASNet-A-Large) model from 'Learning Transferable Architectures for Scalable Image Recognition,'
https://arxiv.org/abs/1707.07012.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_nasnet(
repeat=6,
penultimate_filters=4032,
init_block_channels=96,
final_pool_size=11,
extra_padding=False,
skip_reduction_layer_input=True,
in_size=(331, 331),
model_name="nasnet_6a4032",
**kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
nasnet_4a1056,
nasnet_6a4032,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != nasnet_4a1056 or weight_count == 5289978)
assert (model != nasnet_6a4032 or weight_count == 88753150)
x = torch.randn(1, 3, net.in_size[0], net.in_size[1])
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 38,586 | 28.500765 | 119 | py |
null | qimera-main/pytorchcv/models/nin_cifar.py | """
NIN for CIFAR/SVHN, implemented in PyTorch.
Original paper: 'Network In Network,' https://arxiv.org/abs/1312.4400.
"""
__all__ = ['CIFARNIN', 'nin_cifar10', 'nin_cifar100', 'nin_svhn']
import os
import torch.nn as nn
import torch.nn.init as init
class NINConv(nn.Module):
"""
NIN specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 0
Padding value for convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0):
super(NINConv, self).__init__()
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
bias=True)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
x = self.conv(x)
x = self.activ(x)
return x
class CIFARNIN(nn.Module):
"""
NIN model for CIFAR from 'Network In Network,' https://arxiv.org/abs/1312.4400.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
first_kernel_sizes : list of int
Convolution window sizes for the first units in each stage.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
num_classes : int, default 10
Number of classification classes.
"""
def __init__(self,
channels,
first_kernel_sizes,
in_channels=3,
in_size=(32, 32),
num_classes=10):
super(CIFARNIN, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
if (j == 0) and (i != 0):
if i == 1:
stage.add_module("pool{}".format(i + 1), nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=1))
else:
stage.add_module("pool{}".format(i + 1), nn.AvgPool2d(
kernel_size=3,
stride=2,
padding=1))
stage.add_module("dropout{}".format(i + 1), nn.Dropout(p=0.5))
kernel_size = first_kernel_sizes[i] if j == 0 else 1
padding = (kernel_size - 1) // 2
stage.add_module("unit{}".format(j + 1), NINConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
padding=padding))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.output = nn.Sequential()
self.output.add_module('final_conv', NINConv(
in_channels=in_channels,
out_channels=num_classes,
kernel_size=1))
self.output.add_module('final_pool', nn.AvgPool2d(
kernel_size=8,
stride=1))
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = self.output(x)
x = x.view(x.size(0), -1)
return x
def get_nin_cifar(num_classes,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create NIN model for CIFAR with specific parameters.
Parameters:
----------
num_classes : int
Number of classification classes.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
channels = [[192, 160, 96], [192, 192, 192], [192, 192]]
first_kernel_sizes = [5, 5, 3]
net = CIFARNIN(
channels=channels,
first_kernel_sizes=first_kernel_sizes,
num_classes=num_classes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def nin_cifar10(num_classes=10, **kwargs):
"""
NIN model for CIFAR-10 from 'Network In Network,' https://arxiv.org/abs/1312.4400.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_nin_cifar(num_classes=num_classes, model_name="nin_cifar10", **kwargs)
def nin_cifar100(num_classes=100, **kwargs):
"""
NIN model for CIFAR-100 from 'Network In Network,' https://arxiv.org/abs/1312.4400.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_nin_cifar(num_classes=num_classes, model_name="nin_cifar100", **kwargs)
def nin_svhn(num_classes=10, **kwargs):
"""
NIN model for SVHN from 'Network In Network,' https://arxiv.org/abs/1312.4400.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_nin_cifar(num_classes=num_classes, model_name="nin_svhn", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
(nin_cifar10, 10),
(nin_cifar100, 100),
(nin_svhn, 10),
]
for model, num_classes in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != nin_cifar10 or weight_count == 966986)
assert (model != nin_cifar100 or weight_count == 984356)
assert (model != nin_svhn or weight_count == 966986)
x = torch.randn(1, 3, 32, 32)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, num_classes))
if __name__ == "__main__":
_test()
| 8,048 | 29.957692 | 115 | py |
null | qimera-main/pytorchcv/models/ntsnet_cub.py | """
NTS-Net for CUB-200-2011, implemented in PyTorch.
Original paper: 'Learning to Navigate for Fine-grained Classification,' https://arxiv.org/abs/1809.00287.
"""
__all__ = ['NTSNet', 'ntsnet_cub']
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from .common import conv1x1, conv3x3, Flatten
from .resnet import resnet50b
def hard_nms(cdds,
top_n=10,
iou_thresh=0.25):
"""
Hard Non-Maximum Suppression.
Parameters:
----------
cdds : np.array
Borders.
top_n : int, default 10
Number of top-K informative regions.
iou_thresh : float, default 0.25
IoU threshold.
Returns
-------
np.array
Filtered borders.
"""
assert (type(cdds) == np.ndarray)
assert (len(cdds.shape) == 2)
assert (cdds.shape[1] >= 5)
cdds = cdds.copy()
indices = np.argsort(cdds[:, 0])
cdds = cdds[indices]
cdd_results = []
res = cdds
while res.any():
cdd = res[-1]
cdd_results.append(cdd)
if len(cdd_results) == top_n:
return np.array(cdd_results)
res = res[:-1]
start_max = np.maximum(res[:, 1:3], cdd[1:3])
end_min = np.minimum(res[:, 3:5], cdd[3:5])
lengths = end_min - start_max
intersec_map = lengths[:, 0] * lengths[:, 1]
intersec_map[np.logical_or(lengths[:, 0] < 0, lengths[:, 1] < 0)] = 0
iou_map_cur = intersec_map / ((res[:, 3] - res[:, 1]) * (res[:, 4] - res[:, 2]) + (cdd[3] - cdd[1]) * (
cdd[4] - cdd[2]) - intersec_map)
res = res[iou_map_cur < iou_thresh]
return np.array(cdd_results)
class NavigatorBranch(nn.Module):
"""
Navigator branch block for Navigator unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
"""
def __init__(self,
in_channels,
out_channels,
stride):
super(NavigatorBranch, self).__init__()
mid_channels = 128
self.down_conv = conv3x3(
in_channels=in_channels,
out_channels=mid_channels,
stride=stride,
bias=True)
self.activ = nn.ReLU(inplace=False)
self.tidy_conv = conv1x1(
in_channels=mid_channels,
out_channels=out_channels,
bias=True)
self.flatten = Flatten()
def forward(self, x):
y = self.down_conv(x)
y = self.activ(y)
z = self.tidy_conv(y)
z = self.flatten(z)
return z, y
class NavigatorUnit(nn.Module):
"""
Navigator init.
"""
def __init__(self):
super(NavigatorUnit, self).__init__()
self.branch1 = NavigatorBranch(
in_channels=2048,
out_channels=6,
stride=1)
self.branch2 = NavigatorBranch(
in_channels=128,
out_channels=6,
stride=2)
self.branch3 = NavigatorBranch(
in_channels=128,
out_channels=9,
stride=2)
def forward(self, x):
t1, x = self.branch1(x)
t2, x = self.branch2(x)
t3, _ = self.branch3(x)
return torch.cat((t1, t2, t3), dim=1)
class NTSNet(nn.Module):
"""
NTS-Net model from 'Learning to Navigate for Fine-grained Classification,' https://arxiv.org/abs/1809.00287.
Parameters:
----------
backbone : nn.Sequential
Feature extractor.
aux : bool, default False
Whether to output auxiliary results.
top_n : int, default 4
Number of extra top-K informative regions.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
backbone,
aux=False,
top_n=4,
in_channels=3,
in_size=(448, 448),
num_classes=200):
super(NTSNet, self).__init__()
assert (in_channels > 0)
self.in_size = in_size
self.num_classes = num_classes
pad_side = 224
pad_width = (pad_side, pad_side, pad_side, pad_side)
self.top_n = top_n
self.aux = aux
self.num_cat = 4
_, edge_anchors, _ = self._generate_default_anchor_maps()
self.edge_anchors = (edge_anchors + 224).astype(np.int)
self.edge_anchors = np.concatenate(
(self.edge_anchors.copy(), np.arange(0, len(self.edge_anchors)).reshape(-1, 1)), axis=1)
self.backbone = backbone
self.backbone_tail = nn.Sequential()
self.backbone_tail.add_module("final_pool", nn.AdaptiveAvgPool2d(1))
self.backbone_tail.add_module("flatten", Flatten())
self.backbone_tail.add_module("dropout", nn.Dropout(p=0.5))
self.backbone_classifier = nn.Linear(
in_features=(512 * 4),
out_features=num_classes)
self.pad = nn.ZeroPad2d(padding=pad_width)
self.navigator_unit = NavigatorUnit()
self.concat_net = nn.Linear(
in_features=(2048 * (self.num_cat + 1)),
out_features=num_classes)
if self.aux:
self.partcls_net = nn.Linear(
in_features=(512 * 4),
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
raw_pre_features = self.backbone(x)
rpn_score = self.navigator_unit(raw_pre_features)
all_cdds = [np.concatenate((y.reshape(-1, 1), self.edge_anchors.copy()), axis=1)
for y in rpn_score.detach().cpu().numpy()]
top_n_cdds = [hard_nms(y, top_n=self.top_n, iou_thresh=0.25) for y in all_cdds]
top_n_cdds = np.array(top_n_cdds)
top_n_index = top_n_cdds[:, :, -1].astype(np.int64)
top_n_index = torch.from_numpy(top_n_index).long().to(x.device)
top_n_prob = torch.gather(rpn_score, dim=1, index=top_n_index)
batch = x.size(0)
part_imgs = torch.zeros(batch, self.top_n, 3, 224, 224, dtype=x.dtype, device=x.device)
x_pad = self.pad(x)
for i in range(batch):
for j in range(self.top_n):
y0, x0, y1, x1 = tuple(top_n_cdds[i][j, 1:5].astype(np.int64))
part_imgs[i:i + 1, j] = F.interpolate(
input=x_pad[i:i + 1, :, y0:y1, x0:x1],
size=(224, 224),
mode="bilinear",
align_corners=True)
part_imgs = part_imgs.view(batch * self.top_n, 3, 224, 224)
part_features = self.backbone_tail(self.backbone(part_imgs.detach()))
part_feature = part_features.view(batch, self.top_n, -1)
part_feature = part_feature[:, :self.num_cat, :].contiguous()
part_feature = part_feature.view(batch, -1)
raw_features = self.backbone_tail(raw_pre_features.detach())
concat_out = torch.cat((part_feature, raw_features), dim=1)
concat_logits = self.concat_net(concat_out)
if self.aux:
raw_logits = self.backbone_classifier(raw_features)
part_logits = self.partcls_net(part_features).view(batch, self.top_n, -1)
return concat_logits, raw_logits, part_logits, top_n_prob
else:
return concat_logits
@staticmethod
def _generate_default_anchor_maps(input_shape=(448, 448)):
"""
Generate default anchor maps.
Parameters:
----------
input_shape : tuple of 2 int
Input image size.
Returns
-------
center_anchors : np.array
anchors * 4 (oy, ox, h, w).
edge_anchors : np.array
anchors * 4 (y0, x0, y1, x1).
anchor_area : np.array
anchors * 1 (area).
"""
anchor_scale = [2 ** (1.0 / 3.0), 2 ** (2.0 / 3.0)]
anchor_aspect_ratio = [0.667, 1, 1.5]
anchors_setting = (
dict(layer="p3", stride=32, size=48, scale=anchor_scale, aspect_ratio=anchor_aspect_ratio),
dict(layer="p4", stride=64, size=96, scale=anchor_scale, aspect_ratio=anchor_aspect_ratio),
dict(layer="p5", stride=128, size=192, scale=[1, anchor_scale[0], anchor_scale[1]],
aspect_ratio=anchor_aspect_ratio),
)
center_anchors = np.zeros((0, 4), dtype=np.float32)
edge_anchors = np.zeros((0, 4), dtype=np.float32)
anchor_areas = np.zeros((0,), dtype=np.float32)
input_shape = np.array(input_shape, dtype=int)
for anchor_info in anchors_setting:
stride = anchor_info["stride"]
size = anchor_info["size"]
scales = anchor_info["scale"]
aspect_ratios = anchor_info["aspect_ratio"]
output_map_shape = np.ceil(input_shape.astype(np.float32) / stride)
output_map_shape = output_map_shape.astype(np.int)
output_shape = tuple(output_map_shape) + (4, )
ostart = stride / 2.0
oy = np.arange(ostart, ostart + stride * output_shape[0], stride)
oy = oy.reshape(output_shape[0], 1)
ox = np.arange(ostart, ostart + stride * output_shape[1], stride)
ox = ox.reshape(1, output_shape[1])
center_anchor_map_template = np.zeros(output_shape, dtype=np.float32)
center_anchor_map_template[:, :, 0] = oy
center_anchor_map_template[:, :, 1] = ox
for anchor_scale in scales:
for anchor_aspect_ratio in aspect_ratios:
center_anchor_map = center_anchor_map_template.copy()
center_anchor_map[:, :, 2] = size * anchor_scale / float(anchor_aspect_ratio) ** 0.5
center_anchor_map[:, :, 3] = size * anchor_scale * float(anchor_aspect_ratio) ** 0.5
edge_anchor_map = np.concatenate(
(center_anchor_map[:, :, :2] - center_anchor_map[:, :, 2:4] / 2.0,
center_anchor_map[:, :, :2] + center_anchor_map[:, :, 2:4] / 2.0),
axis=-1)
anchor_area_map = center_anchor_map[:, :, 2] * center_anchor_map[:, :, 3]
center_anchors = np.concatenate((center_anchors, center_anchor_map.reshape(-1, 4)))
edge_anchors = np.concatenate((edge_anchors, edge_anchor_map.reshape(-1, 4)))
anchor_areas = np.concatenate((anchor_areas, anchor_area_map.reshape(-1)))
return center_anchors, edge_anchors, anchor_areas
def get_ntsnet(backbone,
aux=False,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create NTS-Net model with specific parameters.
Parameters:
----------
backbone : nn.Sequential
Feature extractor.
aux : bool, default False
Whether to output auxiliary results.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
net = NTSNet(
backbone=backbone,
aux=aux,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def ntsnet_cub(pretrained_backbone=False, aux=True, **kwargs):
"""
NTS-Net model from 'Learning to Navigate for Fine-grained Classification,' https://arxiv.org/abs/1809.00287.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnet50b(pretrained=pretrained_backbone).features
del backbone[-1]
return get_ntsnet(backbone=backbone, aux=aux, model_name="ntsnet_cub", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
aux = True
models = [
ntsnet_cub,
]
for model in models:
net = model(pretrained=pretrained, aux=aux)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
if aux:
assert (model != ntsnet_cub or weight_count == 29033133)
else:
assert (model != ntsnet_cub or weight_count == 28623333)
x = torch.randn(5, 3, 448, 448)
ys = net(x)
y = ys[0] if aux else ys
y.sum().backward()
assert (tuple(y.size()) == (5, 200))
if __name__ == "__main__":
_test()
| 14,017 | 32.535885 | 115 | py |
null | qimera-main/pytorchcv/models/octresnet.py | """
Oct-ResNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'Drop an Octave: Reducing Spatial Redundancy in Convolutional Neural Networks with Octave
Convolution,' https://arxiv.org/abs/1904.05049.
"""
__all__ = ['OctResNet', 'octresnet10_ad2', 'octresnet50b_ad2', 'OctResUnit']
import os
from inspect import isfunction
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from .common import DualPathSequential
from .resnet import ResInitBlock
class OctConv(nn.Conv2d):
"""
Octave convolution layer.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
bias : bool, default False
Whether the layer uses a bias vector.
oct_alpha : float, default 0.0
Octave alpha coefficient.
oct_mode : str, default 'std'
Octave convolution mode. It can be 'first', 'norm', 'last', or 'std'.
oct_value : int, default 2
Octave value.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding=1,
dilation=1,
groups=1,
bias=False,
oct_alpha=0.0,
oct_mode="std",
oct_value=2):
if isinstance(stride, int):
stride = (stride, stride)
self.downsample = (stride[0] > 1) or (stride[1] > 1)
assert (stride[0] in [1, oct_value]) and (stride[1] in [1, oct_value])
stride = (1, 1)
if oct_mode == "first":
in_alpha = 0.0
out_alpha = oct_alpha
elif oct_mode == "norm":
in_alpha = oct_alpha
out_alpha = oct_alpha
elif oct_mode == "last":
in_alpha = oct_alpha
out_alpha = 0.0
elif oct_mode == "std":
in_alpha = 0.0
out_alpha = 0.0
else:
raise ValueError("Unsupported octave convolution mode: {}".format(oct_mode))
self.h_in_channels = int(in_channels * (1.0 - in_alpha))
self.h_out_channels = int(out_channels * (1.0 - out_alpha))
self.l_out_channels = out_channels - self.h_out_channels
self.oct_alpha = oct_alpha
self.oct_mode = oct_mode
self.oct_value = oct_value
super(OctConv, self).__init__(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
groups=groups,
bias=bias)
self.conv_kwargs = {
"stride": stride,
"padding": padding,
"dilation": dilation,
"groups": groups}
def forward(self, hx, lx=None):
if self.oct_mode == "std":
return F.conv2d(
input=hx,
weight=self.weight,
bias=self.bias,
**self.conv_kwargs), None
if self.downsample:
hx = F.avg_pool2d(
input=hx,
kernel_size=(self.oct_value, self.oct_value),
stride=(self.oct_value, self.oct_value))
hhy = F.conv2d(
input=hx,
weight=self.weight[0:self.h_out_channels, 0:self.h_in_channels, :, :],
bias=self.bias[0:self.h_out_channels] if self.bias is not None else None,
**self.conv_kwargs)
if self.oct_mode != "first":
hlx = F.conv2d(
input=lx,
weight=self.weight[0:self.h_out_channels, self.h_in_channels:, :, :],
bias=self.bias[0:self.h_out_channels] if self.bias is not None else None,
**self.conv_kwargs)
if self.oct_mode == "last":
hy = hhy + hlx
ly = None
return hy, ly
lhx = F.avg_pool2d(
input=hx,
kernel_size=(self.oct_value, self.oct_value),
stride=(self.oct_value, self.oct_value))
lhy = F.conv2d(
input=lhx,
weight=self.weight[self.h_out_channels:, 0:self.h_in_channels, :, :],
bias=self.bias[self.h_out_channels:] if self.bias is not None else None,
**self.conv_kwargs)
if self.oct_mode == "first":
hy = hhy
ly = lhy
return hy, ly
if self.downsample:
hly = hlx
llx = F.avg_pool2d(
input=lx,
kernel_size=(self.oct_value, self.oct_value),
stride=(self.oct_value, self.oct_value))
else:
hly = F.interpolate(
input=hlx,
scale_factor=self.oct_value,
mode="nearest")
llx = lx
lly = F.conv2d(
input=llx,
weight=self.weight[self.h_out_channels:, self.h_in_channels:, :, :],
bias=self.bias[self.h_out_channels:] if self.bias is not None else None,
**self.conv_kwargs)
hy = hhy + hly
ly = lhy + lly
return hy, ly
class OctConvBlock(nn.Module):
"""
Octave convolution block with Batch normalization and ReLU/ReLU6 activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
bias : bool, default False
Whether the layer uses a bias vector.
oct_alpha : float, default 0.0
Octave alpha coefficient.
oct_mode : str, default 'std'
Octave convolution mode. It can be 'first', 'norm', 'last', or 'std'.
bn_eps : float, default 1e-5
Small float added to variance in Batch norm.
activation : function or str or None, default nn.ReLU(inplace=True)
Activation function or name of activation function.
activate : bool, default True
Whether activate the convolution block.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
dilation=1,
groups=1,
bias=False,
oct_alpha=0.0,
oct_mode="std",
bn_eps=1e-5,
activation=(lambda: nn.ReLU(inplace=True)),
activate=True):
super(OctConvBlock, self).__init__()
self.activate = activate
self.last = (oct_mode == "last") or (oct_mode == "std")
out_alpha = 0.0 if self.last else oct_alpha
h_out_channels = int(out_channels * (1.0 - out_alpha))
l_out_channels = out_channels - h_out_channels
self.conv = OctConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
groups=groups,
bias=bias,
oct_alpha=oct_alpha,
oct_mode=oct_mode)
self.h_bn = nn.BatchNorm2d(
num_features=h_out_channels,
eps=bn_eps)
if not self.last:
self.l_bn = nn.BatchNorm2d(
num_features=l_out_channels,
eps=bn_eps)
if self.activate:
assert (activation is not None)
if isfunction(activation):
self.activ = activation()
elif isinstance(activation, str):
if activation == "relu":
self.activ = nn.ReLU(inplace=True)
elif activation == "relu6":
self.activ = nn.ReLU6(inplace=True)
else:
raise NotImplementedError()
else:
self.activ = activation
def forward(self, hx, lx=None):
hx, lx = self.conv(hx, lx)
hx = self.h_bn(hx)
if self.activate:
hx = self.activ(hx)
if not self.last:
lx = self.l_bn(lx)
if self.activate:
lx = self.activ(lx)
return hx, lx
def oct_conv1x1_block(in_channels,
out_channels,
stride=1,
groups=1,
bias=False,
oct_alpha=0.0,
oct_mode="std",
bn_eps=1e-5,
activation=(lambda: nn.ReLU(inplace=True)),
activate=True):
"""
1x1 version of the octave convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
groups : int, default 1
Number of groups.
bias : bool, default False
Whether the layer uses a bias vector.
oct_alpha : float, default 0.0
Octave alpha coefficient.
oct_mode : str, default 'std'
Octave convolution mode. It can be 'first', 'norm', 'last', or 'std'.
bn_eps : float, default 1e-5
Small float added to variance in Batch norm.
activation : function or str or None, default nn.ReLU(inplace=True)
Activation function or name of activation function.
activate : bool, default True
Whether activate the convolution block.
"""
return OctConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
stride=stride,
padding=0,
groups=groups,
bias=bias,
oct_alpha=oct_alpha,
oct_mode=oct_mode,
bn_eps=bn_eps,
activation=activation,
activate=activate)
def oct_conv3x3_block(in_channels,
out_channels,
stride=1,
padding=1,
dilation=1,
groups=1,
bias=False,
oct_alpha=0.0,
oct_mode="std",
bn_eps=1e-5,
activation=(lambda: nn.ReLU(inplace=True)),
activate=True):
"""
3x3 version of the octave convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
bias : bool, default False
Whether the layer uses a bias vector.
oct_alpha : float, default 0.0
Octave alpha coefficient.
oct_mode : str, default 'std'
Octave convolution mode. It can be 'first', 'norm', 'last', or 'std'.
bn_eps : float, default 1e-5
Small float added to variance in Batch norm.
activation : function or str or None, default nn.ReLU(inplace=True)
Activation function or name of activation function.
activate : bool, default True
Whether activate the convolution block.
"""
return OctConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=stride,
padding=padding,
dilation=dilation,
groups=groups,
bias=bias,
oct_alpha=oct_alpha,
oct_mode=oct_mode,
bn_eps=bn_eps,
activation=activation,
activate=activate)
class OctResBlock(nn.Module):
"""
Simple Oct-ResNet block for residual path in Oct-ResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
oct_alpha : float, default 0.0
Octave alpha coefficient.
oct_mode : str, default 'std'
Octave convolution mode. It can be 'first', 'norm', 'last', or 'std'.
"""
def __init__(self,
in_channels,
out_channels,
stride,
oct_alpha=0.0,
oct_mode="std"):
super(OctResBlock, self).__init__()
self.conv1 = oct_conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
oct_alpha=oct_alpha,
oct_mode=oct_mode)
self.conv2 = oct_conv3x3_block(
in_channels=out_channels,
out_channels=out_channels,
oct_alpha=oct_alpha,
oct_mode=("std" if oct_mode == "last" else (oct_mode if oct_mode != "first" else "norm")),
activation=None,
activate=False)
def forward(self, hx, lx=None):
hx, lx = self.conv1(hx, lx)
hx, lx = self.conv2(hx, lx)
return hx, lx
class OctResBottleneck(nn.Module):
"""
Oct-ResNet bottleneck block for residual path in Oct-ResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for the second convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for the second convolution layer.
oct_alpha : float, default 0.0
Octave alpha coefficient.
oct_mode : str, default 'std'
Octave convolution mode. It can be 'first', 'norm', 'last', or 'std'.
conv1_stride : bool, default False
Whether to use stride in the first or the second convolution layer of the block.
bottleneck_factor : int, default 4
Bottleneck factor.
"""
def __init__(self,
in_channels,
out_channels,
stride,
padding=1,
dilation=1,
oct_alpha=0.0,
oct_mode="std",
conv1_stride=False,
bottleneck_factor=4):
super(OctResBottleneck, self).__init__()
mid_channels = out_channels // bottleneck_factor
self.conv1 = oct_conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
stride=(stride if conv1_stride else 1),
oct_alpha=oct_alpha,
oct_mode=(oct_mode if oct_mode != "last" else "norm"))
self.conv2 = oct_conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
stride=(1 if conv1_stride else stride),
padding=padding,
dilation=dilation,
oct_alpha=oct_alpha,
oct_mode=(oct_mode if oct_mode != "first" else "norm"))
self.conv3 = oct_conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
oct_alpha=oct_alpha,
oct_mode=("std" if oct_mode == "last" else (oct_mode if oct_mode != "first" else "norm")),
activation=None,
activate=False)
def forward(self, hx, lx=None):
hx, lx = self.conv1(hx, lx)
hx, lx = self.conv2(hx, lx)
hx, lx = self.conv3(hx, lx)
return hx, lx
class OctResUnit(nn.Module):
"""
Oct-ResNet unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for the second convolution layer in bottleneck.
dilation : int or tuple/list of 2 int, default 1
Dilation value for the second convolution layer in bottleneck.
oct_alpha : float, default 0.0
Octave alpha coefficient.
oct_mode : str, default 'std'
Octave convolution mode. It can be 'first', 'norm', 'last', or 'std'.
bottleneck : bool, default True
Whether to use a bottleneck or simple block in units.
conv1_stride : bool, default False
Whether to use stride in the first or the second convolution layer of the block.
"""
def __init__(self,
in_channels,
out_channels,
stride,
padding=1,
dilation=1,
oct_alpha=0.0,
oct_mode="std",
bottleneck=True,
conv1_stride=False):
super(OctResUnit, self).__init__()
self.resize_identity = (in_channels != out_channels) or (stride != 1) or \
((oct_mode == "first") and (oct_alpha != 0.0))
if bottleneck:
self.body = OctResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
padding=padding,
dilation=dilation,
oct_alpha=oct_alpha,
oct_mode=oct_mode,
conv1_stride=conv1_stride)
else:
self.body = OctResBlock(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
oct_alpha=oct_alpha,
oct_mode=oct_mode)
if self.resize_identity:
self.identity_conv = oct_conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
oct_alpha=oct_alpha,
oct_mode=oct_mode,
activation=None,
activate=False)
self.activ = nn.ReLU(inplace=True)
def forward(self, hx, lx=None):
if self.resize_identity:
h_identity, l_identity = self.identity_conv(hx, lx)
else:
h_identity, l_identity = hx, lx
hx, lx = self.body(hx, lx)
hx = hx + h_identity
hx = self.activ(hx)
if lx is not None:
lx = lx + l_identity
lx = self.activ(lx)
return hx, lx
class OctResNet(nn.Module):
"""
Oct-ResNet model from 'Drop an Octave: Reducing Spatial Redundancy in Convolutional Neural Networks with Octave
Convolution,' https://arxiv.org/abs/1904.05049.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer in units.
oct_alpha : float, default 0.5
Octave alpha coefficient.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
conv1_stride,
oct_alpha=0.5,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(OctResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = DualPathSequential(
return_two=False,
first_ordinals=1,
last_ordinals=1)
self.features.add_module("init_block", ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = DualPathSequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
if (i == 0) and (j == 0):
oct_mode = "first"
elif (i == len(channels) - 1) and (j == 0):
oct_mode = "last"
elif (i == len(channels) - 1) and (j != 0):
oct_mode = "std"
else:
oct_mode = "norm"
stage.add_module("unit{}".format(j + 1), OctResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
oct_alpha=oct_alpha,
oct_mode=oct_mode,
bottleneck=bottleneck,
conv1_stride=conv1_stride))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_octresnet(blocks,
bottleneck=None,
conv1_stride=True,
oct_alpha=0.5,
width_scale=1.0,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create Oct-ResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
bottleneck : bool, default None
Whether to use a bottleneck or simple block in units.
conv1_stride : bool, default True
Whether to use stride in the first or the second convolution layer in units.
oct_alpha : float, default 0.5
Octave alpha coefficient.
width_scale : float, default 1.0
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if bottleneck is None:
bottleneck = (blocks >= 50)
if blocks == 10:
layers = [1, 1, 1, 1]
elif blocks == 12:
layers = [2, 1, 1, 1]
elif blocks == 14 and not bottleneck:
layers = [2, 2, 1, 1]
elif (blocks == 14) and bottleneck:
layers = [1, 1, 1, 1]
elif blocks == 16:
layers = [2, 2, 2, 1]
elif blocks == 18:
layers = [2, 2, 2, 2]
elif (blocks == 26) and not bottleneck:
layers = [3, 3, 3, 3]
elif (blocks == 26) and bottleneck:
layers = [2, 2, 2, 2]
elif blocks == 34:
layers = [3, 4, 6, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
elif blocks == 200:
layers = [3, 24, 36, 3]
elif blocks == 269:
layers = [3, 30, 48, 8]
else:
raise ValueError("Unsupported Oct-ResNet with number of blocks: {}".format(blocks))
if bottleneck:
assert (sum(layers) * 3 + 2 == blocks)
else:
assert (sum(layers) * 2 + 2 == blocks)
init_block_channels = 64
channels_per_layers = [64, 128, 256, 512]
if bottleneck:
bottleneck_factor = 4
channels_per_layers = [ci * bottleneck_factor for ci in channels_per_layers]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if width_scale != 1.0:
channels = [[int(cij * width_scale) if (i != len(channels) - 1) or (j != len(ci) - 1) else cij
for j, cij in enumerate(ci)] for i, ci in enumerate(channels)]
init_block_channels = int(init_block_channels * width_scale)
net = OctResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
oct_alpha=oct_alpha,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def octresnet10_ad2(**kwargs):
"""
Oct-ResNet-10 (alpha=1/2) model from 'Drop an Octave: Reducing Spatial Redundancy in Convolutional Neural Networks
with Octave Convolution,' https://arxiv.org/abs/1904.05049.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_octresnet(blocks=10, oct_alpha=0.5, model_name="octresnet10_ad2", **kwargs)
def octresnet50b_ad2(**kwargs):
"""
Oct-ResNet-50b (alpha=1/2) model from 'Drop an Octave: Reducing Spatial Redundancy in Convolutional Neural Networks
with Octave Convolution,' https://arxiv.org/abs/1904.05049.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_octresnet(blocks=50, conv1_stride=False, oct_alpha=0.5, model_name="octresnet50b_ad2", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
octresnet10_ad2,
octresnet50b_ad2,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != octresnet10_ad2 or weight_count == 5423016)
assert (model != octresnet50b_ad2 or weight_count == 25557032)
x = torch.randn(14, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (14, 1000))
if __name__ == "__main__":
_test()
| 27,931 | 32.612515 | 119 | py |
null | qimera-main/pytorchcv/models/peleenet.py | """
PeleeNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'Pelee: A Real-Time Object Detection System on Mobile Devices,' https://arxiv.org/abs/1804.06882.
"""
__all__ = ['PeleeNet', 'peleenet']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, conv3x3_block, Concurrent
class PeleeBranch1(nn.Module):
"""
PeleeNet branch type 1 block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
mid_channels : int
Number of intermediate channels.
stride : int or tuple/list of 2 int, default 1
Strides of the second convolution.
"""
def __init__(self,
in_channels,
out_channels,
mid_channels,
stride=1):
super(PeleeBranch1, self).__init__()
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels)
self.conv2 = conv3x3_block(
in_channels=mid_channels,
out_channels=out_channels,
stride=stride)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class PeleeBranch2(nn.Module):
"""
PeleeNet branch type 2 block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
mid_channels : int
Number of intermediate channels.
"""
def __init__(self,
in_channels,
out_channels,
mid_channels):
super(PeleeBranch2, self).__init__()
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels)
self.conv2 = conv3x3_block(
in_channels=mid_channels,
out_channels=out_channels)
self.conv3 = conv3x3_block(
in_channels=out_channels,
out_channels=out_channels)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class StemBlock(nn.Module):
"""
PeleeNet stem block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(StemBlock, self).__init__()
mid1_channels = out_channels // 2
mid2_channels = out_channels * 2
self.first_conv = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
stride=2)
self.branches = Concurrent()
self.branches.add_module("branch1", PeleeBranch1(
in_channels=out_channels,
out_channels=out_channels,
mid_channels=mid1_channels,
stride=2))
self.branches.add_module("branch2", nn.MaxPool2d(
kernel_size=2,
stride=2,
padding=0))
self.last_conv = conv1x1_block(
in_channels=mid2_channels,
out_channels=out_channels)
def forward(self, x):
x = self.first_conv(x)
x = self.branches(x)
x = self.last_conv(x)
return x
class DenseBlock(nn.Module):
"""
PeleeNet dense block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bottleneck_size : int
Bottleneck width.
"""
def __init__(self,
in_channels,
out_channels,
bottleneck_size):
super(DenseBlock, self).__init__()
inc_channels = (out_channels - in_channels) // 2
mid_channels = inc_channels * bottleneck_size
self.branch1 = PeleeBranch1(
in_channels=in_channels,
out_channels=inc_channels,
mid_channels=mid_channels)
self.branch2 = PeleeBranch2(
in_channels=in_channels,
out_channels=inc_channels,
mid_channels=mid_channels)
def forward(self, x):
x1 = self.branch1(x)
x2 = self.branch2(x)
x = torch.cat((x, x1, x2), dim=1)
return x
class TransitionBlock(nn.Module):
"""
PeleeNet's transition block, like in DensNet, but with ordinary convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(TransitionBlock, self).__init__()
self.conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels)
self.pool = nn.AvgPool2d(
kernel_size=2,
stride=2,
padding=0)
def forward(self, x):
x = self.conv(x)
x = self.pool(x)
return x
class PeleeNet(nn.Module):
"""
PeleeNet model from 'Pelee: A Real-Time Object Detection System on Mobile Devices,'
https://arxiv.org/abs/1804.06882.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck_sizes : list of int
Bottleneck sizes for each stage.
dropout_rate : float, default 0.5
Parameter of Dropout layer. Faction of the input units to drop.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck_sizes,
dropout_rate=0.5,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(PeleeNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", StemBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
bottleneck_size = bottleneck_sizes[i]
stage = nn.Sequential()
if i != 0:
stage.add_module("trans{}".format(i + 1), TransitionBlock(
in_channels=in_channels,
out_channels=in_channels))
for j, out_channels in enumerate(channels_per_stage):
stage.add_module("unit{}".format(j + 1), DenseBlock(
in_channels=in_channels,
out_channels=out_channels,
bottleneck_size=bottleneck_size))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_block", conv1x1_block(
in_channels=in_channels,
out_channels=in_channels))
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Sequential()
self.output.add_module('dropout', nn.Dropout(p=dropout_rate))
self.output.add_module('fc', nn.Linear(
in_features=in_channels,
out_features=num_classes))
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_peleenet(model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create PeleeNet model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
init_block_channels = 32
growth_rate = 32
layers = [3, 4, 8, 6]
bottleneck_sizes = [1, 2, 4, 4]
from functools import reduce
channels = reduce(
lambda xi, yi: xi + [reduce(
lambda xj, yj: xj + [xj[-1] + yj],
[growth_rate] * yi,
[xi[-1][-1]])[1:]],
layers,
[[init_block_channels]])[1:]
net = PeleeNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck_sizes=bottleneck_sizes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def peleenet(**kwargs):
"""
PeleeNet model from 'Pelee: A Real-Time Object Detection System on Mobile Devices,'
https://arxiv.org/abs/1804.06882.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_peleenet(model_name="peleenet", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
peleenet,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != peleenet or weight_count == 2802248)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 10,827 | 27.419948 | 117 | py |
null | qimera-main/pytorchcv/models/pnasnet.py | """
PNASNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'Progressive Neural Architecture Search,' https://arxiv.org/abs/1712.00559.
"""
__all__ = ['PNASNet', 'pnasnet5large']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1
from .nasnet import nasnet_dual_path_sequential, nasnet_batch_norm, NasConv, NasDwsConv, NasPathBlock, NASNetInitBlock
class PnasMaxPoolBlock(nn.Module):
"""
PNASNet specific Max pooling layer with extra padding.
Parameters:
----------
stride : int or tuple/list of 2 int, default 2
Strides of the convolution.
extra_padding : bool, default False
Whether to use extra padding.
"""
def __init__(self,
stride=2,
extra_padding=False):
super(PnasMaxPoolBlock, self).__init__()
self.extra_padding = extra_padding
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=stride,
padding=1)
if self.extra_padding:
self.pad = nn.ZeroPad2d(padding=(1, 0, 1, 0))
def forward(self, x):
if self.extra_padding:
x = self.pad(x)
x = self.pool(x)
if self.extra_padding:
x = x[:, :, 1:, 1:].contiguous()
return x
def pnas_conv1x1(in_channels,
out_channels,
stride=1):
"""
1x1 version of the PNASNet specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
"""
return NasConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
stride=stride,
padding=0,
groups=1)
class DwsBranch(nn.Module):
"""
PNASNet specific block with depthwise separable convolution layers.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
extra_padding : bool, default False
Whether to use extra padding.
stem : bool, default False
Whether to use squeeze reduction if False.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
extra_padding=False,
stem=False):
super(DwsBranch, self).__init__()
assert (not stem) or (not extra_padding)
mid_channels = out_channels if stem else in_channels
padding = kernel_size // 2
self.conv1 = NasDwsConv(
in_channels=in_channels,
out_channels=mid_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
extra_padding=extra_padding)
self.conv2 = NasDwsConv(
in_channels=mid_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=1,
padding=padding)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
return x
def dws_branch_k3(in_channels,
out_channels,
stride=2,
extra_padding=False,
stem=False):
"""
3x3 version of the PNASNet specific depthwise separable convolution branch.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 2
Strides of the convolution.
extra_padding : bool, default False
Whether to use extra padding.
stem : bool, default False
Whether to use squeeze reduction if False.
"""
return DwsBranch(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=stride,
extra_padding=extra_padding,
stem=stem)
def dws_branch_k5(in_channels,
out_channels,
stride=2,
extra_padding=False,
stem=False):
"""
5x5 version of the PNASNet specific depthwise separable convolution branch.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 2
Strides of the convolution.
extra_padding : bool, default False
Whether to use extra padding.
stem : bool, default False
Whether to use squeeze reduction if False.
"""
return DwsBranch(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=5,
stride=stride,
extra_padding=extra_padding,
stem=stem)
def dws_branch_k7(in_channels,
out_channels,
stride=2,
extra_padding=False):
"""
7x7 version of the PNASNet specific depthwise separable convolution branch.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 2
Strides of the convolution.
extra_padding : bool, default False
Whether to use extra padding.
"""
return DwsBranch(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=7,
stride=stride,
extra_padding=extra_padding,
stem=False)
class PnasMaxPathBlock(nn.Module):
"""
PNASNet specific `max path` auxiliary block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(PnasMaxPathBlock, self).__init__()
self.maxpool = PnasMaxPoolBlock()
self.conv = conv1x1(
in_channels=in_channels,
out_channels=out_channels)
self.bn = nasnet_batch_norm(channels=out_channels)
def forward(self, x):
x = self.maxpool(x)
x = self.conv(x)
x = self.bn(x)
return x
class PnasBaseUnit(nn.Module):
"""
PNASNet base unit.
"""
def __init__(self):
super(PnasBaseUnit, self).__init__()
def cell_forward(self, x, x_prev):
assert (hasattr(self, 'comb0_left'))
x_left = x_prev
x_right = x
x0 = self.comb0_left(x_left) + self.comb0_right(x_left)
x1 = self.comb1_left(x_right) + self.comb1_right(x_right)
x2 = self.comb2_left(x_right) + self.comb2_right(x_right)
x3 = self.comb3_left(x2) + self.comb3_right(x_right)
x4 = self.comb4_left(x_left) + (self.comb4_right(x_right) if self.comb4_right else x_right)
x_out = torch.cat((x0, x1, x2, x3, x4), dim=1)
return x_out
class Stem1Unit(PnasBaseUnit):
"""
PNASNet Stem1 unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(Stem1Unit, self).__init__()
mid_channels = out_channels // 5
self.conv_1x1 = pnas_conv1x1(
in_channels=in_channels,
out_channels=mid_channels)
self.comb0_left = dws_branch_k5(
in_channels=in_channels,
out_channels=mid_channels,
stem=True)
self.comb0_right = PnasMaxPathBlock(
in_channels=in_channels,
out_channels=mid_channels)
self.comb1_left = dws_branch_k7(
in_channels=mid_channels,
out_channels=mid_channels)
self.comb1_right = PnasMaxPoolBlock()
self.comb2_left = dws_branch_k5(
in_channels=mid_channels,
out_channels=mid_channels)
self.comb2_right = dws_branch_k3(
in_channels=mid_channels,
out_channels=mid_channels)
self.comb3_left = dws_branch_k3(
in_channels=mid_channels,
out_channels=mid_channels,
stride=1)
self.comb3_right = PnasMaxPoolBlock()
self.comb4_left = dws_branch_k3(
in_channels=in_channels,
out_channels=mid_channels,
stem=True)
self.comb4_right = pnas_conv1x1(
in_channels=mid_channels,
out_channels=mid_channels,
stride=2)
def forward(self, x):
x_prev = x
x = self.conv_1x1(x)
x_out = self.cell_forward(x, x_prev)
return x_out
class PnasUnit(PnasBaseUnit):
"""
PNASNet ordinary unit.
Parameters:
----------
in_channels : int
Number of input channels.
prev_in_channels : int
Number of input channels in previous input.
out_channels : int
Number of output channels.
reduction : bool, default False
Whether to use reduction.
extra_padding : bool, default False
Whether to use extra padding.
match_prev_layer_dimensions : bool, default False
Whether to match previous layer dimensions.
"""
def __init__(self,
in_channels,
prev_in_channels,
out_channels,
reduction=False,
extra_padding=False,
match_prev_layer_dimensions=False):
super(PnasUnit, self).__init__()
mid_channels = out_channels // 5
stride = 2 if reduction else 1
if match_prev_layer_dimensions:
self.conv_prev_1x1 = NasPathBlock(
in_channels=prev_in_channels,
out_channels=mid_channels)
else:
self.conv_prev_1x1 = pnas_conv1x1(
in_channels=prev_in_channels,
out_channels=mid_channels)
self.conv_1x1 = pnas_conv1x1(
in_channels=in_channels,
out_channels=mid_channels)
self.comb0_left = dws_branch_k5(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride,
extra_padding=extra_padding)
self.comb0_right = PnasMaxPoolBlock(
stride=stride,
extra_padding=extra_padding)
self.comb1_left = dws_branch_k7(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride,
extra_padding=extra_padding)
self.comb1_right = PnasMaxPoolBlock(
stride=stride,
extra_padding=extra_padding)
self.comb2_left = dws_branch_k5(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride,
extra_padding=extra_padding)
self.comb2_right = dws_branch_k3(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride,
extra_padding=extra_padding)
self.comb3_left = dws_branch_k3(
in_channels=mid_channels,
out_channels=mid_channels,
stride=1)
self.comb3_right = PnasMaxPoolBlock(
stride=stride,
extra_padding=extra_padding)
self.comb4_left = dws_branch_k3(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride,
extra_padding=extra_padding)
if reduction:
self.comb4_right = pnas_conv1x1(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride)
else:
self.comb4_right = None
def forward(self, x, x_prev):
# print("x.shape={}, x_prev.shape={}".format(x.shape, x_prev.shape))
x_prev = self.conv_prev_1x1(x_prev)
x = self.conv_1x1(x)
x_out = self.cell_forward(x, x_prev)
return x_out
class PNASNet(nn.Module):
"""
PNASNet model from 'Progressive Neural Architecture Search,' https://arxiv.org/abs/1712.00559.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
stem1_blocks_channels : list of 2 int
Number of output channels for the Stem1 unit.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (331, 331)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
stem1_blocks_channels,
in_channels=3,
in_size=(331, 331),
num_classes=1000):
super(PNASNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nasnet_dual_path_sequential(
return_two=False,
first_ordinals=2,
last_ordinals=2)
self.features.add_module("init_block", NASNetInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
self.features.add_module("stem1_unit", Stem1Unit(
in_channels=in_channels,
out_channels=stem1_blocks_channels))
prev_in_channels = in_channels
in_channels = stem1_blocks_channels
for i, channels_per_stage in enumerate(channels):
stage = nasnet_dual_path_sequential()
for j, out_channels in enumerate(channels_per_stage):
reduction = (j == 0)
extra_padding = (j == 0) and (i not in [0, 2])
match_prev_layer_dimensions = (j == 1) or ((j == 0) and (i == 0))
stage.add_module("unit{}".format(j + 1), PnasUnit(
in_channels=in_channels,
prev_in_channels=prev_in_channels,
out_channels=out_channels,
reduction=reduction,
extra_padding=extra_padding,
match_prev_layer_dimensions=match_prev_layer_dimensions))
prev_in_channels = in_channels
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("activ", nn.ReLU())
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=11,
stride=1))
self.output = nn.Sequential()
self.output.add_module('dropout', nn.Dropout(p=0.5))
self.output.add_module('fc', nn.Linear(
in_features=in_channels,
out_features=num_classes))
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_pnasnet(model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create PNASNet model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
repeat = 4
init_block_channels = 96
stem_blocks_channels = [270, 540]
norm_channels = [1080, 2160, 4320]
channels = [[ci] * repeat for ci in norm_channels]
stem1_blocks_channels = stem_blocks_channels[0]
channels[0] = [stem_blocks_channels[1]] + channels[0]
net = PNASNet(
channels=channels,
init_block_channels=init_block_channels,
stem1_blocks_channels=stem1_blocks_channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def pnasnet5large(**kwargs):
"""
PNASNet-5-Large model from 'Progressive Neural Architecture Search,' https://arxiv.org/abs/1712.00559.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_pnasnet(model_name="pnasnet5large", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
pnasnet5large,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != pnasnet5large or weight_count == 86057668)
x = torch.randn(1, 3, 331, 331)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 18,176 | 28.945634 | 118 | py |
null | qimera-main/pytorchcv/models/polynet.py | """
PolyNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'PolyNet: A Pursuit of Structural Diversity in Very Deep Networks,'
https://arxiv.org/abs/1611.05725.
"""
__all__ = ['PolyNet', 'polynet']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import ConvBlock, conv1x1_block, conv3x3_block, Concurrent, ParametricSequential, ParametricConcurrent
class PolyConv(nn.Module):
"""
PolyNet specific convolution block. A block that is used inside poly-N (poly-2, poly-3, and so on) modules.
The Convolution layer is shared between all Inception blocks inside a poly-N module. BatchNorm layers are not
shared between Inception blocks and therefore the number of BatchNorm layers is equal to the number of Inception
blocks inside a poly-N module.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
num_blocks : int
Number of blocks (BatchNorm layers).
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
num_blocks):
super(PolyConv, self).__init__()
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
bias=False)
self.bns = nn.ModuleList()
for i in range(num_blocks):
self.bns.append(nn.BatchNorm2d(num_features=out_channels))
self.activ = nn.ReLU(inplace=True)
def forward(self, x, index):
x = self.conv(x)
x = self.bns[index](x)
x = self.activ(x)
return x
def poly_conv1x1(in_channels,
out_channels,
num_blocks):
"""
1x1 version of the PolyNet specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
num_blocks : int
Number of blocks (BatchNorm layers).
"""
return PolyConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
stride=1,
padding=0,
num_blocks=num_blocks)
class MaxPoolBranch(nn.Module):
"""
PolyNet specific max pooling branch block.
"""
def __init__(self):
super(MaxPoolBranch, self).__init__()
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=0)
def forward(self, x):
x = self.pool(x)
return x
class Conv1x1Branch(nn.Module):
"""
PolyNet specific convolutional 1x1 branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(Conv1x1Branch, self).__init__()
self.conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels)
def forward(self, x):
x = self.conv(x)
return x
class Conv3x3Branch(nn.Module):
"""
PolyNet specific convolutional 3x3 branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(Conv3x3Branch, self).__init__()
self.conv = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
stride=2,
padding=0)
def forward(self, x):
x = self.conv(x)
return x
class ConvSeqBranch(nn.Module):
"""
PolyNet specific convolutional sequence branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels_list : list of tuple of int
List of numbers of output channels.
kernel_size_list : list of tuple of int or tuple of tuple/list of 2 int
List of convolution window sizes.
strides_list : list of tuple of int or tuple of tuple/list of 2 int
List of strides of the convolution.
padding_list : list of tuple of int or tuple of tuple/list of 2 int
List of padding values for convolution layers.
"""
def __init__(self,
in_channels,
out_channels_list,
kernel_size_list,
strides_list,
padding_list):
super(ConvSeqBranch, self).__init__()
assert (len(out_channels_list) == len(kernel_size_list))
assert (len(out_channels_list) == len(strides_list))
assert (len(out_channels_list) == len(padding_list))
self.conv_list = nn.Sequential()
for i, (out_channels, kernel_size, strides, padding) in enumerate(zip(
out_channels_list, kernel_size_list, strides_list, padding_list)):
self.conv_list.add_module("conv{}".format(i + 1), ConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=strides,
padding=padding))
in_channels = out_channels
def forward(self, x):
x = self.conv_list(x)
return x
class PolyConvSeqBranch(nn.Module):
"""
PolyNet specific convolutional sequence branch block with internal PolyNet specific convolution blocks.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels_list : list of tuple of int
List of numbers of output channels.
kernel_size_list : list of tuple of int or tuple of tuple/list of 2 int
List of convolution window sizes.
strides_list : list of tuple of int or tuple of tuple/list of 2 int
List of strides of the convolution.
padding_list : list of tuple of int or tuple of tuple/list of 2 int
List of padding values for convolution layers.
num_blocks : int
Number of blocks for PolyConv.
"""
def __init__(self,
in_channels,
out_channels_list,
kernel_size_list,
strides_list,
padding_list,
num_blocks):
super(PolyConvSeqBranch, self).__init__()
assert (len(out_channels_list) == len(kernel_size_list))
assert (len(out_channels_list) == len(strides_list))
assert (len(out_channels_list) == len(padding_list))
self.conv_list = ParametricSequential()
for i, (out_channels, kernel_size, strides, padding) in enumerate(zip(
out_channels_list, kernel_size_list, strides_list, padding_list)):
self.conv_list.add_module("conv{}".format(i + 1), PolyConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=strides,
padding=padding,
num_blocks=num_blocks))
in_channels = out_channels
def forward(self, x, index):
x = self.conv_list(x, index=index)
return x
class TwoWayABlock(nn.Module):
"""
PolyNet type Inception-A block.
"""
def __init__(self):
super(TwoWayABlock, self).__init__()
in_channels = 384
self.branches = Concurrent()
self.branches.add_module("branch1", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(32, 48, 64),
kernel_size_list=(1, 3, 3),
strides_list=(1, 1, 1),
padding_list=(0, 1, 1)))
self.branches.add_module("branch2", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(32, 32),
kernel_size_list=(1, 3),
strides_list=(1, 1),
padding_list=(0, 1)))
self.branches.add_module("branch3", Conv1x1Branch(
in_channels=in_channels,
out_channels=32))
self.conv = conv1x1_block(
in_channels=128,
out_channels=in_channels,
activation=None)
def forward(self, x):
x = self.branches(x)
x = self.conv(x)
return x
class TwoWayBBlock(nn.Module):
"""
PolyNet type Inception-B block.
"""
def __init__(self):
super(TwoWayBBlock, self).__init__()
in_channels = 1152
self.branches = Concurrent()
self.branches.add_module("branch1", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(128, 160, 192),
kernel_size_list=(1, (1, 7), (7, 1)),
strides_list=(1, 1, 1),
padding_list=(0, (0, 3), (3, 0))))
self.branches.add_module("branch2", Conv1x1Branch(
in_channels=in_channels,
out_channels=192))
self.conv = conv1x1_block(
in_channels=384,
out_channels=in_channels,
activation=None)
def forward(self, x):
x = self.branches(x)
x = self.conv(x)
return x
class TwoWayCBlock(nn.Module):
"""
PolyNet type Inception-C block.
"""
def __init__(self):
super(TwoWayCBlock, self).__init__()
in_channels = 2048
self.branches = Concurrent()
self.branches.add_module("branch1", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(192, 224, 256),
kernel_size_list=(1, (1, 3), (3, 1)),
strides_list=(1, 1, 1),
padding_list=(0, (0, 1), (1, 0))))
self.branches.add_module("branch2", Conv1x1Branch(
in_channels=in_channels,
out_channels=192))
self.conv = conv1x1_block(
in_channels=448,
out_channels=in_channels,
activation=None)
def forward(self, x):
x = self.branches(x)
x = self.conv(x)
return x
class PolyPreBBlock(nn.Module):
"""
PolyNet type PolyResidual-Pre-B block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
num_blocks : int
Number of blocks (BatchNorm layers).
"""
def __init__(self,
num_blocks):
super(PolyPreBBlock, self).__init__()
in_channels = 1152
self.branches = ParametricConcurrent()
self.branches.add_module("branch1", PolyConvSeqBranch(
in_channels=in_channels,
out_channels_list=(128, 160, 192),
kernel_size_list=(1, (1, 7), (7, 1)),
strides_list=(1, 1, 1),
padding_list=(0, (0, 3), (3, 0)),
num_blocks=num_blocks))
self.branches.add_module("branch2", poly_conv1x1(
in_channels=in_channels,
out_channels=192,
num_blocks=num_blocks))
def forward(self, x, index):
x = self.branches(x, index=index)
return x
class PolyPreCBlock(nn.Module):
"""
PolyNet type PolyResidual-Pre-C block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
num_blocks : int
Number of blocks (BatchNorm layers).
"""
def __init__(self,
num_blocks):
super(PolyPreCBlock, self).__init__()
in_channels = 2048
self.branches = ParametricConcurrent()
self.branches.add_module("branch1", PolyConvSeqBranch(
in_channels=in_channels,
out_channels_list=(192, 224, 256),
kernel_size_list=(1, (1, 3), (3, 1)),
strides_list=(1, 1, 1),
padding_list=(0, (0, 1), (1, 0)),
num_blocks=num_blocks))
self.branches.add_module("branch2", poly_conv1x1(
in_channels=in_channels,
out_channels=192,
num_blocks=num_blocks))
def forward(self, x, index):
x = self.branches(x, index=index)
return x
def poly_res_b_block():
"""
PolyNet type PolyResidual-Res-B block.
"""
return conv1x1_block(
in_channels=384,
out_channels=1152,
stride=1,
activation=None)
def poly_res_c_block():
"""
PolyNet type PolyResidual-Res-C block.
"""
return conv1x1_block(
in_channels=448,
out_channels=2048,
stride=1,
activation=None)
class MultiResidual(nn.Module):
"""
Base class for constructing N-way modules (2-way, 3-way, and so on). Actually it is for 2-way modules.
Parameters:
----------
scale : float, default 1.0
Scale value for each residual branch.
res_block : Module class
Residual branch block.
num_blocks : int
Number of residual branches.
"""
def __init__(self,
scale,
res_block,
num_blocks):
super(MultiResidual, self).__init__()
assert (num_blocks >= 1)
self.scale = scale
self.res_blocks = nn.ModuleList([res_block() for _ in range(num_blocks)])
self.activ = nn.ReLU(inplace=False)
def forward(self, x):
out = x
for res_block in self.res_blocks:
out = out + self.scale * res_block(x)
out = self.activ(out)
return out
class PolyResidual(nn.Module):
"""
The other base class for constructing N-way poly-modules. Actually it is for 3-way poly-modules.
Parameters:
----------
scale : float, default 1.0
Scale value for each residual branch.
res_block : Module class
Residual branch block.
num_blocks : int
Number of residual branches.
pre_block : Module class
Preliminary block.
"""
def __init__(self,
scale,
res_block,
num_blocks,
pre_block):
super(PolyResidual, self).__init__()
assert (num_blocks >= 1)
self.scale = scale
self.pre_block = pre_block(num_blocks=num_blocks)
self.res_blocks = nn.ModuleList([res_block() for _ in range(num_blocks)])
self.activ = nn.ReLU(inplace=False)
def forward(self, x):
out = x
for index, res_block in enumerate(self.res_blocks):
x = self.pre_block(x, index)
x = res_block(x)
out = out + self.scale * x
x = self.activ(x)
out = self.activ(out)
return out
class PolyBaseUnit(nn.Module):
"""
PolyNet unit base class.
Parameters:
----------
two_way_scale : float
Scale value for 2-way stage.
two_way_block : Module class
Residual branch block for 2-way-stage.
poly_scale : float, default 0.0
Scale value for 2-way stage.
poly_res_block : Module class, default None
Residual branch block for poly-stage.
poly_pre_block : Module class, default None
Preliminary branch block for poly-stage.
"""
def __init__(self,
two_way_scale,
two_way_block,
poly_scale=0.0,
poly_res_block=None,
poly_pre_block=None):
super(PolyBaseUnit, self).__init__()
if poly_res_block is not None:
assert (poly_scale != 0.0)
assert (poly_pre_block is not None)
self.poly = PolyResidual(
scale=poly_scale,
res_block=poly_res_block,
num_blocks=3,
pre_block=poly_pre_block)
else:
assert (poly_scale == 0.0)
assert (poly_pre_block is None)
self.poly = None
self.twoway = MultiResidual(
scale=two_way_scale,
res_block=two_way_block,
num_blocks=2)
def forward(self, x):
if self.poly is not None:
x = self.poly(x)
x = self.twoway(x)
return x
class PolyAUnit(PolyBaseUnit):
"""
PolyNet type A unit.
Parameters:
----------
two_way_scale : float
Scale value for 2-way stage.
poly_scale : float
Scale value for 2-way stage.
"""
def __init__(self,
two_way_scale,
poly_scale=0.0):
super(PolyAUnit, self).__init__(
two_way_scale=two_way_scale,
two_way_block=TwoWayABlock)
assert (poly_scale == 0.0)
class PolyBUnit(PolyBaseUnit):
"""
PolyNet type B unit.
Parameters:
----------
two_way_scale : float
Scale value for 2-way stage.
poly_scale : float
Scale value for 2-way stage.
"""
def __init__(self,
two_way_scale,
poly_scale):
super(PolyBUnit, self).__init__(
two_way_scale=two_way_scale,
two_way_block=TwoWayBBlock,
poly_scale=poly_scale,
poly_res_block=poly_res_b_block,
poly_pre_block=PolyPreBBlock)
class PolyCUnit(PolyBaseUnit):
"""
PolyNet type C unit.
Parameters:
----------
two_way_scale : float
Scale value for 2-way stage.
poly_scale : float
Scale value for 2-way stage.
"""
def __init__(self,
two_way_scale,
poly_scale):
super(PolyCUnit, self).__init__(
two_way_scale=two_way_scale,
two_way_block=TwoWayCBlock,
poly_scale=poly_scale,
poly_res_block=poly_res_c_block,
poly_pre_block=PolyPreCBlock)
class ReductionAUnit(nn.Module):
"""
PolyNet type Reduction-A unit.
"""
def __init__(self):
super(ReductionAUnit, self).__init__()
in_channels = 384
self.branches = Concurrent()
self.branches.add_module("branch1", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(256, 256, 384),
kernel_size_list=(1, 3, 3),
strides_list=(1, 1, 2),
padding_list=(0, 1, 0)))
self.branches.add_module("branch2", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(384,),
kernel_size_list=(3,),
strides_list=(2,),
padding_list=(0,)))
self.branches.add_module("branch3", MaxPoolBranch())
def forward(self, x):
x = self.branches(x)
return x
class ReductionBUnit(nn.Module):
"""
PolyNet type Reduction-B unit.
"""
def __init__(self):
super(ReductionBUnit, self).__init__()
in_channels = 1152
self.branches = Concurrent()
self.branches.add_module("branch1", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(256, 256, 256),
kernel_size_list=(1, 3, 3),
strides_list=(1, 1, 2),
padding_list=(0, 1, 0)))
self.branches.add_module("branch2", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(256, 256),
kernel_size_list=(1, 3),
strides_list=(1, 2),
padding_list=(0, 0)))
self.branches.add_module("branch3", ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(256, 384),
kernel_size_list=(1, 3),
strides_list=(1, 2),
padding_list=(0, 0)))
self.branches.add_module("branch4", MaxPoolBranch())
def forward(self, x):
x = self.branches(x)
return x
class PolyBlock3a(nn.Module):
"""
PolyNet type Mixed-3a block.
"""
def __init__(self):
super(PolyBlock3a, self).__init__()
self.branches = Concurrent()
self.branches.add_module("branch1", MaxPoolBranch())
self.branches.add_module("branch2", Conv3x3Branch(
in_channels=64,
out_channels=96))
def forward(self, x):
x = self.branches(x)
return x
class PolyBlock4a(nn.Module):
"""
PolyNet type Mixed-4a block.
"""
def __init__(self):
super(PolyBlock4a, self).__init__()
self.branches = Concurrent()
self.branches.add_module("branch1", ConvSeqBranch(
in_channels=160,
out_channels_list=(64, 96),
kernel_size_list=(1, 3),
strides_list=(1, 1),
padding_list=(0, 0)))
self.branches.add_module("branch2", ConvSeqBranch(
in_channels=160,
out_channels_list=(64, 64, 64, 96),
kernel_size_list=(1, (7, 1), (1, 7), 3),
strides_list=(1, 1, 1, 1),
padding_list=(0, (3, 0), (0, 3), 0)))
def forward(self, x):
x = self.branches(x)
return x
class PolyBlock5a(nn.Module):
"""
PolyNet type Mixed-5a block.
"""
def __init__(self):
super(PolyBlock5a, self).__init__()
self.branches = Concurrent()
self.branches.add_module("branch1", MaxPoolBranch())
self.branches.add_module("branch2", Conv3x3Branch(
in_channels=192,
out_channels=192))
def forward(self, x):
x = self.branches(x)
return x
class PolyInitBlock(nn.Module):
"""
PolyNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
"""
def __init__(self,
in_channels):
super(PolyInitBlock, self).__init__()
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=32,
stride=2,
padding=0)
self.conv2 = conv3x3_block(
in_channels=32,
out_channels=32,
padding=0)
self.conv3 = conv3x3_block(
in_channels=32,
out_channels=64)
self.block1 = PolyBlock3a()
self.block2 = PolyBlock4a()
self.block3 = PolyBlock5a()
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.block1(x)
x = self.block2(x)
x = self.block3(x)
return x
class PolyNet(nn.Module):
"""
PolyNet model from 'PolyNet: A Pursuit of Structural Diversity in Very Deep Networks,'
https://arxiv.org/abs/1611.05725.
Parameters:
----------
two_way_scales : list of list of floats
Two way scale values for each normal unit.
poly_scales : list of list of floats
Three way scale values for each normal unit.
dropout_rate : float, default 0.2
Fraction of the input units to drop. Must be a number between 0 and 1.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (331, 331)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
two_way_scales,
poly_scales,
dropout_rate=0.2,
in_channels=3,
in_size=(331, 331),
num_classes=1000):
super(PolyNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
normal_units = [PolyAUnit, PolyBUnit, PolyCUnit]
reduction_units = [ReductionAUnit, ReductionBUnit]
self.features = nn.Sequential()
self.features.add_module("init_block", PolyInitBlock(
in_channels=in_channels))
for i, (two_way_scales_per_stage, poly_scales_per_stage) in enumerate(zip(two_way_scales, poly_scales)):
stage = nn.Sequential()
for j, (two_way_scale, poly_scale) in enumerate(zip(two_way_scales_per_stage, poly_scales_per_stage)):
if (j == 0) and (i != 0):
unit = reduction_units[i - 1]
stage.add_module("unit{}".format(j + 1), unit())
else:
unit = normal_units[i]
stage.add_module("unit{}".format(j + 1), unit(
two_way_scale=two_way_scale,
poly_scale=poly_scale))
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=9,
stride=1))
self.output = nn.Sequential()
self.output.add_module('dropout', nn.Dropout(p=dropout_rate))
self.output.add_module('fc', nn.Linear(
in_features=2048,
out_features=num_classes))
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_polynet(model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create PolyNet model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
two_way_scales = [
[1.000000, 0.992308, 0.984615, 0.976923, 0.969231, 0.961538, 0.953846, 0.946154, 0.938462, 0.930769],
[0.000000, 0.915385, 0.900000, 0.884615, 0.869231, 0.853846, 0.838462, 0.823077, 0.807692, 0.792308, 0.776923],
[0.000000, 0.761538, 0.746154, 0.730769, 0.715385, 0.700000]]
poly_scales = [
[0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],
[0.000000, 0.923077, 0.907692, 0.892308, 0.876923, 0.861538, 0.846154, 0.830769, 0.815385, 0.800000, 0.784615],
[0.000000, 0.769231, 0.753846, 0.738462, 0.723077, 0.707692]]
net = PolyNet(
two_way_scales=two_way_scales,
poly_scales=poly_scales,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def polynet(**kwargs):
"""
PolyNet model from 'PolyNet: A Pursuit of Structural Diversity in Very Deep Networks,'
https://arxiv.org/abs/1611.05725.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_polynet(model_name="polynet", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
polynet,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != polynet or weight_count == 95366600)
x = torch.randn(1, 3, 331, 331)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 28,281 | 28.928042 | 119 | py |
null | qimera-main/pytorchcv/models/preresnet.py | """
PreResNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027.
"""
__all__ = ['PreResNet', 'preresnet10', 'preresnet12', 'preresnet14', 'preresnetbc14b', 'preresnet16', 'preresnet18_wd4',
'preresnet18_wd2', 'preresnet18_w3d4', 'preresnet18', 'preresnet26', 'preresnetbc26b', 'preresnet34',
'preresnetbc38b', 'preresnet50', 'preresnet50b', 'preresnet101', 'preresnet101b', 'preresnet152',
'preresnet152b', 'preresnet200', 'preresnet200b', 'preresnet269b', 'PreResBlock', 'PreResBottleneck',
'PreResUnit', 'PreResInitBlock', 'PreResActivation']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import pre_conv1x1_block, pre_conv3x3_block, conv1x1
class PreResBlock(nn.Module):
"""
Simple PreResNet block for residual path in ResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
"""
def __init__(self,
in_channels,
out_channels,
stride):
super(PreResBlock, self).__init__()
self.conv1 = pre_conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
return_preact=True)
self.conv2 = pre_conv3x3_block(
in_channels=out_channels,
out_channels=out_channels)
def forward(self, x):
x, x_pre_activ = self.conv1(x)
x = self.conv2(x)
return x, x_pre_activ
class PreResBottleneck(nn.Module):
"""
PreResNet bottleneck block for residual path in PreResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer of the block.
"""
def __init__(self,
in_channels,
out_channels,
stride,
conv1_stride):
super(PreResBottleneck, self).__init__()
mid_channels = out_channels // 4
self.conv1 = pre_conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
stride=(stride if conv1_stride else 1),
return_preact=True)
self.conv2 = pre_conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
stride=(1 if conv1_stride else stride))
self.conv3 = pre_conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels)
def forward(self, x):
x, x_pre_activ = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x, x_pre_activ
class PreResUnit(nn.Module):
"""
PreResNet unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer of the block.
"""
def __init__(self,
in_channels,
out_channels,
stride,
bottleneck,
conv1_stride):
super(PreResUnit, self).__init__()
self.resize_identity = (in_channels != out_channels) or (stride != 1)
if bottleneck:
self.body = PreResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
conv1_stride=conv1_stride)
else:
self.body = PreResBlock(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
if self.resize_identity:
self.identity_conv = conv1x1(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
def forward(self, x):
identity = x
x, x_pre_activ = self.body(x)
if self.resize_identity:
identity = self.identity_conv(x_pre_activ)
x = x + identity
return x
class PreResInitBlock(nn.Module):
"""
PreResNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(PreResInitBlock, self).__init__()
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=7,
stride=2,
padding=3,
bias=False)
self.bn = nn.BatchNorm2d(num_features=out_channels)
self.activ = nn.ReLU(inplace=True)
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=1)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
x = self.activ(x)
x = self.pool(x)
return x
class PreResActivation(nn.Module):
"""
PreResNet pure pre-activation block without convolution layer. It's used by itself as the final block.
Parameters:
----------
in_channels : int
Number of input channels.
"""
def __init__(self,
in_channels):
super(PreResActivation, self).__init__()
self.bn = nn.BatchNorm2d(num_features=in_channels)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
x = self.bn(x)
x = self.activ(x)
return x
class PreResNet(nn.Module):
"""
PreResNet model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer in units.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
conv1_stride,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(PreResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", PreResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 1 if (i == 0) or (j != 0) else 2
stage.add_module("unit{}".format(j + 1), PreResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck,
conv1_stride=conv1_stride))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("post_activ", PreResActivation(in_channels=in_channels))
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_preresnet(blocks,
bottleneck=None,
conv1_stride=True,
width_scale=1.0,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create PreResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
bottleneck : bool, default None
Whether to use a bottleneck or simple block in units.
conv1_stride : bool, default True
Whether to use stride in the first or the second convolution layer in units.
width_scale : float, default 1.0
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if bottleneck is None:
bottleneck = (blocks >= 50)
if blocks == 10:
layers = [1, 1, 1, 1]
elif blocks == 12:
layers = [2, 1, 1, 1]
elif blocks == 14 and not bottleneck:
layers = [2, 2, 1, 1]
elif (blocks == 14) and bottleneck:
layers = [1, 1, 1, 1]
elif blocks == 16:
layers = [2, 2, 2, 1]
elif blocks == 18:
layers = [2, 2, 2, 2]
elif (blocks == 26) and not bottleneck:
layers = [3, 3, 3, 3]
elif (blocks == 26) and bottleneck:
layers = [2, 2, 2, 2]
elif blocks == 34:
layers = [3, 4, 6, 3]
elif (blocks == 38) and bottleneck:
layers = [3, 3, 3, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
elif blocks == 200:
layers = [3, 24, 36, 3]
elif blocks == 269:
layers = [3, 30, 48, 8]
else:
raise ValueError("Unsupported PreResNet with number of blocks: {}".format(blocks))
if bottleneck:
assert (sum(layers) * 3 + 2 == blocks)
else:
assert (sum(layers) * 2 + 2 == blocks)
init_block_channels = 64
channels_per_layers = [64, 128, 256, 512]
if bottleneck:
bottleneck_factor = 4
channels_per_layers = [ci * bottleneck_factor for ci in channels_per_layers]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if width_scale != 1.0:
channels = [[int(cij * width_scale) if (i != len(channels) - 1) or (j != len(ci) - 1) else cij
for j, cij in enumerate(ci)] for i, ci in enumerate(channels)]
init_block_channels = int(init_block_channels * width_scale)
net = PreResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def preresnet10(**kwargs):
"""
PreResNet-10 model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet(blocks=10, model_name="preresnet10", **kwargs)
def preresnet12(**kwargs):
"""
PreResNet-12 model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet(blocks=12, model_name="preresnet12", **kwargs)
def preresnet14(**kwargs):
"""
PreResNet-14 model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet(blocks=14, model_name="preresnet14", **kwargs)
def preresnetbc14b(**kwargs):
"""
PreResNet-BC-14b model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027.
It's an experimental model (bottleneck compressed).
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet(blocks=14, bottleneck=True, conv1_stride=False, model_name="preresnetbc14b", **kwargs)
def preresnet16(**kwargs):
"""
PreResNet-16 model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet(blocks=16, model_name="preresnet16", **kwargs)
def preresnet18_wd4(**kwargs):
"""
PreResNet-18 model with 0.25 width scale from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027. It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet(blocks=18, width_scale=0.25, model_name="preresnet18_wd4", **kwargs)
def preresnet18_wd2(**kwargs):
"""
PreResNet-18 model with 0.5 width scale from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027. It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet(blocks=18, width_scale=0.5, model_name="preresnet18_wd2", **kwargs)
def preresnet18_w3d4(**kwargs):
"""
PreResNet-18 model with 0.75 width scale from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027. It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet(blocks=18, width_scale=0.75, model_name="preresnet18_w3d4", **kwargs)
def preresnet18(**kwargs):
"""
PreResNet-18 model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet(blocks=18, model_name="preresnet18", **kwargs)
def preresnet26(**kwargs):
"""
PreResNet-26 model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet(blocks=26, bottleneck=False, model_name="preresnet26", **kwargs)
def preresnetbc26b(**kwargs):
"""
PreResNet-BC-26b model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027.
It's an experimental model (bottleneck compressed).
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet(blocks=26, bottleneck=True, conv1_stride=False, model_name="preresnetbc26b", **kwargs)
def preresnet34(**kwargs):
"""
PreResNet-34 model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet(blocks=34, model_name="preresnet34", **kwargs)
def preresnetbc38b(**kwargs):
"""
PreResNet-BC-38b model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027.
It's an experimental model (bottleneck compressed).
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet(blocks=38, bottleneck=True, conv1_stride=False, model_name="preresnetbc38b", **kwargs)
def preresnet50(**kwargs):
"""
PreResNet-50 model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet(blocks=50, model_name="preresnet50", **kwargs)
def preresnet50b(**kwargs):
"""
PreResNet-50 model with stride at the second convolution in bottleneck block from 'Identity Mappings in Deep
Residual Networks,' https://arxiv.org/abs/1603.05027.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet(blocks=50, conv1_stride=False, model_name="preresnet50b", **kwargs)
def preresnet101(**kwargs):
"""
PreResNet-101 model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet(blocks=101, model_name="preresnet101", **kwargs)
def preresnet101b(**kwargs):
"""
PreResNet-101 model with stride at the second convolution in bottleneck block from 'Identity Mappings in Deep
Residual Networks,' https://arxiv.org/abs/1603.05027.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet(blocks=101, conv1_stride=False, model_name="preresnet101b", **kwargs)
def preresnet152(**kwargs):
"""
PreResNet-152 model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet(blocks=152, model_name="preresnet152", **kwargs)
def preresnet152b(**kwargs):
"""
PreResNet-152 model with stride at the second convolution in bottleneck block from 'Identity Mappings in Deep
Residual Networks,' https://arxiv.org/abs/1603.05027.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet(blocks=152, conv1_stride=False, model_name="preresnet152b", **kwargs)
def preresnet200(**kwargs):
"""
PreResNet-200 model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet(blocks=200, model_name="preresnet200", **kwargs)
def preresnet200b(**kwargs):
"""
PreResNet-200 model with stride at the second convolution in bottleneck block from 'Identity Mappings in Deep
Residual Networks,' https://arxiv.org/abs/1603.05027.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet(blocks=200, conv1_stride=False, model_name="preresnet200b", **kwargs)
def preresnet269b(**kwargs):
"""
PreResNet-269 model with stride at the second convolution in bottleneck block from 'Identity Mappings in Deep
Residual Networks,' https://arxiv.org/abs/1603.05027.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet(blocks=269, conv1_stride=False, model_name="preresnet269b", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
preresnet10,
preresnet12,
preresnet14,
preresnetbc14b,
preresnet16,
preresnet18_wd4,
preresnet18_wd2,
preresnet18_w3d4,
preresnet18,
preresnet26,
preresnetbc26b,
preresnet34,
preresnetbc38b,
preresnet50,
preresnet50b,
preresnet101,
preresnet101b,
preresnet152,
preresnet152b,
preresnet200,
preresnet200b,
preresnet269b,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != preresnet10 or weight_count == 5417128)
assert (model != preresnet12 or weight_count == 5491112)
assert (model != preresnet14 or weight_count == 5786536)
assert (model != preresnetbc14b or weight_count == 10057384)
assert (model != preresnet16 or weight_count == 6967208)
assert (model != preresnet18_wd4 or weight_count == 3935960)
assert (model != preresnet18_wd2 or weight_count == 5802440)
assert (model != preresnet18_w3d4 or weight_count == 8473784)
assert (model != preresnet18 or weight_count == 11687848)
assert (model != preresnet26 or weight_count == 17958568)
assert (model != preresnetbc26b or weight_count == 15987624)
assert (model != preresnet34 or weight_count == 21796008)
assert (model != preresnetbc38b or weight_count == 21917864)
assert (model != preresnet50 or weight_count == 25549480)
assert (model != preresnet50b or weight_count == 25549480)
assert (model != preresnet101 or weight_count == 44541608)
assert (model != preresnet101b or weight_count == 44541608)
assert (model != preresnet152 or weight_count == 60185256)
assert (model != preresnet152b or weight_count == 60185256)
assert (model != preresnet200 or weight_count == 64666280)
assert (model != preresnet200b or weight_count == 64666280)
assert (model != preresnet269b or weight_count == 102065832)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 25,857 | 32.024266 | 120 | py |
null | qimera-main/pytorchcv/models/preresnet_cifar.py | """
PreResNet for CIFAR/SVHN, implemented in PyTorch.
Original papers: 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027.
"""
__all__ = ['CIFARPreResNet', 'preresnet20_cifar10', 'preresnet20_cifar100', 'preresnet20_svhn',
'preresnet56_cifar10', 'preresnet56_cifar100', 'preresnet56_svhn',
'preresnet110_cifar10', 'preresnet110_cifar100', 'preresnet110_svhn',
'preresnet164bn_cifar10', 'preresnet164bn_cifar100', 'preresnet164bn_svhn',
'preresnet272bn_cifar10', 'preresnet272bn_cifar100', 'preresnet272bn_svhn',
'preresnet542bn_cifar10', 'preresnet542bn_cifar100', 'preresnet542bn_svhn',
'preresnet1001_cifar10', 'preresnet1001_cifar100', 'preresnet1001_svhn',
'preresnet1202_cifar10', 'preresnet1202_cifar100', 'preresnet1202_svhn']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv3x3
from .preresnet import PreResUnit, PreResActivation
class CIFARPreResNet(nn.Module):
"""
PreResNet model for CIFAR from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
num_classes : int, default 10
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
in_channels=3,
in_size=(32, 32),
num_classes=10):
super(CIFARPreResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", conv3x3(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), PreResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck,
conv1_stride=False))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("post_activ", PreResActivation(in_channels=in_channels))
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=8,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_preresnet_cifar(num_classes,
blocks,
bottleneck,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create PreResNet model for CIFAR with specific parameters.
Parameters:
----------
num_classes : int
Number of classification classes.
blocks : int
Number of blocks.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
assert (num_classes in [10, 100])
if bottleneck:
assert ((blocks - 2) % 9 == 0)
layers = [(blocks - 2) // 9] * 3
else:
assert ((blocks - 2) % 6 == 0)
layers = [(blocks - 2) // 6] * 3
channels_per_layers = [16, 32, 64]
init_block_channels = 16
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if bottleneck:
channels = [[cij * 4 for cij in ci] for ci in channels]
net = CIFARPreResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
num_classes=num_classes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def preresnet20_cifar10(num_classes=10, **kwargs):
"""
PreResNet-20 model for CIFAR-10 from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=20, bottleneck=False, model_name="preresnet20_cifar10",
**kwargs)
def preresnet20_cifar100(num_classes=100, **kwargs):
"""
PreResNet-20 model for CIFAR-100 from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=20, bottleneck=False, model_name="preresnet20_cifar100",
**kwargs)
def preresnet20_svhn(num_classes=10, **kwargs):
"""
PreResNet-20 model for SVHN from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=20, bottleneck=False, model_name="preresnet20_svhn",
**kwargs)
def preresnet56_cifar10(num_classes=10, **kwargs):
"""
PreResNet-56 model for CIFAR-10 from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=56, bottleneck=False, model_name="preresnet56_cifar10",
**kwargs)
def preresnet56_cifar100(num_classes=100, **kwargs):
"""
PreResNet-56 model for CIFAR-100 from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=56, bottleneck=False, model_name="preresnet56_cifar100",
**kwargs)
def preresnet56_svhn(num_classes=10, **kwargs):
"""
PreResNet-56 model for SVHN from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=56, bottleneck=False, model_name="preresnet56_svhn",
**kwargs)
def preresnet110_cifar10(num_classes=10, **kwargs):
"""
PreResNet-110 model for CIFAR-10 from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=110, bottleneck=False, model_name="preresnet110_cifar10",
**kwargs)
def preresnet110_cifar100(num_classes=100, **kwargs):
"""
PreResNet-110 model for CIFAR-100 from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=110, bottleneck=False,
model_name="preresnet110_cifar100", **kwargs)
def preresnet110_svhn(num_classes=10, **kwargs):
"""
PreResNet-110 model for SVHN from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=110, bottleneck=False, model_name="preresnet110_svhn",
**kwargs)
def preresnet164bn_cifar10(num_classes=10, **kwargs):
"""
PreResNet-164(BN) model for CIFAR-10 from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=164, bottleneck=True,
model_name="preresnet164bn_cifar10", **kwargs)
def preresnet164bn_cifar100(num_classes=100, **kwargs):
"""
PreResNet-164(BN) model for CIFAR-100 from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=164, bottleneck=True,
model_name="preresnet164bn_cifar100", **kwargs)
def preresnet164bn_svhn(num_classes=10, **kwargs):
"""
PreResNet-164(BN) model for SVHN from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=164, bottleneck=True,
model_name="preresnet164bn_svhn", **kwargs)
def preresnet272bn_cifar10(num_classes=10, **kwargs):
"""
PreResNet-272(BN) model for CIFAR-10 from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=272, bottleneck=True,
model_name="preresnet272bn_cifar10", **kwargs)
def preresnet272bn_cifar100(num_classes=100, **kwargs):
"""
PreResNet-272(BN) model for CIFAR-100 from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=272, bottleneck=True,
model_name="preresnet272bn_cifar100", **kwargs)
def preresnet272bn_svhn(num_classes=10, **kwargs):
"""
PreResNet-272(BN) model for SVHN from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=272, bottleneck=True,
model_name="preresnet272bn_svhn", **kwargs)
def preresnet542bn_cifar10(num_classes=10, **kwargs):
"""
PreResNet-542(BN) model for CIFAR-10 from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=542, bottleneck=True,
model_name="preresnet542bn_cifar10", **kwargs)
def preresnet542bn_cifar100(num_classes=100, **kwargs):
"""
PreResNet-542(BN) model for CIFAR-100 from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=542, bottleneck=True,
model_name="preresnet542bn_cifar100", **kwargs)
def preresnet542bn_svhn(num_classes=10, **kwargs):
"""
PreResNet-542(BN) model for SVHN from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=542, bottleneck=True,
model_name="preresnet542bn_svhn", **kwargs)
def preresnet1001_cifar10(num_classes=10, **kwargs):
"""
PreResNet-1001 model for CIFAR-10 from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=1001, bottleneck=True,
model_name="preresnet1001_cifar10", **kwargs)
def preresnet1001_cifar100(num_classes=100, **kwargs):
"""
PreResNet-1001 model for CIFAR-100 from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=1001, bottleneck=True,
model_name="preresnet1001_cifar100", **kwargs)
def preresnet1001_svhn(num_classes=10, **kwargs):
"""
PreResNet-1001 model for SVHN from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=1001, bottleneck=True,
model_name="preresnet1001_svhn", **kwargs)
def preresnet1202_cifar10(num_classes=10, **kwargs):
"""
PreResNet-1202 model for CIFAR-10 from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=1202, bottleneck=False,
model_name="preresnet1202_cifar10", **kwargs)
def preresnet1202_cifar100(num_classes=100, **kwargs):
"""
PreResNet-1202 model for CIFAR-100 from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=1202, bottleneck=False,
model_name="preresnet1202_cifar100", **kwargs)
def preresnet1202_svhn(num_classes=10, **kwargs):
"""
PreResNet-1202 model for SVHN from 'Identity Mappings in Deep Residual Networks,'
https://arxiv.org/abs/1603.05027.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_preresnet_cifar(num_classes=num_classes, blocks=1202, bottleneck=False,
model_name="preresnet1202_svhn", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
(preresnet20_cifar10, 10),
(preresnet20_cifar100, 100),
(preresnet20_svhn, 10),
(preresnet56_cifar10, 10),
(preresnet56_cifar100, 100),
(preresnet56_svhn, 10),
(preresnet110_cifar10, 10),
(preresnet110_cifar100, 100),
(preresnet110_svhn, 10),
(preresnet164bn_cifar10, 10),
(preresnet164bn_cifar100, 100),
(preresnet164bn_svhn, 10),
(preresnet272bn_cifar10, 10),
(preresnet272bn_cifar100, 100),
(preresnet272bn_svhn, 10),
(preresnet542bn_cifar10, 10),
(preresnet542bn_cifar100, 100),
(preresnet542bn_svhn, 10),
(preresnet1001_cifar10, 10),
(preresnet1001_cifar100, 100),
(preresnet1001_svhn, 10),
(preresnet1202_cifar10, 10),
(preresnet1202_cifar100, 100),
(preresnet1202_svhn, 10),
]
for model, num_classes in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != preresnet20_cifar10 or weight_count == 272282)
assert (model != preresnet20_cifar100 or weight_count == 278132)
assert (model != preresnet20_svhn or weight_count == 272282)
assert (model != preresnet56_cifar10 or weight_count == 855578)
assert (model != preresnet56_cifar100 or weight_count == 861428)
assert (model != preresnet56_svhn or weight_count == 855578)
assert (model != preresnet110_cifar10 or weight_count == 1730522)
assert (model != preresnet110_cifar100 or weight_count == 1736372)
assert (model != preresnet110_svhn or weight_count == 1730522)
assert (model != preresnet164bn_cifar10 or weight_count == 1703258)
assert (model != preresnet164bn_cifar100 or weight_count == 1726388)
assert (model != preresnet164bn_svhn or weight_count == 1703258)
assert (model != preresnet272bn_cifar10 or weight_count == 2816090)
assert (model != preresnet272bn_cifar100 or weight_count == 2839220)
assert (model != preresnet272bn_svhn or weight_count == 2816090)
assert (model != preresnet542bn_cifar10 or weight_count == 5598170)
assert (model != preresnet542bn_cifar100 or weight_count == 5621300)
assert (model != preresnet542bn_svhn or weight_count == 5598170)
assert (model != preresnet1001_cifar10 or weight_count == 10327706)
assert (model != preresnet1001_cifar100 or weight_count == 10350836)
assert (model != preresnet1001_svhn or weight_count == 10327706)
assert (model != preresnet1202_cifar10 or weight_count == 19423834)
assert (model != preresnet1202_cifar100 or weight_count == 19429684)
assert (model != preresnet1202_svhn or weight_count == 19423834)
x = torch.randn(1, 3, 32, 32)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, num_classes))
if __name__ == "__main__":
_test()
| 24,611 | 35.789238 | 120 | py |
null | qimera-main/pytorchcv/models/proxylessnas.py | """
ProxylessNAS for ImageNet-1K, implemented in PyTorch.
Original paper: 'ProxylessNAS: Direct Neural Architecture Search on Target Task and Hardware,'
https://arxiv.org/abs/1812.00332.
"""
__all__ = ['ProxylessNAS', 'proxylessnas_cpu', 'proxylessnas_gpu', 'proxylessnas_mobile', 'proxylessnas_mobile14',
'ProxylessUnit', 'get_proxylessnas']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import ConvBlock, conv1x1_block, conv3x3_block
class ProxylessBlock(nn.Module):
"""
ProxylessNAS block for residual path in ProxylessNAS unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int
Convolution window size.
stride : int
Strides of the convolution.
bn_eps : float
Small float added to variance in Batch norm.
expansion : int
Expansion ratio.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
bn_eps,
expansion):
super(ProxylessBlock, self).__init__()
self.use_bc = (expansion > 1)
mid_channels = in_channels * expansion
if self.use_bc:
self.bc_conv = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
bn_eps=bn_eps,
activation="relu6")
padding = (kernel_size - 1) // 2
self.dw_conv = ConvBlock(
in_channels=mid_channels,
out_channels=mid_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
groups=mid_channels,
bn_eps=bn_eps,
activation="relu6")
self.pw_conv = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
bn_eps=bn_eps,
activation=None)
def forward(self, x):
if self.use_bc:
x = self.bc_conv(x)
x = self.dw_conv(x)
x = self.pw_conv(x)
return x
class ProxylessUnit(nn.Module):
"""
ProxylessNAS unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int
Convolution window size for body block.
stride : int
Strides of the convolution.
bn_eps : float
Small float added to variance in Batch norm.
expansion : int
Expansion ratio for body block.
residual : bool
Whether to use residual branch.
shortcut : bool
Whether to use identity branch.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
bn_eps,
expansion,
residual,
shortcut):
super(ProxylessUnit, self).__init__()
assert (residual or shortcut)
self.residual = residual
self.shortcut = shortcut
if self.residual:
self.body = ProxylessBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
bn_eps=bn_eps,
expansion=expansion)
def forward(self, x):
if not self.residual:
return x
if not self.shortcut:
return self.body(x)
identity = x
x = self.body(x)
x = identity + x
return x
class ProxylessNAS(nn.Module):
"""
ProxylessNAS model from 'ProxylessNAS: Direct Neural Architecture Search on Target Task and Hardware,'
https://arxiv.org/abs/1812.00332.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
final_block_channels : int
Number of output channels for the final unit.
residuals : list of list of int
Whether to use residual branch in units.
shortcuts : list of list of int
Whether to use identity branch in units.
kernel_sizes : list of list of int
Convolution window size for each units.
expansions : list of list of int
Expansion ratio for each units.
bn_eps : float, default 1e-3
Small float added to variance in Batch norm.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
final_block_channels,
residuals,
shortcuts,
kernel_sizes,
expansions,
bn_eps=1e-3,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(ProxylessNAS, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels,
stride=2,
bn_eps=bn_eps,
activation="relu6"))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
residuals_per_stage = residuals[i]
shortcuts_per_stage = shortcuts[i]
kernel_sizes_per_stage = kernel_sizes[i]
expansions_per_stage = expansions[i]
for j, out_channels in enumerate(channels_per_stage):
residual = (residuals_per_stage[j] == 1)
shortcut = (shortcuts_per_stage[j] == 1)
kernel_size = kernel_sizes_per_stage[j]
expansion = expansions_per_stage[j]
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), ProxylessUnit(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
bn_eps=bn_eps,
expansion=expansion,
residual=residual,
shortcut=shortcut))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_block", conv1x1_block(
in_channels=in_channels,
out_channels=final_block_channels,
bn_eps=bn_eps,
activation="relu6"))
in_channels = final_block_channels
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_proxylessnas(version,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create ProxylessNAS model with specific parameters.
Parameters:
----------
version : str
Version of ProxylessNAS ('cpu', 'gpu', 'mobile' or 'mobile14').
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if version == "cpu":
residuals = [[1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]
channels = [[24], [32, 32, 32, 32], [48, 48, 48, 48], [88, 88, 88, 88, 104, 104, 104, 104],
[216, 216, 216, 216, 360]]
kernel_sizes = [[3], [3, 3, 3, 3], [3, 3, 3, 5], [3, 3, 3, 3, 5, 3, 3, 3], [5, 5, 5, 3, 5]]
expansions = [[1], [6, 3, 3, 3], [6, 3, 3, 3], [6, 3, 3, 3, 6, 3, 3, 3], [6, 3, 3, 3, 6]]
init_block_channels = 40
final_block_channels = 1432
elif version == "gpu":
residuals = [[1], [1, 0, 0, 0], [1, 0, 0, 1], [1, 0, 0, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1]]
channels = [[24], [32, 32, 32, 32], [56, 56, 56, 56], [112, 112, 112, 112, 128, 128, 128, 128],
[256, 256, 256, 256, 432]]
kernel_sizes = [[3], [5, 3, 3, 3], [7, 3, 3, 3], [7, 5, 5, 5, 5, 3, 3, 5], [7, 7, 7, 5, 7]]
expansions = [[1], [3, 3, 3, 3], [3, 3, 3, 3], [6, 3, 3, 3, 6, 3, 3, 3], [6, 6, 6, 6, 6]]
init_block_channels = 40
final_block_channels = 1728
elif version == "mobile":
residuals = [[1], [1, 1, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]
channels = [[16], [32, 32, 32, 32], [40, 40, 40, 40], [80, 80, 80, 80, 96, 96, 96, 96],
[192, 192, 192, 192, 320]]
kernel_sizes = [[3], [5, 3, 3, 3], [7, 3, 5, 5], [7, 5, 5, 5, 5, 5, 5, 5], [7, 7, 7, 7, 7]]
expansions = [[1], [3, 3, 3, 3], [3, 3, 3, 3], [6, 3, 3, 3, 6, 3, 3, 3], [6, 6, 3, 3, 6]]
init_block_channels = 32
final_block_channels = 1280
elif version == "mobile14":
residuals = [[1], [1, 1, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]
channels = [[24], [40, 40, 40, 40], [56, 56, 56, 56], [112, 112, 112, 112, 136, 136, 136, 136],
[256, 256, 256, 256, 448]]
kernel_sizes = [[3], [5, 3, 3, 3], [7, 3, 5, 5], [7, 5, 5, 5, 5, 5, 5, 5], [7, 7, 7, 7, 7]]
expansions = [[1], [3, 3, 3, 3], [3, 3, 3, 3], [6, 3, 3, 3, 6, 3, 3, 3], [6, 6, 3, 3, 6]]
init_block_channels = 48
final_block_channels = 1792
else:
raise ValueError("Unsupported ProxylessNAS version: {}".format(version))
shortcuts = [[0], [0, 1, 1, 1], [0, 1, 1, 1], [0, 1, 1, 1, 0, 1, 1, 1], [0, 1, 1, 1, 0]]
net = ProxylessNAS(
channels=channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
residuals=residuals,
shortcuts=shortcuts,
kernel_sizes=kernel_sizes,
expansions=expansions,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def proxylessnas_cpu(**kwargs):
"""
ProxylessNAS (CPU) model from 'ProxylessNAS: Direct Neural Architecture Search on Target Task and Hardware,'
https://arxiv.org/abs/1812.00332.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_proxylessnas(version="cpu", model_name="proxylessnas_cpu", **kwargs)
def proxylessnas_gpu(**kwargs):
"""
ProxylessNAS (GPU) model from 'ProxylessNAS: Direct Neural Architecture Search on Target Task and Hardware,'
https://arxiv.org/abs/1812.00332.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_proxylessnas(version="gpu", model_name="proxylessnas_gpu", **kwargs)
def proxylessnas_mobile(**kwargs):
"""
ProxylessNAS (Mobile) model from 'ProxylessNAS: Direct Neural Architecture Search on Target Task and Hardware,'
https://arxiv.org/abs/1812.00332.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_proxylessnas(version="mobile", model_name="proxylessnas_mobile", **kwargs)
def proxylessnas_mobile14(**kwargs):
"""
ProxylessNAS (Mobile-14) model from 'ProxylessNAS: Direct Neural Architecture Search on Target Task and Hardware,'
https://arxiv.org/abs/1812.00332.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_proxylessnas(version="mobile14", model_name="proxylessnas_mobile14", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
proxylessnas_cpu,
proxylessnas_gpu,
proxylessnas_mobile,
proxylessnas_mobile14,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != proxylessnas_cpu or weight_count == 4361648)
assert (model != proxylessnas_gpu or weight_count == 7119848)
assert (model != proxylessnas_mobile or weight_count == 4080512)
assert (model != proxylessnas_mobile14 or weight_count == 6857568)
x = torch.randn(14, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (14, 1000))
if __name__ == "__main__":
_test()
| 14,555 | 33.492891 | 118 | py |
null | qimera-main/pytorchcv/models/proxylessnas_cub.py | """
ProxylessNAS for CUB-200-2011, implemented in Gluon.
Original paper: 'ProxylessNAS: Direct Neural Architecture Search on Target Task and Hardware,'
https://arxiv.org/abs/1812.00332.
"""
__all__ = ['proxylessnas_cpu_cub', 'proxylessnas_gpu_cub', 'proxylessnas_mobile_cub', 'proxylessnas_mobile14_cub']
from .proxylessnas import get_proxylessnas
def proxylessnas_cpu_cub(num_classes=200, **kwargs):
"""
ProxylessNAS (CPU) model for CUB-200-2011 from 'ProxylessNAS: Direct Neural Architecture Search on Target Task and
Hardware,' https://arxiv.org/abs/1812.00332.
Parameters:
----------
num_classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_proxylessnas(num_classes=num_classes, version="cpu", model_name="proxylessnas_cpu_cub", **kwargs)
def proxylessnas_gpu_cub(num_classes=200, **kwargs):
"""
ProxylessNAS (GPU) model for CUB-200-2011 from 'ProxylessNAS: Direct Neural Architecture Search on Target Task and
Hardware,' https://arxiv.org/abs/1812.00332.
Parameters:
----------
num_classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_proxylessnas(num_classes=num_classes, version="gpu", model_name="proxylessnas_gpu_cub", **kwargs)
def proxylessnas_mobile_cub(num_classes=200, **kwargs):
"""
ProxylessNAS (Mobile) model for CUB-200-2011 from 'ProxylessNAS: Direct Neural Architecture Search on Target Task
and Hardware,' https://arxiv.org/abs/1812.00332.
Parameters:
----------
num_classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_proxylessnas(num_classes=num_classes, version="mobile", model_name="proxylessnas_mobile_cub", **kwargs)
def proxylessnas_mobile14_cub(num_classes=200, **kwargs):
"""
ProxylessNAS (Mobile-14) model for CUB-200-2011 from 'ProxylessNAS: Direct Neural Architecture Search on Target Task
and Hardware,' https://arxiv.org/abs/1812.00332.
Parameters:
----------
num_classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_proxylessnas(num_classes=num_classes, version="mobile14", model_name="proxylessnas_mobile14_cub",
**kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
proxylessnas_cpu_cub,
proxylessnas_gpu_cub,
proxylessnas_mobile_cub,
proxylessnas_mobile14_cub,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != proxylessnas_cpu_cub or weight_count == 3215248)
assert (model != proxylessnas_gpu_cub or weight_count == 5736648)
assert (model != proxylessnas_mobile_cub or weight_count == 3055712)
assert (model != proxylessnas_mobile14_cub or weight_count == 5423168)
x = torch.randn(14, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (14, 200))
if __name__ == "__main__":
_test()
| 4,155 | 32.788618 | 120 | py |
null | qimera-main/pytorchcv/models/pspnet.py | """
PSPNet for image segmentation, implemented in PyTorch.
Original paper: 'Pyramid Scene Parsing Network,' https://arxiv.org/abs/1612.01105.
"""
__all__ = ['PSPNet', 'pspnet_resnetd50b_voc', 'pspnet_resnetd101b_voc', 'pspnet_resnetd50b_coco',
'pspnet_resnetd101b_coco', 'pspnet_resnetd50b_ade20k', 'pspnet_resnetd101b_ade20k',
'pspnet_resnetd50b_cityscapes', 'pspnet_resnetd101b_cityscapes']
import os
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from .common import conv1x1, conv1x1_block, conv3x3_block, Concurrent, Identity
from .resnetd import resnetd50b, resnetd101b
class PSPFinalBlock(nn.Module):
"""
PSPNet final block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bottleneck_factor : int, default 4
Bottleneck factor.
"""
def __init__(self,
in_channels,
out_channels,
bottleneck_factor=4):
super(PSPFinalBlock, self).__init__()
assert (in_channels % bottleneck_factor == 0)
mid_channels = in_channels // bottleneck_factor
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=mid_channels)
self.dropout = nn.Dropout(p=0.1, inplace=False)
self.conv2 = conv1x1(
in_channels=mid_channels,
out_channels=out_channels,
bias=True)
def forward(self, x, out_size):
x = self.conv1(x)
x = self.dropout(x)
x = self.conv2(x)
x = F.interpolate(x, size=out_size, mode="bilinear", align_corners=True)
return x
class PyramidPoolingBranch(nn.Module):
"""
Pyramid Pooling branch.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
pool_out_size : int
Target output size of the image.
upscale_out_size : tuple of 2 int
Spatial size of output image for the bilinear upsampling operation.
"""
def __init__(self,
in_channels,
out_channels,
pool_out_size,
upscale_out_size):
super(PyramidPoolingBranch, self).__init__()
self.upscale_out_size = upscale_out_size
self.pool = nn.AdaptiveAvgPool2d(pool_out_size)
self.conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels)
def forward(self, x):
in_size = self.upscale_out_size if self.upscale_out_size is not None else x.shape[2:]
x = self.pool(x)
x = self.conv(x)
x = F.interpolate(x, size=in_size, mode="bilinear", align_corners=True)
return x
class PyramidPooling(nn.Module):
"""
Pyramid Pooling module.
Parameters:
----------
in_channels : int
Number of input channels.
upscale_out_size : tuple of 2 int
Spatial size of the input tensor for the bilinear upsampling operation.
"""
def __init__(self,
in_channels,
upscale_out_size):
super(PyramidPooling, self).__init__()
pool_out_sizes = [1, 2, 3, 6]
assert (len(pool_out_sizes) == 4)
assert (in_channels % 4 == 0)
mid_channels = in_channels // 4
self.branches = Concurrent()
self.branches.add_module("branch1", Identity())
for i, pool_out_size in enumerate(pool_out_sizes):
self.branches.add_module("branch{}".format(i + 2), PyramidPoolingBranch(
in_channels=in_channels,
out_channels=mid_channels,
pool_out_size=pool_out_size,
upscale_out_size=upscale_out_size))
def forward(self, x):
x = self.branches(x)
return x
class PSPNet(nn.Module):
"""
PSPNet model from 'Pyramid Scene Parsing Network,' https://arxiv.org/abs/1612.01105.
Parameters:
----------
backbone : nn.Sequential
Feature extractor.
backbone_out_channels : int, default 2048
Number of output channels form feature extractor.
aux : bool, default False
Whether to output an auxiliary result.
fixed_size : bool, default True
Whether to expect fixed spatial size of input image.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (480, 480)
Spatial size of the expected input image.
num_classes : int, default 21
Number of segmentation classes.
"""
def __init__(self,
backbone,
backbone_out_channels=2048,
aux=False,
fixed_size=True,
in_channels=3,
in_size=(480, 480),
num_classes=21):
super(PSPNet, self).__init__()
assert (in_channels > 0)
assert ((in_size[0] % 8 == 0) and (in_size[1] % 8 == 0))
self.in_size = in_size
self.num_classes = num_classes
self.aux = aux
self.fixed_size = fixed_size
self.backbone = backbone
pool_out_size = (self.in_size[0] // 8, self.in_size[1] // 8) if fixed_size else None
self.pool = PyramidPooling(
in_channels=backbone_out_channels,
upscale_out_size=pool_out_size)
pool_out_channels = 2 * backbone_out_channels
self.final_block = PSPFinalBlock(
in_channels=pool_out_channels,
out_channels=num_classes,
bottleneck_factor=8)
if self.aux:
aux_out_channels = backbone_out_channels // 2
self.aux_block = PSPFinalBlock(
in_channels=aux_out_channels,
out_channels=num_classes,
bottleneck_factor=4)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
in_size = self.in_size if self.fixed_size else x.shape[2:]
x, y = self.backbone(x)
x = self.pool(x)
x = self.final_block(x, in_size)
if self.aux:
y = self.aux_block(y, in_size)
return x, y
else:
return x
def get_pspnet(backbone,
num_classes,
aux=False,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create PSPNet model with specific parameters.
Parameters:
----------
backbone : nn.Sequential
Feature extractor.
num_classes : int
Number of segmentation classes.
aux : bool, default False
Whether to output an auxiliary result.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
net = PSPNet(
backbone=backbone,
num_classes=num_classes,
aux=aux,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def pspnet_resnetd50b_voc(pretrained_backbone=False, num_classes=21, aux=True, **kwargs):
"""
PSPNet model on the base of ResNet(D)-50b for Pascal VOC from 'Pyramid Scene Parsing Network,'
https://arxiv.org/abs/1612.01105.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 21
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_pspnet(backbone=backbone, num_classes=num_classes, aux=aux, model_name="pspnet_resnetd50b_voc", **kwargs)
def pspnet_resnetd101b_voc(pretrained_backbone=False, num_classes=21, aux=True, **kwargs):
"""
PSPNet model on the base of ResNet(D)-101b for Pascal VOC from 'Pyramid Scene Parsing Network,'
https://arxiv.org/abs/1612.01105.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 21
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_pspnet(backbone=backbone, num_classes=num_classes, aux=aux, model_name="pspnet_resnetd101b_voc",
**kwargs)
def pspnet_resnetd50b_coco(pretrained_backbone=False, num_classes=21, aux=True, **kwargs):
"""
PSPNet model on the base of ResNet(D)-50b for COCO from 'Pyramid Scene Parsing Network,'
https://arxiv.org/abs/1612.01105.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 21
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_pspnet(backbone=backbone, num_classes=num_classes, aux=aux, model_name="pspnet_resnetd50b_coco",
**kwargs)
def pspnet_resnetd101b_coco(pretrained_backbone=False, num_classes=21, aux=True, **kwargs):
"""
PSPNet model on the base of ResNet(D)-101b for COCO from 'Pyramid Scene Parsing Network,'
https://arxiv.org/abs/1612.01105.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 21
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_pspnet(backbone=backbone, num_classes=num_classes, aux=aux, model_name="pspnet_resnetd101b_coco",
**kwargs)
def pspnet_resnetd50b_ade20k(pretrained_backbone=False, num_classes=150, aux=True, **kwargs):
"""
PSPNet model on the base of ResNet(D)-50b for ADE20K from 'Pyramid Scene Parsing Network,'
https://arxiv.org/abs/1612.01105.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 150
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_pspnet(backbone=backbone, num_classes=num_classes, aux=aux, model_name="pspnet_resnetd50b_ade20k",
**kwargs)
def pspnet_resnetd101b_ade20k(pretrained_backbone=False, num_classes=150, aux=True, **kwargs):
"""
PSPNet model on the base of ResNet(D)-101b for ADE20K from 'Pyramid Scene Parsing Network,'
https://arxiv.org/abs/1612.01105.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 150
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_pspnet(backbone=backbone, num_classes=num_classes, aux=aux, model_name="pspnet_resnetd101b_ade20k",
**kwargs)
def pspnet_resnetd50b_cityscapes(pretrained_backbone=False, num_classes=19, aux=True, **kwargs):
"""
PSPNet model on the base of ResNet(D)-50b for Cityscapes from 'Pyramid Scene Parsing Network,'
https://arxiv.org/abs/1612.01105.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 19
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_pspnet(backbone=backbone, num_classes=num_classes, aux=aux, model_name="pspnet_resnetd50b_cityscapes",
**kwargs)
def pspnet_resnetd101b_cityscapes(pretrained_backbone=False, num_classes=19, aux=True, **kwargs):
"""
PSPNet model on the base of ResNet(D)-101b for Cityscapes from 'Pyramid Scene Parsing Network,'
https://arxiv.org/abs/1612.01105.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
num_classes : int, default 19
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[-1]
return get_pspnet(backbone=backbone, num_classes=num_classes, aux=aux, model_name="pspnet_resnetd101b_cityscapes",
**kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
in_size = (480, 480)
aux = False
pretrained = False
models = [
(pspnet_resnetd50b_voc, 21),
(pspnet_resnetd101b_voc, 21),
(pspnet_resnetd50b_coco, 21),
(pspnet_resnetd101b_coco, 21),
(pspnet_resnetd50b_ade20k, 150),
(pspnet_resnetd101b_ade20k, 150),
(pspnet_resnetd50b_cityscapes, 19),
(pspnet_resnetd101b_cityscapes, 19),
]
for model, num_classes in models:
net = model(pretrained=pretrained, in_size=in_size, aux=aux)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
if aux:
assert (model != pspnet_resnetd50b_voc or weight_count == 49081578)
assert (model != pspnet_resnetd101b_voc or weight_count == 68073706)
assert (model != pspnet_resnetd50b_coco or weight_count == 49081578)
assert (model != pspnet_resnetd101b_coco or weight_count == 68073706)
assert (model != pspnet_resnetd50b_ade20k or weight_count == 49180908)
assert (model != pspnet_resnetd101b_ade20k or weight_count == 68173036)
assert (model != pspnet_resnetd50b_cityscapes or weight_count == 49080038)
assert (model != pspnet_resnetd101b_cityscapes or weight_count == 68072166)
else:
assert (model != pspnet_resnetd50b_voc or weight_count == 46716373)
assert (model != pspnet_resnetd101b_voc or weight_count == 65708501)
assert (model != pspnet_resnetd50b_coco or weight_count == 46716373)
assert (model != pspnet_resnetd101b_coco or weight_count == 65708501)
assert (model != pspnet_resnetd50b_ade20k or weight_count == 46782550)
assert (model != pspnet_resnetd101b_ade20k or weight_count == 65774678)
assert (model != pspnet_resnetd50b_cityscapes or weight_count == 46715347)
assert (model != pspnet_resnetd101b_cityscapes or weight_count == 65707475)
x = torch.randn(1, 3, in_size[0], in_size[1])
ys = net(x)
y = ys[0] if aux else ys
y.sum().backward()
assert ((y.size(0) == x.size(0)) and (y.size(1) == num_classes) and (y.size(2) == x.size(2)) and
(y.size(3) == x.size(3)))
if __name__ == "__main__":
_test()
| 18,442 | 35.886 | 120 | py |
null | qimera-main/pytorchcv/models/pyramidnet.py | """
PyramidNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915.
"""
__all__ = ['PyramidNet', 'pyramidnet101_a360', 'PyrUnit']
import os
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
from .common import pre_conv1x1_block, pre_conv3x3_block
from .preresnet import PreResActivation
class PyrBlock(nn.Module):
"""
Simple PyramidNet block for residual path in PyramidNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
"""
def __init__(self,
in_channels,
out_channels,
stride):
super(PyrBlock, self).__init__()
self.conv1 = pre_conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
activate=False)
self.conv2 = pre_conv3x3_block(
in_channels=out_channels,
out_channels=out_channels)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class PyrBottleneck(nn.Module):
"""
PyramidNet bottleneck block for residual path in PyramidNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
"""
def __init__(self,
in_channels,
out_channels,
stride):
super(PyrBottleneck, self).__init__()
mid_channels = out_channels // 4
self.conv1 = pre_conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
activate=False)
self.conv2 = pre_conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride)
self.conv3 = pre_conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class PyrUnit(nn.Module):
"""
PyramidNet unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
"""
def __init__(self,
in_channels,
out_channels,
stride,
bottleneck):
super(PyrUnit, self).__init__()
assert (out_channels >= in_channels)
self.resize_identity = (stride != 1)
self.identity_pad_width = (0, 0, 0, 0, 0, out_channels - in_channels)
if bottleneck:
self.body = PyrBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
else:
self.body = PyrBlock(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
self.bn = nn.BatchNorm2d(num_features=out_channels)
if self.resize_identity:
self.identity_pool = nn.AvgPool2d(
kernel_size=2,
stride=stride,
ceil_mode=True)
def forward(self, x):
identity = x
x = self.body(x)
x = self.bn(x)
if self.resize_identity:
identity = self.identity_pool(identity)
identity = F.pad(identity, pad=self.identity_pad_width)
x = x + identity
return x
class PyrInitBlock(nn.Module):
"""
PyramidNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(PyrInitBlock, self).__init__()
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=7,
stride=2,
padding=3,
bias=False)
self.bn = nn.BatchNorm2d(num_features=out_channels)
self.activ = nn.ReLU(inplace=True)
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=1)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
x = self.activ(x)
x = self.pool(x)
return x
class PyramidNet(nn.Module):
"""
PyramidNet model from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(PyramidNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", PyrInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 1 if (i == 0) or (j != 0) else 2
stage.add_module("unit{}".format(j + 1), PyrUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('post_activ', PreResActivation(in_channels=in_channels))
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_pyramidnet(blocks,
alpha,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create PyramidNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
alpha : int
PyramidNet's alpha value.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 10:
layers = [1, 1, 1, 1]
elif blocks == 12:
layers = [2, 1, 1, 1]
elif blocks == 14:
layers = [2, 2, 1, 1]
elif blocks == 16:
layers = [2, 2, 2, 1]
elif blocks == 18:
layers = [2, 2, 2, 2]
elif blocks == 34:
layers = [3, 4, 6, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
elif blocks == 200:
layers = [3, 24, 36, 3]
else:
raise ValueError("Unsupported ResNet with number of blocks: {}".format(blocks))
init_block_channels = 64
growth_add = float(alpha) / float(sum(layers))
from functools import reduce
channels = reduce(
lambda xi, yi: xi + [[(i + 1) * growth_add + xi[-1][-1] for i in list(range(yi))]],
layers,
[[init_block_channels]])[1:]
channels = [[int(round(cij)) for cij in ci] for ci in channels]
if blocks < 50:
bottleneck = False
else:
bottleneck = True
channels = [[cij * 4 for cij in ci] for ci in channels]
net = PyramidNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def pyramidnet101_a360(**kwargs):
"""
PyramidNet-101 model from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_pyramidnet(blocks=101, alpha=360, model_name="pyramidnet101_a360", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
pyramidnet101_a360,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != pyramidnet101_a360 or weight_count == 42455070)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 11,038 | 28.126649 | 115 | py |
null | qimera-main/pytorchcv/models/pyramidnet_cifar.py | """
PyramidNet for CIFAR/SVHN, implemented in PyTorch.
Original paper: 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915.
"""
__all__ = ['CIFARPyramidNet', 'pyramidnet110_a48_cifar10', 'pyramidnet110_a48_cifar100', 'pyramidnet110_a48_svhn',
'pyramidnet110_a84_cifar10', 'pyramidnet110_a84_cifar100', 'pyramidnet110_a84_svhn',
'pyramidnet110_a270_cifar10', 'pyramidnet110_a270_cifar100', 'pyramidnet110_a270_svhn',
'pyramidnet164_a270_bn_cifar10', 'pyramidnet164_a270_bn_cifar100', 'pyramidnet164_a270_bn_svhn',
'pyramidnet200_a240_bn_cifar10', 'pyramidnet200_a240_bn_cifar100', 'pyramidnet200_a240_bn_svhn',
'pyramidnet236_a220_bn_cifar10', 'pyramidnet236_a220_bn_cifar100', 'pyramidnet236_a220_bn_svhn',
'pyramidnet272_a200_bn_cifar10', 'pyramidnet272_a200_bn_cifar100', 'pyramidnet272_a200_bn_svhn']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv3x3_block
from .preresnet import PreResActivation
from .pyramidnet import PyrUnit
class CIFARPyramidNet(nn.Module):
"""
PyramidNet model for CIFAR from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
num_classes : int, default 10
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
in_channels=3,
in_size=(32, 32),
num_classes=10):
super(CIFARPyramidNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels,
activation=None))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 1 if (i == 0) or (j != 0) else 2
stage.add_module("unit{}".format(j + 1), PyrUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('post_activ', PreResActivation(in_channels=in_channels))
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=8,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_pyramidnet_cifar(num_classes,
blocks,
alpha,
bottleneck,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create PyramidNet for CIFAR model with specific parameters.
Parameters:
----------
num_classes : int
Number of classification classes.
blocks : int
Number of blocks.
alpha : int
PyramidNet's alpha value.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
assert (num_classes in [10, 100])
if bottleneck:
assert ((blocks - 2) % 9 == 0)
layers = [(blocks - 2) // 9] * 3
else:
assert ((blocks - 2) % 6 == 0)
layers = [(blocks - 2) // 6] * 3
init_block_channels = 16
growth_add = float(alpha) / float(sum(layers))
from functools import reduce
channels = reduce(
lambda xi, yi: xi + [[(i + 1) * growth_add + xi[-1][-1] for i in list(range(yi))]],
layers,
[[init_block_channels]])[1:]
channels = [[int(round(cij)) for cij in ci] for ci in channels]
if bottleneck:
channels = [[cij * 4 for cij in ci] for ci in channels]
net = CIFARPyramidNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
num_classes=num_classes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def pyramidnet110_a48_cifar10(num_classes=10, **kwargs):
"""
PyramidNet-110 (a=48) model for CIFAR-10 from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_pyramidnet_cifar(
num_classes=num_classes,
blocks=110,
alpha=48,
bottleneck=False,
model_name="pyramidnet110_a48_cifar10",
**kwargs)
def pyramidnet110_a48_cifar100(num_classes=100, **kwargs):
"""
PyramidNet-110 (a=48) model for CIFAR-100 from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_pyramidnet_cifar(
num_classes=num_classes,
blocks=110,
alpha=48,
bottleneck=False,
model_name="pyramidnet110_a48_cifar100",
**kwargs)
def pyramidnet110_a48_svhn(num_classes=10, **kwargs):
"""
PyramidNet-110 (a=48) model for SVHN from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_pyramidnet_cifar(
num_classes=num_classes,
blocks=110,
alpha=48,
bottleneck=False,
model_name="pyramidnet110_a48_svhn",
**kwargs)
def pyramidnet110_a84_cifar10(num_classes=10, **kwargs):
"""
PyramidNet-110 (a=84) model for CIFAR-10 from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_pyramidnet_cifar(
num_classes=num_classes,
blocks=110,
alpha=84,
bottleneck=False,
model_name="pyramidnet110_a84_cifar10",
**kwargs)
def pyramidnet110_a84_cifar100(num_classes=100, **kwargs):
"""
PyramidNet-110 (a=84) model for CIFAR-100 from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_pyramidnet_cifar(
num_classes=num_classes,
blocks=110,
alpha=84,
bottleneck=False,
model_name="pyramidnet110_a84_cifar100",
**kwargs)
def pyramidnet110_a84_svhn(num_classes=10, **kwargs):
"""
PyramidNet-110 (a=84) model for SVHN from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_pyramidnet_cifar(
num_classes=num_classes,
blocks=110,
alpha=84,
bottleneck=False,
model_name="pyramidnet110_a84_svhn",
**kwargs)
def pyramidnet110_a270_cifar10(num_classes=10, **kwargs):
"""
PyramidNet-110 (a=270) model for CIFAR-10 from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_pyramidnet_cifar(
num_classes=num_classes,
blocks=110,
alpha=270,
bottleneck=False,
model_name="pyramidnet110_a270_cifar10",
**kwargs)
def pyramidnet110_a270_cifar100(num_classes=100, **kwargs):
"""
PyramidNet-110 (a=270) model for CIFAR-100 from 'Deep Pyramidal Residual Networks,'
https://arxiv.org/abs/1610.02915.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_pyramidnet_cifar(
num_classes=num_classes,
blocks=110,
alpha=270,
bottleneck=False,
model_name="pyramidnet110_a270_cifar100",
**kwargs)
def pyramidnet110_a270_svhn(num_classes=10, **kwargs):
"""
PyramidNet-110 (a=270) model for SVHN from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_pyramidnet_cifar(
num_classes=num_classes,
blocks=110,
alpha=270,
bottleneck=False,
model_name="pyramidnet110_a270_svhn",
**kwargs)
def pyramidnet164_a270_bn_cifar10(num_classes=10, **kwargs):
"""
PyramidNet-164 (a=270, bn) model for CIFAR-10 from 'Deep Pyramidal Residual Networks,'
https://arxiv.org/abs/1610.02915.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_pyramidnet_cifar(
num_classes=num_classes,
blocks=164,
alpha=270,
bottleneck=True,
model_name="pyramidnet164_a270_bn_cifar10",
**kwargs)
def pyramidnet164_a270_bn_cifar100(num_classes=100, **kwargs):
"""
PyramidNet-164 (a=270, bn) model for CIFAR-100 from 'Deep Pyramidal Residual Networks,'
https://arxiv.org/abs/1610.02915.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_pyramidnet_cifar(
num_classes=num_classes,
blocks=164,
alpha=270,
bottleneck=True,
model_name="pyramidnet164_a270_bn_cifar100",
**kwargs)
def pyramidnet164_a270_bn_svhn(num_classes=10, **kwargs):
"""
PyramidNet-164 (a=270, bn) model for SVHN from 'Deep Pyramidal Residual Networks,'
https://arxiv.org/abs/1610.02915.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_pyramidnet_cifar(
num_classes=num_classes,
blocks=164,
alpha=270,
bottleneck=True,
model_name="pyramidnet164_a270_bn_svhn",
**kwargs)
def pyramidnet200_a240_bn_cifar10(num_classes=10, **kwargs):
"""
PyramidNet-200 (a=240, bn) model for CIFAR-10 from 'Deep Pyramidal Residual Networks,'
https://arxiv.org/abs/1610.02915.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_pyramidnet_cifar(
num_classes=num_classes,
blocks=200,
alpha=240,
bottleneck=True,
model_name="pyramidnet200_a240_bn_cifar10",
**kwargs)
def pyramidnet200_a240_bn_cifar100(num_classes=100, **kwargs):
"""
PyramidNet-200 (a=240, bn) model for CIFAR-100 from 'Deep Pyramidal Residual Networks,'
https://arxiv.org/abs/1610.02915.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_pyramidnet_cifar(
num_classes=num_classes,
blocks=200,
alpha=240,
bottleneck=True,
model_name="pyramidnet200_a240_bn_cifar100",
**kwargs)
def pyramidnet200_a240_bn_svhn(num_classes=10, **kwargs):
"""
PyramidNet-200 (a=240, bn) model for SVHN from 'Deep Pyramidal Residual Networks,'
https://arxiv.org/abs/1610.02915.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_pyramidnet_cifar(
num_classes=num_classes,
blocks=200,
alpha=240,
bottleneck=True,
model_name="pyramidnet200_a240_bn_svhn",
**kwargs)
def pyramidnet236_a220_bn_cifar10(num_classes=10, **kwargs):
"""
PyramidNet-236 (a=220, bn) model for CIFAR-10 from 'Deep Pyramidal Residual Networks,'
https://arxiv.org/abs/1610.02915.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_pyramidnet_cifar(
num_classes=num_classes,
blocks=236,
alpha=220,
bottleneck=True,
model_name="pyramidnet236_a220_bn_cifar10",
**kwargs)
def pyramidnet236_a220_bn_cifar100(num_classes=100, **kwargs):
"""
PyramidNet-236 (a=220, bn) model for CIFAR-100 from 'Deep Pyramidal Residual Networks,'
https://arxiv.org/abs/1610.02915.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_pyramidnet_cifar(
num_classes=num_classes,
blocks=236,
alpha=220,
bottleneck=True,
model_name="pyramidnet236_a220_bn_cifar100",
**kwargs)
def pyramidnet236_a220_bn_svhn(num_classes=10, **kwargs):
"""
PyramidNet-236 (a=220, bn) model for SVHN from 'Deep Pyramidal Residual Networks,'
https://arxiv.org/abs/1610.02915.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_pyramidnet_cifar(
num_classes=num_classes,
blocks=236,
alpha=220,
bottleneck=True,
model_name="pyramidnet236_a220_bn_svhn",
**kwargs)
def pyramidnet272_a200_bn_cifar10(num_classes=10, **kwargs):
"""
PyramidNet-272 (a=200, bn) model for CIFAR-10 from 'Deep Pyramidal Residual Networks,'
https://arxiv.org/abs/1610.02915.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_pyramidnet_cifar(
num_classes=num_classes,
blocks=272,
alpha=200,
bottleneck=True,
model_name="pyramidnet272_a200_bn_cifar10",
**kwargs)
def pyramidnet272_a200_bn_cifar100(num_classes=100, **kwargs):
"""
PyramidNet-272 (a=200, bn) model for CIFAR-100 from 'Deep Pyramidal Residual Networks,'
https://arxiv.org/abs/1610.02915.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_pyramidnet_cifar(
num_classes=num_classes,
blocks=272,
alpha=200,
bottleneck=True,
model_name="pyramidnet272_a200_bn_cifar100",
**kwargs)
def pyramidnet272_a200_bn_svhn(num_classes=10, **kwargs):
"""
PyramidNet-272 (a=200, bn) model for SVHN from 'Deep Pyramidal Residual Networks,'
https://arxiv.org/abs/1610.02915.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_pyramidnet_cifar(
num_classes=num_classes,
blocks=272,
alpha=200,
bottleneck=True,
model_name="pyramidnet272_a200_bn_svhn",
**kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
(pyramidnet110_a48_cifar10, 10),
(pyramidnet110_a48_cifar100, 100),
(pyramidnet110_a48_svhn, 10),
(pyramidnet110_a84_cifar10, 10),
(pyramidnet110_a84_cifar100, 100),
(pyramidnet110_a84_svhn, 10),
(pyramidnet110_a270_cifar10, 10),
(pyramidnet110_a270_cifar100, 100),
(pyramidnet110_a270_svhn, 10),
(pyramidnet164_a270_bn_cifar10, 10),
(pyramidnet164_a270_bn_cifar100, 100),
(pyramidnet164_a270_bn_svhn, 10),
(pyramidnet200_a240_bn_cifar10, 10),
(pyramidnet200_a240_bn_cifar100, 100),
(pyramidnet200_a240_bn_svhn, 10),
(pyramidnet236_a220_bn_cifar10, 10),
(pyramidnet236_a220_bn_cifar100, 100),
(pyramidnet236_a220_bn_svhn, 10),
(pyramidnet272_a200_bn_cifar10, 10),
(pyramidnet272_a200_bn_cifar100, 100),
(pyramidnet272_a200_bn_svhn, 10),
]
for model, num_classes in models:
net = model(pretrained=pretrained, num_classes=num_classes)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != pyramidnet110_a48_cifar10 or weight_count == 1772706)
assert (model != pyramidnet110_a48_cifar100 or weight_count == 1778556)
assert (model != pyramidnet110_a48_svhn or weight_count == 1772706)
assert (model != pyramidnet110_a84_cifar10 or weight_count == 3904446)
assert (model != pyramidnet110_a84_cifar100 or weight_count == 3913536)
assert (model != pyramidnet110_a84_svhn or weight_count == 3904446)
assert (model != pyramidnet110_a270_cifar10 or weight_count == 28485477)
assert (model != pyramidnet110_a270_cifar100 or weight_count == 28511307)
assert (model != pyramidnet110_a270_svhn or weight_count == 28485477)
assert (model != pyramidnet164_a270_bn_cifar10 or weight_count == 27216021)
assert (model != pyramidnet164_a270_bn_cifar100 or weight_count == 27319071)
assert (model != pyramidnet164_a270_bn_svhn or weight_count == 27216021)
assert (model != pyramidnet200_a240_bn_cifar10 or weight_count == 26752702)
assert (model != pyramidnet200_a240_bn_cifar100 or weight_count == 26844952)
assert (model != pyramidnet200_a240_bn_svhn or weight_count == 26752702)
assert (model != pyramidnet236_a220_bn_cifar10 or weight_count == 26969046)
assert (model != pyramidnet236_a220_bn_cifar100 or weight_count == 27054096)
assert (model != pyramidnet236_a220_bn_svhn or weight_count == 26969046)
assert (model != pyramidnet272_a200_bn_cifar10 or weight_count == 26210842)
assert (model != pyramidnet272_a200_bn_cifar100 or weight_count == 26288692)
assert (model != pyramidnet272_a200_bn_svhn or weight_count == 26210842)
x = torch.randn(1, 3, 32, 32)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, num_classes))
if __name__ == "__main__":
_test()
| 23,823 | 32.413745 | 120 | py |
null | qimera-main/pytorchcv/models/resattnet.py | """
ResAttNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904.
"""
__all__ = ['ResAttNet', 'resattnet56', 'resattnet92', 'resattnet128', 'resattnet164', 'resattnet200', 'resattnet236',
'resattnet452']
import os
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from .common import conv1x1, conv7x7_block, pre_conv1x1_block, pre_conv3x3_block, Hourglass
class PreResBottleneck(nn.Module):
"""
PreResNet bottleneck block for residual path in PreResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
"""
def __init__(self,
in_channels,
out_channels,
stride):
super(PreResBottleneck, self).__init__()
mid_channels = out_channels // 4
self.conv1 = pre_conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
return_preact=True)
self.conv2 = pre_conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride)
self.conv3 = pre_conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels)
def forward(self, x):
x, x_pre_activ = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x, x_pre_activ
class ResBlock(nn.Module):
"""
Residual block with pre-activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
"""
def __init__(self,
in_channels,
out_channels,
stride=1):
super(ResBlock, self).__init__()
self.resize_identity = (in_channels != out_channels) or (stride != 1)
self.body = PreResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
if self.resize_identity:
self.identity_conv = conv1x1(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
def forward(self, x):
identity = x
x, x_pre_activ = self.body(x)
if self.resize_identity:
identity = self.identity_conv(x_pre_activ)
x = x + identity
return x
class InterpolationBlock(nn.Module):
"""
Interpolation block.
Parameters:
----------
scale_factor : float
Multiplier for spatial size.
"""
def __init__(self,
scale_factor):
super(InterpolationBlock, self).__init__()
self.scale_factor = scale_factor
def forward(self, x):
return F.interpolate(
input=x,
scale_factor=self.scale_factor,
mode='bilinear',
align_corners=True)
class DoubleSkipBlock(nn.Module):
"""
Double skip connection block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(DoubleSkipBlock, self).__init__()
self.skip1 = ResBlock(
in_channels=in_channels,
out_channels=out_channels)
def forward(self, x):
x = x + self.skip1(x)
return x
class ResBlockSequence(nn.Module):
"""
Sequence of residual blocks with pre-activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
length : int
Length of sequence.
"""
def __init__(self,
in_channels,
out_channels,
length):
super(ResBlockSequence, self).__init__()
self.blocks = nn.Sequential()
for i in range(length):
self.blocks.add_module('block{}'.format(i + 1), ResBlock(
in_channels=in_channels,
out_channels=out_channels))
def forward(self, x):
x = self.blocks(x)
return x
class DownAttBlock(nn.Module):
"""
Down sub-block for hourglass of attention block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
length : int
Length of residual blocks list.
"""
def __init__(self,
in_channels,
out_channels,
length):
super(DownAttBlock, self).__init__()
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=1)
self.res_blocks = ResBlockSequence(
in_channels=in_channels,
out_channels=out_channels,
length=length)
def forward(self, x):
x = self.pool(x)
x = self.res_blocks(x)
return x
class UpAttBlock(nn.Module):
"""
Up sub-block for hourglass of attention block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
length : int
Length of residual blocks list.
scale_factor : float
Multiplier for spatial size.
"""
def __init__(self,
in_channels,
out_channels,
length,
scale_factor):
super(UpAttBlock, self).__init__()
self.res_blocks = ResBlockSequence(
in_channels=in_channels,
out_channels=out_channels,
length=length)
self.upsample = InterpolationBlock(scale_factor)
def forward(self, x):
x = self.res_blocks(x)
x = self.upsample(x)
return x
class MiddleAttBlock(nn.Module):
"""
Middle sub-block for attention block.
Parameters:
----------
channels : int
Number of input/output channels.
"""
def __init__(self,
channels):
super(MiddleAttBlock, self).__init__()
self.conv1 = pre_conv1x1_block(
in_channels=channels,
out_channels=channels)
self.conv2 = pre_conv1x1_block(
in_channels=channels,
out_channels=channels)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.sigmoid(x)
return x
class AttBlock(nn.Module):
"""
Attention block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
hourglass_depth : int
Depth of hourglass block.
att_scales : list of int
Attention block specific scales.
"""
def __init__(self,
in_channels,
out_channels,
hourglass_depth,
att_scales):
super(AttBlock, self).__init__()
assert (len(att_scales) == 3)
scale_factor = 2
scale_p, scale_t, scale_r = att_scales
self.init_blocks = ResBlockSequence(
in_channels=in_channels,
out_channels=out_channels,
length=scale_p)
down_seq = nn.Sequential()
up_seq = nn.Sequential()
skip_seq = nn.Sequential()
for i in range(hourglass_depth):
down_seq.add_module('down{}'.format(i + 1), DownAttBlock(
in_channels=in_channels,
out_channels=out_channels,
length=scale_r))
up_seq.add_module('up{}'.format(i + 1), UpAttBlock(
in_channels=in_channels,
out_channels=out_channels,
length=scale_r,
scale_factor=scale_factor))
if i == 0:
skip_seq.add_module('skip1', ResBlockSequence(
in_channels=in_channels,
out_channels=out_channels,
length=scale_t))
else:
skip_seq.add_module('skip{}'.format(i + 1), DoubleSkipBlock(
in_channels=in_channels,
out_channels=out_channels))
self.hg = Hourglass(
down_seq=down_seq,
up_seq=up_seq,
skip_seq=skip_seq,
return_first_skip=True)
self.middle_block = MiddleAttBlock(channels=out_channels)
self.final_block = ResBlock(
in_channels=in_channels,
out_channels=out_channels)
def forward(self, x):
x = self.init_blocks(x)
x, y = self.hg(x)
x = self.middle_block(x)
x = (1 + x) * y
x = self.final_block(x)
return x
class ResAttInitBlock(nn.Module):
"""
ResAttNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(ResAttInitBlock, self).__init__()
self.conv = conv7x7_block(
in_channels=in_channels,
out_channels=out_channels,
stride=2)
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=1)
def forward(self, x):
x = self.conv(x)
x = self.pool(x)
return x
class PreActivation(nn.Module):
"""
Pre-activation block without convolution layer. It's used by itself as the final block in PreResNet.
Parameters:
----------
in_channels : int
Number of input channels.
"""
def __init__(self,
in_channels):
super(PreActivation, self).__init__()
self.bn = nn.BatchNorm2d(num_features=in_channels)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
x = self.bn(x)
x = self.activ(x)
return x
class ResAttNet(nn.Module):
"""
ResAttNet model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
attentions : list of list of int
Whether to use a attention unit or residual one.
att_scales : list of int
Attention block specific scales.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
attentions,
att_scales,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(ResAttNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", ResAttInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
hourglass_depth = len(channels) - 1 - i
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 1 if (i == 0) or (j != 0) else 2
if attentions[i][j]:
stage.add_module("unit{}".format(j + 1), AttBlock(
in_channels=in_channels,
out_channels=out_channels,
hourglass_depth=hourglass_depth,
att_scales=att_scales))
else:
stage.add_module("unit{}".format(j + 1), ResBlock(
in_channels=in_channels,
out_channels=out_channels,
stride=stride))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('post_activ', PreActivation(in_channels=in_channels))
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_resattnet(blocks,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create ResAttNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 56:
att_layers = [1, 1, 1]
att_scales = [1, 2, 1]
elif blocks == 92:
att_layers = [1, 2, 3]
att_scales = [1, 2, 1]
elif blocks == 128:
att_layers = [2, 3, 4]
att_scales = [1, 2, 1]
elif blocks == 164:
att_layers = [3, 4, 5]
att_scales = [1, 2, 1]
elif blocks == 200:
att_layers = [4, 5, 6]
att_scales = [1, 2, 1]
elif blocks == 236:
att_layers = [5, 6, 7]
att_scales = [1, 2, 1]
elif blocks == 452:
att_layers = [5, 6, 7]
att_scales = [2, 4, 3]
else:
raise ValueError("Unsupported ResAttNet with number of blocks: {}".format(blocks))
init_block_channels = 64
channels_per_layers = [256, 512, 1024, 2048]
layers = att_layers + [2]
channels = [[ci] * (li + 1) for (ci, li) in zip(channels_per_layers, layers)]
attentions = [[0] + [1] * li for li in att_layers] + [[0] * 3]
net = ResAttNet(
channels=channels,
init_block_channels=init_block_channels,
attentions=attentions,
att_scales=att_scales,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def resattnet56(**kwargs):
"""
ResAttNet-56 model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resattnet(blocks=56, model_name="resattnet56", **kwargs)
def resattnet92(**kwargs):
"""
ResAttNet-92 model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resattnet(blocks=92, model_name="resattnet92", **kwargs)
def resattnet128(**kwargs):
"""
ResAttNet-128 model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resattnet(blocks=128, model_name="resattnet128", **kwargs)
def resattnet164(**kwargs):
"""
ResAttNet-164 model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resattnet(blocks=164, model_name="resattnet164", **kwargs)
def resattnet200(**kwargs):
"""
ResAttNet-200 model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resattnet(blocks=200, model_name="resattnet200", **kwargs)
def resattnet236(**kwargs):
"""
ResAttNet-236 model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resattnet(blocks=236, model_name="resattnet236", **kwargs)
def resattnet452(**kwargs):
"""
ResAttNet-452 model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resattnet(blocks=452, model_name="resattnet452", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
resattnet56,
resattnet92,
resattnet128,
resattnet164,
resattnet200,
resattnet236,
resattnet452,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != resattnet56 or weight_count == 31810728)
assert (model != resattnet92 or weight_count == 52466344)
assert (model != resattnet128 or weight_count == 65294504)
assert (model != resattnet164 or weight_count == 78122664)
assert (model != resattnet200 or weight_count == 90950824)
assert (model != resattnet236 or weight_count == 103778984)
assert (model != resattnet452 or weight_count == 182285224)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 20,035 | 28.464706 | 117 | py |
null | qimera-main/pytorchcv/models/resdropresnet_cifar.py | """
ResDrop-ResNet for CIFAR/SVHN, implemented in PyTorch.
Original paper: 'Deep Networks with Stochastic Depth,' https://arxiv.org/abs/1603.09382.
"""
__all__ = ['CIFARResDropResNet', 'resdropresnet20_cifar10', 'resdropresnet20_cifar100', 'resdropresnet20_svhn']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, conv3x3_block
from .resnet import ResBlock, ResBottleneck
class ResDropResUnit(nn.Module):
"""
ResDrop-ResNet unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
life_prob : float
Residual branch life probability.
"""
def __init__(self,
in_channels,
out_channels,
stride,
bottleneck,
life_prob):
super(ResDropResUnit, self).__init__()
self.life_prob = life_prob
self.resize_identity = (in_channels != out_channels) or (stride != 1)
body_class = ResBottleneck if bottleneck else ResBlock
self.body = body_class(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
activation=None)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
if self.training:
b = torch.bernoulli(torch.full((1,), self.life_prob, dtype=x.dtype, device=x.device))
x = float(b) / self.life_prob * x
x = x + identity
x = self.activ(x)
return x
class CIFARResDropResNet(nn.Module):
"""
ResDrop-ResNet model for CIFAR from 'Deep Networks with Stochastic Depth,' https://arxiv.org/abs/1603.09382.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
life_probs : list of float
Residual branch life probability for each unit.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
num_classes : int, default 10
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
life_probs,
in_channels=3,
in_size=(32, 32),
num_classes=10):
super(CIFARResDropResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
k = 0
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), ResDropResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck,
life_prob=life_probs[k]))
in_channels = out_channels
k += 1
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=8,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_resdropresnet_cifar(classes,
blocks,
bottleneck,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create ResDrop-ResNet model for CIFAR with specific parameters.
Parameters:
----------
classes : int
Number of classification classes.
blocks : int
Number of blocks.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
assert (classes in [10, 100])
if bottleneck:
assert ((blocks - 2) % 9 == 0)
layers = [(blocks - 2) // 9] * 3
else:
assert ((blocks - 2) % 6 == 0)
layers = [(blocks - 2) // 6] * 3
init_block_channels = 16
channels_per_layers = [16, 32, 64]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if bottleneck:
channels = [[cij * 4 for cij in ci] for ci in channels]
total_layers = sum(layers)
final_death_prob = 0.5
life_probs = [1.0 - float(i + 1) / float(total_layers) * final_death_prob for i in range(total_layers)]
net = CIFARResDropResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
life_probs=life_probs,
num_classes=classes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def resdropresnet20_cifar10(classes=10, **kwargs):
"""
ResDrop-ResNet-20 model for CIFAR-10 from 'Deep Networks with Stochastic Depth,' https://arxiv.org/abs/1603.09382.
Parameters:
----------
classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resdropresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name="resdropresnet20_cifar10",
**kwargs)
def resdropresnet20_cifar100(classes=100, **kwargs):
"""
ResDrop-ResNet-20 model for CIFAR-100 from 'Deep Networks with Stochastic Depth,' https://arxiv.org/abs/1603.09382.
Parameters:
----------
classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resdropresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name="resdropresnet20_cifar100",
**kwargs)
def resdropresnet20_svhn(classes=10, **kwargs):
"""
ResDrop-ResNet-20 model for SVHN from 'Deep Networks with Stochastic Depth,' https://arxiv.org/abs/1603.09382.
Parameters:
----------
classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resdropresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name="resdropresnet20_svhn",
**kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
(resdropresnet20_cifar10, 10),
(resdropresnet20_cifar100, 100),
(resdropresnet20_svhn, 10),
]
for model, num_classes in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != resdropresnet20_cifar10 or weight_count == 272474)
assert (model != resdropresnet20_cifar100 or weight_count == 278324)
assert (model != resdropresnet20_svhn or weight_count == 272474)
x = torch.randn(14, 3, 32, 32)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (14, num_classes))
if __name__ == "__main__":
_test()
| 9,918 | 31.735974 | 119 | py |
null | qimera-main/pytorchcv/models/resnet.py | """
ResNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
"""
__all__ = ['ResNet', 'resnet10', 'resnet12', 'resnet14', 'resnetbc14b', 'resnet16', 'resnet18_wd4', 'resnet18_wd2',
'resnet18_w3d4', 'resnet18', 'resnet26', 'resnetbc26b', 'resnet34', 'resnetbc38b', 'resnet50', 'resnet50b',
'resnet101', 'resnet101b', 'resnet152', 'resnet152b', 'resnet200', 'resnet200b', 'ResBlock', 'ResBottleneck',
'ResUnit', 'ResInitBlock']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, conv3x3_block, conv7x7_block
class ResBlock(nn.Module):
"""
Simple ResNet block for residual path in ResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
"""
def __init__(self,
in_channels,
out_channels,
stride):
super(ResBlock, self).__init__()
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
self.conv2 = conv3x3_block(
in_channels=out_channels,
out_channels=out_channels,
activation=None)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class ResBottleneck(nn.Module):
"""
ResNet bottleneck block for residual path in ResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for the second convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for the second convolution layer.
conv1_stride : bool, default False
Whether to use stride in the first or the second convolution layer of the block.
bottleneck_factor : int, default 4
Bottleneck factor.
"""
def __init__(self,
in_channels,
out_channels,
stride,
padding=1,
dilation=1,
conv1_stride=False,
bottleneck_factor=4):
super(ResBottleneck, self).__init__()
mid_channels = out_channels // bottleneck_factor
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
stride=(stride if conv1_stride else 1))
self.conv2 = conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
stride=(1 if conv1_stride else stride),
padding=padding,
dilation=dilation)
self.conv3 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
activation=None)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class ResUnit(nn.Module):
"""
ResNet unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for the second convolution layer in bottleneck.
dilation : int or tuple/list of 2 int, default 1
Dilation value for the second convolution layer in bottleneck.
bottleneck : bool, default True
Whether to use a bottleneck or simple block in units.
conv1_stride : bool, default False
Whether to use stride in the first or the second convolution layer of the block.
"""
def __init__(self,
in_channels,
out_channels,
stride,
padding=1,
dilation=1,
bottleneck=True,
conv1_stride=False):
super(ResUnit, self).__init__()
self.resize_identity = (in_channels != out_channels) or (stride != 1)
if bottleneck:
self.body = ResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
padding=padding,
dilation=dilation,
conv1_stride=conv1_stride)
else:
self.body = ResBlock(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
activation=None)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = x + identity
x = self.activ(x)
return x
class ResInitBlock(nn.Module):
"""
ResNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(ResInitBlock, self).__init__()
self.conv = conv7x7_block(
in_channels=in_channels,
out_channels=out_channels,
stride=2)
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=1)
def forward(self, x):
x = self.conv(x)
x = self.pool(x)
return x
class ResNet(nn.Module):
"""
ResNet model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer in units.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
conv1_stride,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(ResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), ResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck,
conv1_stride=conv1_stride))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x, out_feature=False):
x = self.features(x)
feature = x.view(x.size(0), -1)
x = self.output(feature)
if out_feature == False:
return x
else:
return x, feature
def get_resnet(blocks,
bottleneck=None,
conv1_stride=True,
width_scale=1.0,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create ResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
bottleneck : bool, default None
Whether to use a bottleneck or simple block in units.
conv1_stride : bool, default True
Whether to use stride in the first or the second convolution layer in units.
width_scale : float, default 1.0
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if bottleneck is None:
bottleneck = (blocks >= 50)
if blocks == 10:
layers = [1, 1, 1, 1]
elif blocks == 12:
layers = [2, 1, 1, 1]
elif blocks == 14 and not bottleneck:
layers = [2, 2, 1, 1]
elif (blocks == 14) and bottleneck:
layers = [1, 1, 1, 1]
elif blocks == 16:
layers = [2, 2, 2, 1]
elif blocks == 18:
layers = [2, 2, 2, 2]
elif (blocks == 26) and not bottleneck:
layers = [3, 3, 3, 3]
elif (blocks == 26) and bottleneck:
layers = [2, 2, 2, 2]
elif blocks == 34:
layers = [3, 4, 6, 3]
elif (blocks == 38) and bottleneck:
layers = [3, 3, 3, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
elif blocks == 200:
layers = [3, 24, 36, 3]
else:
raise ValueError("Unsupported ResNet with number of blocks: {}".format(blocks))
if bottleneck:
assert (sum(layers) * 3 + 2 == blocks)
else:
assert (sum(layers) * 2 + 2 == blocks)
init_block_channels = 64
channels_per_layers = [64, 128, 256, 512]
if bottleneck:
bottleneck_factor = 4
channels_per_layers = [ci * bottleneck_factor for ci in channels_per_layers]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if width_scale != 1.0:
channels = [[int(cij * width_scale) if (i != len(channels) - 1) or (j != len(ci) - 1) else cij
for j, cij in enumerate(ci)] for i, ci in enumerate(channels)]
init_block_channels = int(init_block_channels * width_scale)
net = ResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def resnet10(**kwargs):
"""
ResNet-10 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=10, model_name="resnet10", **kwargs)
def resnet12(**kwargs):
"""
ResNet-12 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=12, model_name="resnet12", **kwargs)
def resnet14(**kwargs):
"""
ResNet-14 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=14, model_name="resnet14", **kwargs)
def resnetbc14b(**kwargs):
"""
ResNet-BC-14b model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
It's an experimental model (bottleneck compressed).
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=14, bottleneck=True, conv1_stride=False, model_name="resnetbc14b", **kwargs)
def resnet16(**kwargs):
"""
ResNet-16 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=16, model_name="resnet16", **kwargs)
def resnet18_wd4(**kwargs):
"""
ResNet-18 model with 0.25 width scale from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385. It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=18, width_scale=0.25, model_name="resnet18_wd4", **kwargs)
def resnet18_wd2(**kwargs):
"""
ResNet-18 model with 0.5 width scale from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385. It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=18, width_scale=0.5, model_name="resnet18_wd2", **kwargs)
def resnet18_w3d4(**kwargs):
"""
ResNet-18 model with 0.75 width scale from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385. It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=18, width_scale=0.75, model_name="resnet18_w3d4", **kwargs)
def resnet18(**kwargs):
"""
ResNet-18 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=18, model_name="resnet18", **kwargs)
def resnet26(**kwargs):
"""
ResNet-26 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=26, bottleneck=False, model_name="resnet26", **kwargs)
def resnetbc26b(**kwargs):
"""
ResNet-BC-26b model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
It's an experimental model (bottleneck compressed).
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=26, bottleneck=True, conv1_stride=False, model_name="resnetbc26b", **kwargs)
def resnet34(**kwargs):
"""
ResNet-34 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=34, model_name="resnet34", **kwargs)
def resnetbc38b(**kwargs):
"""
ResNet-BC-38b model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
It's an experimental model (bottleneck compressed).
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=38, bottleneck=True, conv1_stride=False, model_name="resnetbc38b", **kwargs)
def resnet50(**kwargs):
"""
ResNet-50 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=50, model_name="resnet50", **kwargs)
def resnet50b(**kwargs):
"""
ResNet-50 model with stride at the second convolution in bottleneck block from 'Deep Residual Learning for Image
Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=50, conv1_stride=False, model_name="resnet50b", **kwargs)
def resnet101(**kwargs):
"""
ResNet-101 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=101, model_name="resnet101", **kwargs)
def resnet101b(**kwargs):
"""
ResNet-101 model with stride at the second convolution in bottleneck block from 'Deep Residual Learning for Image
Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=101, conv1_stride=False, model_name="resnet101b", **kwargs)
def resnet152(**kwargs):
"""
ResNet-152 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=152, model_name="resnet152", **kwargs)
def resnet152b(**kwargs):
"""
ResNet-152 model with stride at the second convolution in bottleneck block from 'Deep Residual Learning for Image
Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=152, conv1_stride=False, model_name="resnet152b", **kwargs)
def resnet200(**kwargs):
"""
ResNet-200 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=200, model_name="resnet200", **kwargs)
def resnet200b(**kwargs):
"""
ResNet-200 model with stride at the second convolution in bottleneck block from 'Deep Residual Learning for Image
Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=200, conv1_stride=False, model_name="resnet200b", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
resnet10,
resnet12,
resnet14,
resnetbc14b,
resnet16,
resnet18_wd4,
resnet18_wd2,
resnet18_w3d4,
resnet18,
resnet26,
resnetbc26b,
resnet34,
resnetbc38b,
resnet50,
resnet50b,
resnet101,
resnet101b,
resnet152,
resnet152b,
resnet200,
resnet200b,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != resnet10 or weight_count == 5418792)
assert (model != resnet12 or weight_count == 5492776)
assert (model != resnet14 or weight_count == 5788200)
assert (model != resnetbc14b or weight_count == 10064936)
assert (model != resnet16 or weight_count == 6968872)
assert (model != resnet18_wd4 or weight_count == 3937400)
assert (model != resnet18_wd2 or weight_count == 5804296)
assert (model != resnet18_w3d4 or weight_count == 8476056)
assert (model != resnet18 or weight_count == 11689512)
assert (model != resnet26 or weight_count == 17960232)
assert (model != resnetbc26b or weight_count == 15995176)
assert (model != resnet34 or weight_count == 21797672)
assert (model != resnetbc38b or weight_count == 21925416)
assert (model != resnet50 or weight_count == 25557032)
assert (model != resnet50b or weight_count == 25557032)
assert (model != resnet101 or weight_count == 44549160)
assert (model != resnet101b or weight_count == 44549160)
assert (model != resnet152 or weight_count == 60192808)
assert (model != resnet152b or weight_count == 60192808)
assert (model != resnet200 or weight_count == 64673832)
assert (model != resnet200b or weight_count == 64673832)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 24,823 | 31.620237 | 120 | py |
null | qimera-main/pytorchcv/models/resnet_cifar.py | """
ResNet for CIFAR/SVHN, implemented in PyTorch.
Original paper: 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
"""
__all__ = ['CIFARResNet', 'resnet20_cifar10', 'resnet20_cifar100', 'resnet20_svhn',
'resnet56_cifar10', 'resnet56_cifar100', 'resnet56_svhn',
'resnet110_cifar10', 'resnet110_cifar100', 'resnet110_svhn',
'resnet164bn_cifar10', 'resnet164bn_cifar100', 'resnet164bn_svhn',
'resnet272bn_cifar10', 'resnet272bn_cifar100', 'resnet272bn_svhn',
'resnet542bn_cifar10', 'resnet542bn_cifar100', 'resnet542bn_svhn',
'resnet1001_cifar10', 'resnet1001_cifar100', 'resnet1001_svhn',
'resnet1202_cifar10', 'resnet1202_cifar100', 'resnet1202_svhn']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv3x3_block
from .resnet import ResUnit
class CIFARResNet(nn.Module):
"""
ResNet model for CIFAR from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
num_classes : int, default 10
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
in_channels=3,
in_size=(32, 32),
num_classes=10):
super(CIFARResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), ResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck,
conv1_stride=False))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=8,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x, out_feature=False):
x = self.features(x)
feature = x.view(x.size(0), -1)
x = self.output(feature)
if out_feature == False:
return x
else:
return x, feature
def get_resnet_cifar(num_classes,
blocks,
bottleneck,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create ResNet model for CIFAR with specific parameters.
Parameters:
----------
num_classes : int
Number of classification classes.
blocks : int
Number of blocks.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
assert (num_classes in [10, 100])
if bottleneck:
assert ((blocks - 2) % 9 == 0)
layers = [(blocks - 2) // 9] * 3
else:
assert ((blocks - 2) % 6 == 0)
layers = [(blocks - 2) // 6] * 3
channels_per_layers = [16, 32, 64]
init_block_channels = 16
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if bottleneck:
channels = [[cij * 4 for cij in ci] for ci in channels]
net = CIFARResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
num_classes=num_classes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def resnet20_cifar10(num_classes=10, **kwargs):
"""
ResNet-20 model for CIFAR-10 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=20, bottleneck=False, model_name="resnet20_cifar10",
**kwargs)
def resnet20_cifar100(num_classes=100, **kwargs):
"""
ResNet-20 model for CIFAR-100 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=20, bottleneck=False, model_name="resnet20_cifar100",
**kwargs)
def resnet20_svhn(num_classes=10, **kwargs):
"""
ResNet-20 model for SVHN from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=20, bottleneck=False, model_name="resnet20_svhn",
**kwargs)
def resnet56_cifar10(num_classes=10, **kwargs):
"""
ResNet-56 model for CIFAR-10 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=56, bottleneck=False, model_name="resnet56_cifar10",
**kwargs)
def resnet56_cifar100(num_classes=100, **kwargs):
"""
ResNet-56 model for CIFAR-100 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=56, bottleneck=False, model_name="resnet56_cifar100",
**kwargs)
def resnet56_svhn(num_classes=10, **kwargs):
"""
ResNet-56 model for SVHN from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=56, bottleneck=False, model_name="resnet56_svhn",
**kwargs)
def resnet110_cifar10(num_classes=10, **kwargs):
"""
ResNet-110 model for CIFAR-10 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=110, bottleneck=False, model_name="resnet110_cifar10",
**kwargs)
def resnet110_cifar100(num_classes=100, **kwargs):
"""
ResNet-110 model for CIFAR-100 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=110, bottleneck=False, model_name="resnet110_cifar100",
**kwargs)
def resnet110_svhn(num_classes=10, **kwargs):
"""
ResNet-110 model for SVHN from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=110, bottleneck=False, model_name="resnet110_svhn",
**kwargs)
def resnet164bn_cifar10(num_classes=10, **kwargs):
"""
ResNet-164(BN) model for CIFAR-10 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=164, bottleneck=True, model_name="resnet164bn_cifar10",
**kwargs)
def resnet164bn_cifar100(num_classes=100, **kwargs):
"""
ResNet-164(BN) model for CIFAR-100 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=164, bottleneck=True, model_name="resnet164bn_cifar100",
**kwargs)
def resnet164bn_svhn(num_classes=10, **kwargs):
"""
ResNet-164(BN) model for SVHN from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=164, bottleneck=True, model_name="resnet164bn_svhn",
**kwargs)
def resnet272bn_cifar10(num_classes=10, **kwargs):
"""
ResNet-272(BN) model for CIFAR-10 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=272, bottleneck=True, model_name="resnet272bn_cifar10",
**kwargs)
def resnet272bn_cifar100(num_classes=100, **kwargs):
"""
ResNet-272(BN) model for CIFAR-100 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=272, bottleneck=True, model_name="resnet272bn_cifar100",
**kwargs)
def resnet272bn_svhn(num_classes=10, **kwargs):
"""
ResNet-272(BN) model for SVHN from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=272, bottleneck=True, model_name="resnet272bn_svhn",
**kwargs)
def resnet542bn_cifar10(num_classes=10, **kwargs):
"""
ResNet-542(BN) model for CIFAR-10 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=542, bottleneck=True, model_name="resnet542bn_cifar10",
**kwargs)
def resnet542bn_cifar100(num_classes=100, **kwargs):
"""
ResNet-542(BN) model for CIFAR-100 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=542, bottleneck=True, model_name="resnet542bn_cifar100",
**kwargs)
def resnet542bn_svhn(num_classes=10, **kwargs):
"""
ResNet-542(BN) model for SVHN from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=542, bottleneck=True, model_name="resnet542bn_svhn",
**kwargs)
def resnet1001_cifar10(num_classes=10, **kwargs):
"""
ResNet-1001 model for CIFAR-10 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=1001, bottleneck=True, model_name="resnet1001_cifar10",
**kwargs)
def resnet1001_cifar100(num_classes=100, **kwargs):
"""
ResNet-1001 model for CIFAR-100 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=1001, bottleneck=True, model_name="resnet1001_cifar100",
**kwargs)
def resnet1001_svhn(num_classes=10, **kwargs):
"""
ResNet-1001 model for SVHN from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=1001, bottleneck=True, model_name="resnet1001_svhn",
**kwargs)
def resnet1202_cifar10(num_classes=10, **kwargs):
"""
ResNet-1202 model for CIFAR-10 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=1202, bottleneck=False, model_name="resnet1202_cifar10",
**kwargs)
def resnet1202_cifar100(num_classes=100, **kwargs):
"""
ResNet-1202 model for CIFAR-100 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=1202, bottleneck=False, model_name="resnet1202_cifar100",
**kwargs)
def resnet1202_svhn(num_classes=10, **kwargs):
"""
ResNet-1202 model for SVHN from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(num_classes=num_classes, blocks=1202, bottleneck=False, model_name="resnet1202_svhn",
**kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
(resnet20_cifar10, 10),
(resnet20_cifar100, 100),
(resnet20_svhn, 10),
(resnet56_cifar10, 10),
(resnet56_cifar100, 100),
(resnet56_svhn, 10),
(resnet110_cifar10, 10),
(resnet110_cifar100, 100),
(resnet110_svhn, 10),
(resnet164bn_cifar10, 10),
(resnet164bn_cifar100, 100),
(resnet164bn_svhn, 10),
(resnet272bn_cifar10, 10),
(resnet272bn_cifar100, 100),
(resnet272bn_svhn, 10),
(resnet542bn_cifar10, 10),
(resnet542bn_cifar100, 100),
(resnet542bn_svhn, 10),
(resnet1001_cifar10, 10),
(resnet1001_cifar100, 100),
(resnet1001_svhn, 10),
(resnet1202_cifar10, 10),
(resnet1202_cifar100, 100),
(resnet1202_svhn, 10),
]
for model, num_classes in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != resnet20_cifar10 or weight_count == 272474)
assert (model != resnet20_cifar100 or weight_count == 278324)
assert (model != resnet20_svhn or weight_count == 272474)
assert (model != resnet56_cifar10 or weight_count == 855770)
assert (model != resnet56_cifar100 or weight_count == 861620)
assert (model != resnet56_svhn or weight_count == 855770)
assert (model != resnet110_cifar10 or weight_count == 1730714)
assert (model != resnet110_cifar100 or weight_count == 1736564)
assert (model != resnet110_svhn or weight_count == 1730714)
assert (model != resnet164bn_cifar10 or weight_count == 1704154)
assert (model != resnet164bn_cifar100 or weight_count == 1727284)
assert (model != resnet164bn_svhn or weight_count == 1704154)
assert (model != resnet272bn_cifar10 or weight_count == 2816986)
assert (model != resnet272bn_cifar100 or weight_count == 2840116)
assert (model != resnet272bn_svhn or weight_count == 2816986)
assert (model != resnet542bn_cifar10 or weight_count == 5599066)
assert (model != resnet542bn_cifar100 or weight_count == 5622196)
assert (model != resnet542bn_svhn or weight_count == 5599066)
assert (model != resnet1001_cifar10 or weight_count == 10328602)
assert (model != resnet1001_cifar100 or weight_count == 10351732)
assert (model != resnet1001_svhn or weight_count == 10328602)
assert (model != resnet1202_cifar10 or weight_count == 19424026)
assert (model != resnet1202_cifar100 or weight_count == 19429876)
assert (model != resnet1202_svhn or weight_count == 19424026)
x = torch.randn(1, 3, 32, 32)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, num_classes))
if __name__ == "__main__":
_test()
| 23,994 | 35.137048 | 120 | py |
null | qimera-main/pytorchcv/models/resnet_cub.py | """
ResNet for CUB-200-2011, implemented in PyTorch.
Original paper: 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
"""
__all__ = ['resnet10_cub', 'resnet12_cub', 'resnet14_cub', 'resnetbc14b_cub', 'resnet16_cub', 'resnet18_cub',
'resnet26_cub', 'resnetbc26b_cub', 'resnet34_cub', 'resnetbc38b_cub', 'resnet50_cub', 'resnet50b_cub',
'resnet101_cub', 'resnet101b_cub', 'resnet152_cub', 'resnet152b_cub', 'resnet200_cub', 'resnet200b_cub']
from .resnet import get_resnet
def resnet10_cub(num_classes=200, **kwargs):
"""
ResNet-10 model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385. It's an experimental model.
Parameters:
----------
classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(num_classes=num_classes, blocks=10, model_name="resnet10_cub", **kwargs)
def resnet12_cub(num_classes=200, **kwargs):
"""
ResNet-12 model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385. It's an experimental model.
Parameters:
----------
classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(num_classes=num_classes, blocks=12, model_name="resnet12_cub", **kwargs)
def resnet14_cub(num_classes=200, **kwargs):
"""
ResNet-14 model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385. It's an experimental model.
Parameters:
----------
classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(num_classes=num_classes, blocks=14, model_name="resnet14_cub", **kwargs)
def resnetbc14b_cub(num_classes=200, **kwargs):
"""
ResNet-BC-14b model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385. It's an experimental model (bottleneck compressed).
Parameters:
----------
classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(num_classes=num_classes, blocks=14, bottleneck=True, conv1_stride=False,
model_name="resnetbc14b_cub", **kwargs)
def resnet16_cub(num_classes=200, **kwargs):
"""
ResNet-16 model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385. It's an experimental model.
Parameters:
----------
classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(num_classes=num_classes, blocks=16, model_name="resnet16_cub", **kwargs)
def resnet18_cub(num_classes=200, **kwargs):
"""
ResNet-18 model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(num_classes=num_classes, blocks=18, model_name="resnet18_cub", **kwargs)
def resnet26_cub(num_classes=200, **kwargs):
"""
ResNet-26 model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385. It's an experimental model.
Parameters:
----------
classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(num_classes=num_classes, blocks=26, bottleneck=False, model_name="resnet26_cub", **kwargs)
def resnetbc26b_cub(num_classes=200, **kwargs):
"""
ResNet-BC-26b model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385. It's an experimental model (bottleneck compressed).
Parameters:
----------
classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(num_classes=num_classes, blocks=26, bottleneck=True, conv1_stride=False,
model_name="resnetbc26b_cub", **kwargs)
def resnet34_cub(num_classes=200, **kwargs):
"""
ResNet-34 model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(num_classes=num_classes, blocks=34, model_name="resnet34_cub", **kwargs)
def resnetbc38b_cub(num_classes=200, **kwargs):
"""
ResNet-BC-38b model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385. It's an experimental model (bottleneck compressed).
Parameters:
----------
classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(num_classes=num_classes, blocks=38, bottleneck=True, conv1_stride=False,
model_name="resnetbc38b_cub", **kwargs)
def resnet50_cub(num_classes=200, **kwargs):
"""
ResNet-50 model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(num_classes=num_classes, blocks=50, model_name="resnet50_cub", **kwargs)
def resnet50b_cub(num_classes=200, **kwargs):
"""
ResNet-50 model with stride at the second convolution in bottleneck block from 'Deep Residual Learning for Image
Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(num_classes=num_classes, blocks=50, conv1_stride=False, model_name="resnet50b_cub", **kwargs)
def resnet101_cub(num_classes=200, **kwargs):
"""
ResNet-101 model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(num_classes=num_classes, blocks=101, model_name="resnet101_cub", **kwargs)
def resnet101b_cub(num_classes=200, **kwargs):
"""
ResNet-101 model with stride at the second convolution in bottleneck block from 'Deep Residual Learning for Image
Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(num_classes=num_classes, blocks=101, conv1_stride=False, model_name="resnet101b_cub", **kwargs)
def resnet152_cub(num_classes=200, **kwargs):
"""
ResNet-152 model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(num_classes=num_classes, blocks=152, model_name="resnet152_cub", **kwargs)
def resnet152b_cub(num_classes=200, **kwargs):
"""
ResNet-152 model with stride at the second convolution in bottleneck block from 'Deep Residual Learning for Image
Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(num_classes=num_classes, blocks=152, conv1_stride=False, model_name="resnet152b_cub", **kwargs)
def resnet200_cub(num_classes=200, **kwargs):
"""
ResNet-200 model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385. It's an experimental model.
Parameters:
----------
classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(num_classes=num_classes, blocks=200, model_name="resnet200_cub", **kwargs)
def resnet200b_cub(num_classes=200, **kwargs):
"""
ResNet-200 model with stride at the second convolution in bottleneck block from 'Deep Residual Learning for Image
Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model.
Parameters:
----------
classes : int, default 200
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnet(num_classes=num_classes, blocks=200, conv1_stride=False, model_name="resnet200b_cub", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
resnet10_cub,
resnet12_cub,
resnet14_cub,
resnetbc14b_cub,
resnet16_cub,
resnet18_cub,
resnet26_cub,
resnetbc26b_cub,
resnet34_cub,
resnetbc38b_cub,
resnet50_cub,
resnet50b_cub,
resnet101_cub,
resnet101b_cub,
resnet152_cub,
resnet152b_cub,
resnet200_cub,
resnet200b_cub,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != resnet10_cub or weight_count == 5008392)
assert (model != resnet12_cub or weight_count == 5082376)
assert (model != resnet14_cub or weight_count == 5377800)
assert (model != resnetbc14b_cub or weight_count == 8425736)
assert (model != resnet16_cub or weight_count == 6558472)
assert (model != resnet18_cub or weight_count == 11279112)
assert (model != resnet26_cub or weight_count == 17549832)
assert (model != resnetbc26b_cub or weight_count == 14355976)
assert (model != resnet34_cub or weight_count == 21387272)
assert (model != resnetbc38b_cub or weight_count == 20286216)
assert (model != resnet50_cub or weight_count == 23917832)
assert (model != resnet50b_cub or weight_count == 23917832)
assert (model != resnet101_cub or weight_count == 42909960)
assert (model != resnet101b_cub or weight_count == 42909960)
assert (model != resnet152_cub or weight_count == 58553608)
assert (model != resnet152b_cub or weight_count == 58553608)
assert (model != resnet200_cub or weight_count == 63034632)
assert (model != resnet200b_cub or weight_count == 63034632)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 200))
if __name__ == "__main__":
_test()
| 14,148 | 35.094388 | 117 | py |
null | qimera-main/pytorchcv/models/resnetd.py | """
ResNet(D) with dilation for ImageNet-1K, implemented in PyTorch.
Original paper: 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
"""
__all__ = ['ResNetD', 'resnetd50b', 'resnetd101b', 'resnetd152b']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import MultiOutputSequential
from .resnet import ResUnit, ResInitBlock
from .senet import SEInitBlock
class ResNetD(nn.Module):
"""
ResNet(D) with dilation model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer in units.
ordinary_init : bool, default False
Whether to use original initial block or SENet one.
multi_output : bool, default False
Whether to return intermediate outputs.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
conv1_stride,
ordinary_init=False,
multi_output=False,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(ResNetD, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.multi_output = multi_output
self.features = MultiOutputSequential()
if ordinary_init:
self.features.add_module("init_block", ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
else:
init_block_channels = 2 * init_block_channels
self.features.add_module("init_block", SEInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if ((j == 0) and (i != 0) and (i < 2)) else 1
dilation = (2 ** max(0, i - 1 - int(j == 0)))
stage.add_module("unit{}".format(j + 1), ResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
padding=dilation,
dilation=dilation,
bottleneck=bottleneck,
conv1_stride=conv1_stride))
in_channels = out_channels
if i == 2:
stage.do_output = True
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AdaptiveAvgPool2d(output_size=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
outs = self.features(x)
x = outs[0]
x = x.view(x.size(0), -1)
x = self.output(x)
if self.multi_output:
return [x] + outs[1:]
else:
return x
def get_resnetd(blocks,
conv1_stride=True,
width_scale=1.0,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create ResNet(D) with dilation model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
conv1_stride : bool, default True
Whether to use stride in the first or the second convolution layer in units.
width_scale : float, default 1.0
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 10:
layers = [1, 1, 1, 1]
elif blocks == 12:
layers = [2, 1, 1, 1]
elif blocks == 14:
layers = [2, 2, 1, 1]
elif blocks == 16:
layers = [2, 2, 2, 1]
elif blocks == 18:
layers = [2, 2, 2, 2]
elif blocks == 34:
layers = [3, 4, 6, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
elif blocks == 200:
layers = [3, 24, 36, 3]
else:
raise ValueError("Unsupported ResNet(D) with number of blocks: {}".format(blocks))
init_block_channels = 64
if blocks < 50:
channels_per_layers = [64, 128, 256, 512]
bottleneck = False
else:
channels_per_layers = [256, 512, 1024, 2048]
bottleneck = True
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if width_scale != 1.0:
channels = [[int(cij * width_scale) if (i != len(channels) - 1) or (j != len(ci) - 1) else cij
for j, cij in enumerate(ci)] for i, ci in enumerate(channels)]
init_block_channels = int(init_block_channels * width_scale)
net = ResNetD(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def resnetd50b(**kwargs):
"""
ResNet(D)-50 with dilation model with stride at the second convolution in bottleneck block from 'Deep Residual
Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnetd(blocks=50, conv1_stride=False, model_name="resnetd50b", **kwargs)
def resnetd101b(**kwargs):
"""
ResNet(D)-101 with dilation model with stride at the second convolution in bottleneck block from 'Deep Residual
Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnetd(blocks=101, conv1_stride=False, model_name="resnetd101b", **kwargs)
def resnetd152b(**kwargs):
"""
ResNet(D)-152 with dilation model with stride at the second convolution in bottleneck block from 'Deep Residual
Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnetd(blocks=152, conv1_stride=False, model_name="resnetd152b", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
ordinary_init = False
multi_output = False
pretrained = False
models = [
resnetd50b,
resnetd101b,
resnetd152b,
]
for model in models:
net = model(
pretrained=pretrained,
ordinary_init=ordinary_init,
multi_output=multi_output)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
if ordinary_init:
assert (model != resnetd50b or weight_count == 25557032)
assert (model != resnetd101b or weight_count == 44549160)
assert (model != resnetd152b or weight_count == 60192808)
else:
assert (model != resnetd50b or weight_count == 25680808)
assert (model != resnetd101b or weight_count == 44672936)
assert (model != resnetd152b or weight_count == 60316584)
x = torch.randn(1, 3, 224, 224)
y = net(x)
if multi_output:
y = y[0]
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 9,661 | 32.202749 | 120 | py |
null | qimera-main/pytorchcv/models/resnext.py | """
ResNeXt for ImageNet-1K, implemented in PyTorch.
Original paper: 'Aggregated Residual Transformations for Deep Neural Networks,' http://arxiv.org/abs/1611.05431.
"""
__all__ = ['ResNeXt', 'resnext14_16x4d', 'resnext14_32x2d', 'resnext14_32x4d', 'resnext26_16x4d', 'resnext26_32x2d',
'resnext26_32x4d', 'resnext38_32x4d', 'resnext50_32x4d', 'resnext101_32x4d', 'resnext101_64x4d',
'ResNeXtBottleneck', 'ResNeXtUnit']
import os
import math
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, conv3x3_block
from .resnet import ResInitBlock
class ResNeXtBottleneck(nn.Module):
"""
ResNeXt bottleneck block for residual path in ResNeXt unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
bottleneck_factor : int, default 4
Bottleneck factor.
"""
def __init__(self,
in_channels,
out_channels,
stride,
cardinality,
bottleneck_width,
bottleneck_factor=4):
super(ResNeXtBottleneck, self).__init__()
mid_channels = out_channels // bottleneck_factor
D = int(math.floor(mid_channels * (bottleneck_width / 64.0)))
group_width = cardinality * D
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=group_width)
self.conv2 = conv3x3_block(
in_channels=group_width,
out_channels=group_width,
stride=stride,
groups=cardinality)
self.conv3 = conv1x1_block(
in_channels=group_width,
out_channels=out_channels,
activation=None)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class ResNeXtUnit(nn.Module):
"""
ResNeXt unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
"""
def __init__(self,
in_channels,
out_channels,
stride,
cardinality,
bottleneck_width):
super(ResNeXtUnit, self).__init__()
self.resize_identity = (in_channels != out_channels) or (stride != 1)
self.body = ResNeXtBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
cardinality=cardinality,
bottleneck_width=bottleneck_width)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
activation=None)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = x + identity
x = self.activ(x)
return x
class ResNeXt(nn.Module):
"""
ResNeXt model from 'Aggregated Residual Transformations for Deep Neural Networks,' http://arxiv.org/abs/1611.05431.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
cardinality,
bottleneck_width,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(ResNeXt, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), ResNeXtUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
cardinality=cardinality,
bottleneck_width=bottleneck_width))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_resnext(blocks,
cardinality,
bottleneck_width,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create ResNeXt model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 14:
layers = [1, 1, 1, 1]
elif blocks == 26:
layers = [2, 2, 2, 2]
elif blocks == 38:
layers = [3, 3, 3, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
else:
raise ValueError("Unsupported ResNeXt with number of blocks: {}".format(blocks))
assert (sum(layers) * 3 + 2 == blocks)
init_block_channels = 64
channels_per_layers = [256, 512, 1024, 2048]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = ResNeXt(
channels=channels,
init_block_channels=init_block_channels,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def resnext14_16x4d(**kwargs):
"""
ResNeXt-14 (16x4d) model from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext(blocks=14, cardinality=16, bottleneck_width=4, model_name="resnext14_16x4d", **kwargs)
def resnext14_32x2d(**kwargs):
"""
ResNeXt-14 (32x2d) model from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext(blocks=14, cardinality=32, bottleneck_width=2, model_name="resnext14_32x2d", **kwargs)
def resnext14_32x4d(**kwargs):
"""
ResNeXt-14 (32x4d) model from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext(blocks=14, cardinality=32, bottleneck_width=4, model_name="resnext14_32x4d", **kwargs)
def resnext26_16x4d(**kwargs):
"""
ResNeXt-26 (16x4d) model from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext(blocks=26, cardinality=16, bottleneck_width=4, model_name="resnext26_16x4d", **kwargs)
def resnext26_32x2d(**kwargs):
"""
ResNeXt-26 (32x2d) model from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext(blocks=26, cardinality=32, bottleneck_width=2, model_name="resnext26_32x2d", **kwargs)
def resnext26_32x4d(**kwargs):
"""
ResNeXt-26 (32x4d) model from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext(blocks=26, cardinality=32, bottleneck_width=4, model_name="resnext26_32x4d", **kwargs)
def resnext38_32x4d(**kwargs):
"""
ResNeXt-38 (32x4d) model from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext(blocks=38, cardinality=32, bottleneck_width=4, model_name="resnext38_32x4d", **kwargs)
def resnext50_32x4d(**kwargs):
"""
ResNeXt-50 (32x4d) model from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext(blocks=50, cardinality=32, bottleneck_width=4, model_name="resnext50_32x4d", **kwargs)
def resnext101_32x4d(**kwargs):
"""
ResNeXt-101 (32x4d) model from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext(blocks=101, cardinality=32, bottleneck_width=4, model_name="resnext101_32x4d", **kwargs)
def resnext101_64x4d(**kwargs):
"""
ResNeXt-101 (64x4d) model from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext(blocks=101, cardinality=64, bottleneck_width=4, model_name="resnext101_64x4d", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
resnext14_16x4d,
resnext14_32x2d,
resnext14_32x4d,
resnext26_16x4d,
resnext26_32x2d,
resnext26_32x4d,
resnext38_32x4d,
resnext50_32x4d,
resnext101_32x4d,
resnext101_64x4d,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != resnext14_16x4d or weight_count == 7127336)
assert (model != resnext14_32x2d or weight_count == 7029416)
assert (model != resnext14_32x4d or weight_count == 9411880)
assert (model != resnext26_16x4d or weight_count == 10119976)
assert (model != resnext26_32x2d or weight_count == 9924136)
assert (model != resnext26_32x4d or weight_count == 15389480)
assert (model != resnext38_32x4d or weight_count == 21367080)
assert (model != resnext50_32x4d or weight_count == 25028904)
assert (model != resnext101_32x4d or weight_count == 44177704)
assert (model != resnext101_64x4d or weight_count == 83455272)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 14,857 | 31.090713 | 119 | py |
null | qimera-main/pytorchcv/models/resnext_cifar.py | """
ResNeXt for CIFAR/SVHN, implemented in PyTorch.
Original paper: 'Aggregated Residual Transformations for Deep Neural Networks,' http://arxiv.org/abs/1611.05431.
"""
__all__ = ['CIFARResNeXt', 'resnext20_16x4d_cifar10', 'resnext20_16x4d_cifar100', 'resnext20_16x4d_svhn',
'resnext20_32x2d_cifar10', 'resnext20_32x2d_cifar100', 'resnext20_32x2d_svhn',
'resnext20_32x4d_cifar10', 'resnext20_32x4d_cifar100', 'resnext20_32x4d_svhn',
'resnext29_32x4d_cifar10', 'resnext29_32x4d_cifar100', 'resnext29_32x4d_svhn',
'resnext29_16x64d_cifar10', 'resnext29_16x64d_cifar100', 'resnext29_16x64d_svhn',
'resnext272_1x64d_cifar10', 'resnext272_1x64d_cifar100', 'resnext272_1x64d_svhn',
'resnext272_2x32d_cifar10', 'resnext272_2x32d_cifar100', 'resnext272_2x32d_svhn']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv3x3_block
from .resnext import ResNeXtUnit
class CIFARResNeXt(nn.Module):
"""
ResNeXt model for CIFAR from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
num_classes : int, default 10
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
cardinality,
bottleneck_width,
in_channels=3,
in_size=(32, 32),
num_classes=10):
super(CIFARResNeXt, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), ResNeXtUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
cardinality=cardinality,
bottleneck_width=bottleneck_width))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=8,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_resnext_cifar(num_classes,
blocks,
cardinality,
bottleneck_width,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
ResNeXt model for CIFAR with specific parameters.
Parameters:
----------
num_classes : int
Number of classification classes.
blocks : int
Number of blocks.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
assert (blocks - 2) % 9 == 0
layers = [(blocks - 2) // 9] * 3
channels_per_layers = [256, 512, 1024]
init_block_channels = 64
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = CIFARResNeXt(
channels=channels,
init_block_channels=init_block_channels,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
num_classes=num_classes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def resnext20_16x4d_cifar10(num_classes=10, **kwargs):
"""
ResNeXt-20 (16x4d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(num_classes=num_classes, blocks=20, cardinality=16, bottleneck_width=4,
model_name="resnext20_16x4d_cifar10", **kwargs)
def resnext20_16x4d_cifar100(num_classes=100, **kwargs):
"""
ResNeXt-20 (16x4d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(num_classes=num_classes, blocks=20, cardinality=16, bottleneck_width=4,
model_name="resnext20_16x4d_cifar100", **kwargs)
def resnext20_16x4d_svhn(num_classes=10, **kwargs):
"""
ResNeXt-20 (16x4d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(num_classes=num_classes, blocks=20, cardinality=16, bottleneck_width=4,
model_name="resnext20_16x4d_svhn", **kwargs)
def resnext20_32x2d_cifar10(num_classes=10, **kwargs):
"""
ResNeXt-20 (32x2d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(num_classes=num_classes, blocks=20, cardinality=32, bottleneck_width=2,
model_name="resnext20_32x2d_cifar10", **kwargs)
def resnext20_32x2d_cifar100(num_classes=100, **kwargs):
"""
ResNeXt-20 (32x2d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(num_classes=num_classes, blocks=20, cardinality=32, bottleneck_width=2,
model_name="resnext20_32x2d_cifar100", **kwargs)
def resnext20_32x2d_svhn(num_classes=10, **kwargs):
"""
ResNeXt-20 (32x2d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(num_classes=num_classes, blocks=20, cardinality=32, bottleneck_width=2,
model_name="resnext20_32x2d_svhn", **kwargs)
def resnext20_32x4d_cifar10(num_classes=10, **kwargs):
"""
ResNeXt-20 (32x4d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(num_classes=num_classes, blocks=20, cardinality=32, bottleneck_width=4,
model_name="resnext20_32x4d_cifar10", **kwargs)
def resnext20_32x4d_cifar100(num_classes=100, **kwargs):
"""
ResNeXt-20 (32x4d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(num_classes=num_classes, blocks=20, cardinality=32, bottleneck_width=4,
model_name="resnext20_32x4d_cifar100", **kwargs)
def resnext20_32x4d_svhn(num_classes=10, **kwargs):
"""
ResNeXt-20 (32x4d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(num_classes=num_classes, blocks=20, cardinality=32, bottleneck_width=4,
model_name="resnext20_32x4d_svhn", **kwargs)
def resnext29_32x4d_cifar10(num_classes=10, **kwargs):
"""
ResNeXt-29 (32x4d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(num_classes=num_classes, blocks=29, cardinality=32, bottleneck_width=4,
model_name="resnext29_32x4d_cifar10", **kwargs)
def resnext29_32x4d_cifar100(num_classes=100, **kwargs):
"""
ResNeXt-29 (32x4d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(num_classes=num_classes, blocks=29, cardinality=32, bottleneck_width=4,
model_name="resnext29_32x4d_cifar100", **kwargs)
def resnext29_32x4d_svhn(num_classes=10, **kwargs):
"""
ResNeXt-29 (32x4d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(num_classes=num_classes, blocks=29, cardinality=32, bottleneck_width=4,
model_name="resnext29_32x4d_svhn", **kwargs)
def resnext29_16x64d_cifar10(num_classes=10, **kwargs):
"""
ResNeXt-29 (16x64d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(num_classes=num_classes, blocks=29, cardinality=16, bottleneck_width=64,
model_name="resnext29_16x64d_cifar10", **kwargs)
def resnext29_16x64d_cifar100(num_classes=100, **kwargs):
"""
ResNeXt-29 (16x64d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(num_classes=num_classes, blocks=29, cardinality=16, bottleneck_width=64,
model_name="resnext29_16x64d_cifar100", **kwargs)
def resnext29_16x64d_svhn(num_classes=10, **kwargs):
"""
ResNeXt-29 (16x64d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(num_classes=num_classes, blocks=29, cardinality=16, bottleneck_width=64,
model_name="resnext29_16x64d_svhn", **kwargs)
def resnext272_1x64d_cifar10(num_classes=10, **kwargs):
"""
ResNeXt-272 (1x64d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(num_classes=num_classes, blocks=272, cardinality=1, bottleneck_width=64,
model_name="resnext272_1x64d_cifar10", **kwargs)
def resnext272_1x64d_cifar100(num_classes=100, **kwargs):
"""
ResNeXt-272 (1x64d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(num_classes=num_classes, blocks=272, cardinality=1, bottleneck_width=64,
model_name="resnext272_1x64d_cifar100", **kwargs)
def resnext272_1x64d_svhn(num_classes=10, **kwargs):
"""
ResNeXt-272 (1x64d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(num_classes=num_classes, blocks=272, cardinality=1, bottleneck_width=64,
model_name="resnext272_1x64d_svhn", **kwargs)
def resnext272_2x32d_cifar10(num_classes=10, **kwargs):
"""
ResNeXt-272 (2x32d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(num_classes=num_classes, blocks=272, cardinality=2, bottleneck_width=32,
model_name="resnext272_2x32d_cifar10", **kwargs)
def resnext272_2x32d_cifar100(num_classes=100, **kwargs):
"""
ResNeXt-272 (2x32d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(num_classes=num_classes, blocks=272, cardinality=2, bottleneck_width=32,
model_name="resnext272_2x32d_cifar100", **kwargs)
def resnext272_2x32d_svhn(num_classes=10, **kwargs):
"""
ResNeXt-272 (2x32d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(num_classes=num_classes, blocks=272, cardinality=2, bottleneck_width=32,
model_name="resnext272_2x32d_svhn", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
(resnext20_16x4d_cifar10, 10),
(resnext20_16x4d_cifar100, 100),
(resnext20_16x4d_svhn, 10),
(resnext20_32x2d_cifar10, 10),
(resnext20_32x2d_cifar100, 100),
(resnext20_32x2d_svhn, 10),
(resnext20_32x4d_cifar10, 10),
(resnext20_32x4d_cifar100, 100),
(resnext20_32x4d_svhn, 10),
(resnext29_32x4d_cifar10, 10),
(resnext29_32x4d_cifar100, 100),
(resnext29_32x4d_svhn, 10),
(resnext29_16x64d_cifar10, 10),
(resnext29_16x64d_cifar100, 100),
(resnext29_16x64d_svhn, 10),
(resnext272_1x64d_cifar10, 10),
(resnext272_1x64d_cifar100, 100),
(resnext272_1x64d_svhn, 10),
(resnext272_2x32d_cifar10, 10),
(resnext272_2x32d_cifar100, 100),
(resnext272_2x32d_svhn, 10),
]
for model, num_classes in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != resnext20_16x4d_cifar10 or weight_count == 1995082)
assert (model != resnext20_16x4d_cifar100 or weight_count == 2087332)
assert (model != resnext20_16x4d_svhn or weight_count == 1995082)
assert (model != resnext20_32x2d_cifar10 or weight_count == 1946698)
assert (model != resnext20_32x2d_cifar100 or weight_count == 2038948)
assert (model != resnext20_32x2d_svhn or weight_count == 1946698)
assert (model != resnext20_32x4d_cifar10 or weight_count == 3295562)
assert (model != resnext20_32x4d_cifar100 or weight_count == 3387812)
assert (model != resnext20_32x4d_svhn or weight_count == 3295562)
assert (model != resnext29_32x4d_cifar10 or weight_count == 4775754)
assert (model != resnext29_32x4d_cifar100 or weight_count == 4868004)
assert (model != resnext29_32x4d_svhn or weight_count == 4775754)
assert (model != resnext29_16x64d_cifar10 or weight_count == 68155210)
assert (model != resnext29_16x64d_cifar100 or weight_count == 68247460)
assert (model != resnext29_16x64d_svhn or weight_count == 68155210)
assert (model != resnext272_1x64d_cifar10 or weight_count == 44540746)
assert (model != resnext272_1x64d_cifar100 or weight_count == 44632996)
assert (model != resnext272_1x64d_svhn or weight_count == 44540746)
assert (model != resnext272_2x32d_cifar10 or weight_count == 32928586)
assert (model != resnext272_2x32d_cifar100 or weight_count == 33020836)
assert (model != resnext272_2x32d_svhn or weight_count == 32928586)
x = torch.randn(1, 3, 32, 32)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, num_classes))
if __name__ == "__main__":
_test()
| 23,083 | 37.092409 | 116 | py |
null | qimera-main/pytorchcv/models/revnet.py | """
RevNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'The Reversible Residual Network: Backpropagation Without Storing Activations,'
https://arxiv.org/abs/1707.04585.
"""
__all__ = ['RevNet', 'revnet38', 'revnet110', 'revnet164']
import os
from contextlib import contextmanager
import torch
import torch.nn as nn
import torch.nn.init as init
from torch.autograd import Variable
from .common import conv1x1, conv3x3, conv1x1_block, conv3x3_block, pre_conv1x1_block, pre_conv3x3_block
use_context_mans = int(
torch.__version__[0]) * 100 + int(torch.__version__[2]) - (1 if 'a' in torch.__version__ else 0) > 3
@contextmanager
def set_grad_enabled(grad_mode):
if not use_context_mans:
yield
else:
with torch.set_grad_enabled(grad_mode) as c:
yield [c]
class ReversibleBlockFunction(torch.autograd.Function):
"""
RevNet reversible block function.
"""
@staticmethod
def forward(ctx, x, fm, gm, *params):
with torch.no_grad():
x1, x2 = torch.chunk(x, chunks=2, dim=1)
x1 = x1.contiguous()
x2 = x2.contiguous()
y1 = x1 + fm(x2)
y2 = x2 + gm(y1)
y = torch.cat((y1, y2), dim=1)
x1.set_()
x2.set_()
y1.set_()
y2.set_()
del x1, x2, y1, y2
ctx.save_for_backward(x, y)
ctx.fm = fm
ctx.gm = gm
return y
@staticmethod
def backward(ctx, grad_y):
fm = ctx.fm
gm = ctx.gm
x, y = ctx.saved_variables
y1, y2 = torch.chunk(y, chunks=2, dim=1)
y1 = y1.contiguous()
y2 = y2.contiguous()
with torch.no_grad():
y1_z = Variable(y1.data, requires_grad=True)
x2 = y2 - gm(y1_z)
x1 = y1 - fm(x2)
with set_grad_enabled(True):
x1_ = Variable(x1.data, requires_grad=True)
x2_ = Variable(x2.data, requires_grad=True)
y1_ = x1_ + fm.forward(x2_)
y2_ = x2_ + gm(y1_)
y = torch.cat((y1_, y2_), dim=1)
dd = torch.autograd.grad(y, (x1_, x2_) + tuple(gm.parameters()) + tuple(fm.parameters()), grad_y)
gm_params_len = len([p for p in gm.parameters()])
gm_params_grads = dd[2:2 + gm_params_len]
fm_params_grads = dd[2 + gm_params_len:]
grad_x = torch.cat((dd[0], dd[1]), dim=1)
y1_.detach_()
y2_.detach_()
del y1_, y2_
x.data.set_(torch.cat((x1, x2), dim=1).data.contiguous())
return (grad_x, None, None) + fm_params_grads + gm_params_grads
class ReversibleBlock(nn.Module):
"""
RevNet reversible block.
Parameters:
----------
fm : nn.Module
Fm-function.
gm : nn.Module
Gm-function.
"""
def __init__(self,
fm,
gm):
super(ReversibleBlock, self).__init__()
self.gm = gm
self.fm = fm
self.rev_funct = ReversibleBlockFunction.apply
def forward(self, x):
assert (x.shape[1] % 2 == 0)
params = [w for w in self.fm.parameters()] + [w for w in self.gm.parameters()]
y = self.rev_funct(x, self.fm, self.gm, *params)
x.data.set_()
return y
def inverse(self, y):
assert (y.shape[1] % 2 == 0)
y1, y2 = torch.chunk(y, chunks=2, dim=1)
y1 = y1.contiguous()
y2 = y2.contiguous()
x2 = y2 - self.gm(y1)
x1 = y1 - self.fm(x2)
x = torch.cat((x1, x2), dim=1)
return x
class RevResBlock(nn.Module):
"""
Simple RevNet block for residual path in RevNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
preactivate : bool
Whether use pre-activation for the first convolution block.
"""
def __init__(self,
in_channels,
out_channels,
stride,
preactivate):
super(RevResBlock, self).__init__()
if preactivate:
self.conv1 = pre_conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
else:
self.conv1 = conv3x3(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
self.conv2 = pre_conv3x3_block(
in_channels=out_channels,
out_channels=out_channels)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class RevResBottleneck(nn.Module):
"""
RevNet bottleneck block for residual path in RevNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
preactivate : bool
Whether use pre-activation for the first convolution block.
bottleneck_factor : int, default 4
Bottleneck factor.
"""
def __init__(self,
in_channels,
out_channels,
stride,
preactivate,
bottleneck_factor=4):
super(RevResBottleneck, self).__init__()
mid_channels = out_channels // bottleneck_factor
if preactivate:
self.conv1 = pre_conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels)
else:
self.conv1 = conv1x1(
in_channels=in_channels,
out_channels=mid_channels)
self.conv2 = pre_conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride)
self.conv3 = pre_conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class RevUnit(nn.Module):
"""
RevNet unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
preactivate : bool
Whether use pre-activation for the first convolution block.
"""
def __init__(self,
in_channels,
out_channels,
stride,
bottleneck,
preactivate):
super(RevUnit, self).__init__()
self.resize_identity = (in_channels != out_channels) or (stride != 1)
body_class = RevResBottleneck if bottleneck else RevResBlock
if (not self.resize_identity) and (stride == 1):
assert (in_channels % 2 == 0)
assert (out_channels % 2 == 0)
in_channels2 = in_channels // 2
out_channels2 = out_channels // 2
gm = body_class(
in_channels=in_channels2,
out_channels=out_channels2,
stride=1,
preactivate=preactivate)
fm = body_class(
in_channels=in_channels2,
out_channels=out_channels2,
stride=1,
preactivate=preactivate)
self.body = ReversibleBlock(gm, fm)
else:
self.body = body_class(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
preactivate=preactivate)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
activation=None)
def forward(self, x):
if self.resize_identity:
identity = self.identity_conv(x)
x = self.body(x)
x = x + identity
else:
x = self.body(x)
return x
class RevPostActivation(nn.Module):
"""
RevNet specific post-activation block.
Parameters:
----------
in_channels : int
Number of input channels.
"""
def __init__(self,
in_channels):
super(RevPostActivation, self).__init__()
self.bn = nn.BatchNorm2d(num_features=in_channels)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
x = self.bn(x)
x = self.activ(x)
return x
class RevNet(nn.Module):
"""
RevNet model from 'The Reversible Residual Network: Backpropagation Without Storing Activations,'
https://arxiv.org/abs/1707.04585.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(RevNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
preactivate = (j != 0) or (i != 0)
stage.add_module("unit{}".format(j + 1), RevUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck,
preactivate=preactivate))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_postactiv", RevPostActivation(in_channels=in_channels))
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=56,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_revnet(blocks,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create RevNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 38:
layers = [3, 3, 3]
channels_per_layers = [32, 64, 112]
bottleneck = False
elif blocks == 110:
layers = [9, 9, 9]
channels_per_layers = [32, 64, 128]
bottleneck = False
elif blocks == 164:
layers = [9, 9, 9]
channels_per_layers = [128, 256, 512]
bottleneck = True
else:
raise ValueError("Unsupported RevNet with number of blocks: {}".format(blocks))
init_block_channels = 32
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = RevNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def revnet38(**kwargs):
"""
RevNet-38 model from 'The Reversible Residual Network: Backpropagation Without Storing Activations,'
https://arxiv.org/abs/1707.04585.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_revnet(blocks=38, model_name="revnet38", **kwargs)
def revnet110(**kwargs):
"""
RevNet-110 model from 'The Reversible Residual Network: Backpropagation Without Storing Activations,'
https://arxiv.org/abs/1707.04585.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_revnet(blocks=110, model_name="revnet110", **kwargs)
def revnet164(**kwargs):
"""
RevNet-164 model from 'The Reversible Residual Network: Backpropagation Without Storing Activations,'
https://arxiv.org/abs/1707.04585.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_revnet(blocks=164, model_name="revnet164", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
revnet38,
revnet110,
revnet164,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != revnet38 or weight_count == 685864)
assert (model != revnet110 or weight_count == 1982600)
assert (model != revnet164 or weight_count == 2491656)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 15,590 | 28.142056 | 115 | py |
null | qimera-main/pytorchcv/models/rir_cifar.py | """
RiR for CIFAR/SVHN, implemented in PyTorch.
Original paper: 'Resnet in Resnet: Generalizing Residual Architectures,' https://arxiv.org/abs/1603.08029.
"""
__all__ = ['CIFARRiR', 'rir_cifar10', 'rir_cifar100', 'rir_svhn', 'RiRFinalBlock']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1, conv3x3, conv1x1_block, conv3x3_block, DualPathSequential
class PostActivation(nn.Module):
"""
Pure pre-activation block without convolution layer.
Parameters:
----------
in_channels : int
Number of input channels.
"""
def __init__(self,
in_channels):
super(PostActivation, self).__init__()
self.bn = nn.BatchNorm2d(num_features=in_channels)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
x = self.bn(x)
x = self.activ(x)
return x
class RiRUnit(nn.Module):
"""
RiR unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
"""
def __init__(self,
in_channels,
out_channels,
stride):
super(RiRUnit, self).__init__()
self.resize_identity = (in_channels != out_channels) or (stride != 1)
self.res_pass_conv = conv3x3(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
self.trans_pass_conv = conv3x3(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
self.res_cross_conv = conv3x3(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
self.trans_cross_conv = conv3x3(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
self.res_postactiv = PostActivation(in_channels=out_channels)
self.trans_postactiv = PostActivation(in_channels=out_channels)
if self.resize_identity:
self.identity_conv = conv1x1(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
def forward(self, x_res, x_trans):
if self.resize_identity:
x_res_identity = self.identity_conv(x_res)
else:
x_res_identity = x_res
y_res = self.res_cross_conv(x_res)
y_trans = self.trans_cross_conv(x_trans)
x_res = self.res_pass_conv(x_res)
x_trans = self.trans_pass_conv(x_trans)
x_res = x_res + x_res_identity + y_trans
x_trans = x_trans + y_res
x_res = self.res_postactiv(x_res)
x_trans = self.trans_postactiv(x_trans)
return x_res, x_trans
class RiRInitBlock(nn.Module):
"""
RiR initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(RiRInitBlock, self).__init__()
self.res_conv = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels)
self.trans_conv = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels)
def forward(self, x, _):
x_res = self.res_conv(x)
x_trans = self.trans_conv(x)
return x_res, x_trans
class RiRFinalBlock(nn.Module):
"""
RiR final block.
"""
def __init__(self):
super(RiRFinalBlock, self).__init__()
def forward(self, x_res, x_trans):
x = torch.cat((x_res, x_trans), dim=1)
return x, None
class CIFARRiR(nn.Module):
"""
RiR model for CIFAR from 'Resnet in Resnet: Generalizing Residual Architectures,' https://arxiv.org/abs/1603.08029.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
final_block_channels : int
Number of output channels for the final unit.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
num_classes : int, default 10
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
final_block_channels,
in_channels=3,
in_size=(32, 32),
num_classes=10):
super(CIFARRiR, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = DualPathSequential(
return_two=False,
first_ordinals=0,
last_ordinals=0)
self.features.add_module("init_block", RiRInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = DualPathSequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), RiRUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_block", RiRFinalBlock())
in_channels = final_block_channels
self.output = nn.Sequential()
self.output.add_module('final_conv', conv1x1_block(
in_channels=in_channels,
out_channels=num_classes,
activation=None))
self.output.add_module('final_pool', nn.AvgPool2d(
kernel_size=8,
stride=1))
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = self.output(x)
x = x.view(x.size(0), -1)
return x
def get_rir_cifar(num_classes,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create RiR model for CIFAR with specific parameters.
Parameters:
----------
num_classes : int
Number of classification classes.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
channels = [[48, 48, 48, 48], [96, 96, 96, 96, 96, 96], [192, 192, 192, 192, 192, 192]]
init_block_channels = 48
final_block_channels = 384
net = CIFARRiR(
channels=channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
num_classes=num_classes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def rir_cifar10(num_classes=10, **kwargs):
"""
RiR model for CIFAR-10 from 'Resnet in Resnet: Generalizing Residual Architectures,'
https://arxiv.org/abs/1603.08029.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_rir_cifar(num_classes=num_classes, model_name="rir_cifar10", **kwargs)
def rir_cifar100(num_classes=100, **kwargs):
"""
RiR model for CIFAR-100 from 'Resnet in Resnet: Generalizing Residual Architectures,'
https://arxiv.org/abs/1603.08029.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_rir_cifar(num_classes=num_classes, model_name="rir_cifar100", **kwargs)
def rir_svhn(num_classes=10, **kwargs):
"""
RiR model for SVHN from 'Resnet in Resnet: Generalizing Residual Architectures,'
https://arxiv.org/abs/1603.08029.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_rir_cifar(num_classes=num_classes, model_name="rir_svhn", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
(rir_cifar10, 10),
(rir_cifar100, 100),
(rir_svhn, 10),
]
for model, num_classes in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != rir_cifar10 or weight_count == 9492980)
assert (model != rir_cifar100 or weight_count == 9527720)
assert (model != rir_svhn or weight_count == 9492980)
x = torch.randn(1, 3, 32, 32)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, num_classes))
if __name__ == "__main__":
_test()
| 10,658 | 29.454286 | 119 | py |
null | qimera-main/pytorchcv/models/ror_cifar.py | """
RoR-3 for CIFAR/SVHN, implemented in PyTorch.
Original paper: 'Residual Networks of Residual Networks: Multilevel Residual Networks,'
https://arxiv.org/abs/1608.02908.
"""
__all__ = ['CIFARRoR', 'ror3_56_cifar10', 'ror3_56_cifar100', 'ror3_56_svhn', 'ror3_110_cifar10', 'ror3_110_cifar100',
'ror3_110_svhn', 'ror3_164_cifar10', 'ror3_164_cifar100', 'ror3_164_svhn']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, conv3x3_block
class RoRBlock(nn.Module):
"""
RoR-3 block for residual path in residual unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
dropout_rate : float
Parameter of Dropout layer. Faction of the input units to drop.
"""
def __init__(self,
in_channels,
out_channels,
dropout_rate):
super(RoRBlock, self).__init__()
self.use_dropout = (dropout_rate != 0.0)
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels)
self.conv2 = conv3x3_block(
in_channels=out_channels,
out_channels=out_channels,
activation=None)
if self.use_dropout:
self.dropout = nn.Dropout(p=dropout_rate)
def forward(self, x):
x = self.conv1(x)
if self.use_dropout:
x = self.dropout(x)
x = self.conv2(x)
return x
class RoRResUnit(nn.Module):
"""
RoR-3 residual unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
dropout_rate : float
Parameter of Dropout layer. Faction of the input units to drop.
last_activate : bool, default True
Whether activate output.
"""
def __init__(self,
in_channels,
out_channels,
dropout_rate,
last_activate=True):
super(RoRResUnit, self).__init__()
self.last_activate = last_activate
self.resize_identity = (in_channels != out_channels)
self.body = RoRBlock(
in_channels=in_channels,
out_channels=out_channels,
dropout_rate=dropout_rate)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
activation=None)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = x + identity
if self.last_activate:
x = self.activ(x)
return x
class RoRResStage(nn.Module):
"""
RoR-3 residual stage.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels_list : list of int
Number of output channels for each unit.
dropout_rate : float
Parameter of Dropout layer. Faction of the input units to drop.
downsample : bool, default True
Whether downsample output.
"""
def __init__(self,
in_channels,
out_channels_list,
dropout_rate,
downsample=True):
super(RoRResStage, self).__init__()
self.downsample = downsample
self.shortcut = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels_list[-1],
activation=None)
self.units = nn.Sequential()
for i, out_channels in enumerate(out_channels_list):
last_activate = (i != len(out_channels_list) - 1)
self.units.add_module("unit{}".format(i + 1), RoRResUnit(
in_channels=in_channels,
out_channels=out_channels,
dropout_rate=dropout_rate,
last_activate=last_activate))
in_channels = out_channels
if self.downsample:
self.activ = nn.ReLU(inplace=True)
self.pool = nn.MaxPool2d(
kernel_size=2,
stride=2,
padding=0)
def forward(self, x):
identity = self.shortcut(x)
x = self.units(x)
x = x + identity
if self.downsample:
x = self.activ(x)
x = self.pool(x)
return x
class RoRResBody(nn.Module):
"""
RoR-3 residual body (main feature path).
Parameters:
----------
in_channels : int
Number of input channels.
out_channels_lists : list of list of int
Number of output channels for each stage.
dropout_rate : float
Parameter of Dropout layer. Faction of the input units to drop.
"""
def __init__(self,
in_channels,
out_channels_lists,
dropout_rate):
super(RoRResBody, self).__init__()
self.shortcut = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels_lists[-1][-1],
stride=4,
activation=None)
self.stages = nn.Sequential()
for i, channels_per_stage in enumerate(out_channels_lists):
downsample = (i != len(out_channels_lists) - 1)
self.stages.add_module("stage{}".format(i + 1), RoRResStage(
in_channels=in_channels,
out_channels_list=channels_per_stage,
dropout_rate=dropout_rate,
downsample=downsample))
in_channels = channels_per_stage[-1]
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
identity = self.shortcut(x)
x = self.stages(x)
x = x + identity
x = self.activ(x)
return x
class CIFARRoR(nn.Module):
"""
RoR-3 model for CIFAR from 'Residual Networks of Residual Networks: Multilevel Residual Networks,'
https://arxiv.org/abs/1608.02908.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
dropout_rate : float, default 0.0
Parameter of Dropout layer. Faction of the input units to drop.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
num_classes : int, default 10
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
dropout_rate=0.0,
in_channels=3,
in_size=(32, 32),
num_classes=10):
super(CIFARRoR, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
self.features.add_module("body", RoRResBody(
in_channels=in_channels,
out_channels_lists=channels,
dropout_rate=dropout_rate))
in_channels = channels[-1][-1]
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=8,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_ror_cifar(num_classes,
blocks,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create RoR-3 model for CIFAR with specific parameters.
Parameters:
----------
num_classes : int
Number of classification classes.
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
assert (num_classes in [10, 100])
assert ((blocks - 8) % 6 == 0)
layers = [(blocks - 8) // 6] * 3
channels_per_layers = [16, 32, 64]
init_block_channels = 16
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = CIFARRoR(
channels=channels,
init_block_channels=init_block_channels,
num_classes=num_classes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def ror3_56_cifar10(num_classes=10, **kwargs):
"""
RoR-3-56 model for CIFAR-10 from 'Residual Networks of Residual Networks: Multilevel Residual Networks,'
https://arxiv.org/abs/1608.02908.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_ror_cifar(num_classes=num_classes, blocks=56, model_name="ror3_56_cifar10", **kwargs)
def ror3_56_cifar100(num_classes=100, **kwargs):
"""
RoR-3-56 model for CIFAR-100 from 'Residual Networks of Residual Networks: Multilevel Residual Networks,'
https://arxiv.org/abs/1608.02908.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_ror_cifar(num_classes=num_classes, blocks=56, model_name="ror3_56_cifar100", **kwargs)
def ror3_56_svhn(num_classes=10, **kwargs):
"""
RoR-3-56 model for SVHN from 'Residual Networks of Residual Networks: Multilevel Residual Networks,'
https://arxiv.org/abs/1608.02908.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_ror_cifar(num_classes=num_classes, blocks=56, model_name="ror3_56_svhn", **kwargs)
def ror3_110_cifar10(num_classes=10, **kwargs):
"""
RoR-3-110 model for CIFAR-10 from 'Residual Networks of Residual Networks: Multilevel Residual Networks,'
https://arxiv.org/abs/1608.02908.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_ror_cifar(num_classes=num_classes, blocks=110, model_name="ror3_110_cifar10", **kwargs)
def ror3_110_cifar100(num_classes=100, **kwargs):
"""
RoR-3-110 model for CIFAR-100 from 'Residual Networks of Residual Networks: Multilevel Residual Networks,'
https://arxiv.org/abs/1608.02908.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_ror_cifar(num_classes=num_classes, blocks=110, model_name="ror3_110_cifar100", **kwargs)
def ror3_110_svhn(num_classes=10, **kwargs):
"""
RoR-3-110 model for SVHN from 'Residual Networks of Residual Networks: Multilevel Residual Networks,'
https://arxiv.org/abs/1608.02908.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_ror_cifar(num_classes=num_classes, blocks=110, model_name="ror3_110_svhn", **kwargs)
def ror3_164_cifar10(num_classes=10, **kwargs):
"""
RoR-3-164 model for CIFAR-10 from 'Residual Networks of Residual Networks: Multilevel Residual Networks,'
https://arxiv.org/abs/1608.02908.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_ror_cifar(num_classes=num_classes, blocks=164, model_name="ror3_164_cifar10", **kwargs)
def ror3_164_cifar100(num_classes=100, **kwargs):
"""
RoR-3-164 model for CIFAR-100 from 'Residual Networks of Residual Networks: Multilevel Residual Networks,'
https://arxiv.org/abs/1608.02908.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_ror_cifar(num_classes=num_classes, blocks=164, model_name="ror3_164_cifar100", **kwargs)
def ror3_164_svhn(num_classes=10, **kwargs):
"""
RoR-3-164 model for SVHN from 'Residual Networks of Residual Networks: Multilevel Residual Networks,'
https://arxiv.org/abs/1608.02908.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_ror_cifar(num_classes=num_classes, blocks=164, model_name="ror3_164_svhn", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
(ror3_56_cifar10, 10),
(ror3_56_cifar100, 100),
(ror3_56_svhn, 10),
(ror3_110_cifar10, 10),
(ror3_110_cifar100, 100),
(ror3_110_svhn, 10),
(ror3_164_cifar10, 10),
(ror3_164_cifar100, 100),
(ror3_164_svhn, 10),
]
for model, num_classes in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != ror3_56_cifar10 or weight_count == 762746)
assert (model != ror3_56_cifar100 or weight_count == 768596)
assert (model != ror3_56_svhn or weight_count == 762746)
assert (model != ror3_110_cifar10 or weight_count == 1637690)
assert (model != ror3_110_cifar100 or weight_count == 1643540)
assert (model != ror3_110_svhn or weight_count == 1637690)
assert (model != ror3_164_cifar10 or weight_count == 2512634)
assert (model != ror3_164_cifar100 or weight_count == 2518484)
assert (model != ror3_164_svhn or weight_count == 2512634)
x = torch.randn(1, 3, 32, 32)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, num_classes))
if __name__ == "__main__":
_test()
| 16,718 | 31.401163 | 118 | py |
null | qimera-main/pytorchcv/models/senet.py | """
SENet for ImageNet-1K, implemented in PyTorch.
Original paper: 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
"""
__all__ = ['SENet', 'senet16', 'senet28', 'senet40', 'senet52', 'senet103', 'senet154', 'SEInitBlock']
import os
import math
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, conv3x3_block, SEBlock
class SENetBottleneck(nn.Module):
"""
SENet bottleneck block for residual path in SENet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
"""
def __init__(self,
in_channels,
out_channels,
stride,
cardinality,
bottleneck_width):
super(SENetBottleneck, self).__init__()
mid_channels = out_channels // 4
D = int(math.floor(mid_channels * (bottleneck_width / 64.0)))
group_width = cardinality * D
group_width2 = group_width // 2
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=group_width2)
self.conv2 = conv3x3_block(
in_channels=group_width2,
out_channels=group_width,
stride=stride,
groups=cardinality)
self.conv3 = conv1x1_block(
in_channels=group_width,
out_channels=out_channels,
activation=None)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class SENetUnit(nn.Module):
"""
SENet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
identity_conv3x3 : bool, default False
Whether to use 3x3 convolution in the identity link.
"""
def __init__(self,
in_channels,
out_channels,
stride,
cardinality,
bottleneck_width,
identity_conv3x3):
super(SENetUnit, self).__init__()
self.resize_identity = (in_channels != out_channels) or (stride != 1)
self.body = SENetBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
cardinality=cardinality,
bottleneck_width=bottleneck_width)
self.se = SEBlock(channels=out_channels)
if self.resize_identity:
if identity_conv3x3:
self.identity_conv = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
activation=None)
else:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
activation=None)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = self.se(x)
x = x + identity
x = self.activ(x)
return x
class SEInitBlock(nn.Module):
"""
SENet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(SEInitBlock, self).__init__()
mid_channels = out_channels // 2
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=mid_channels,
stride=2)
self.conv2 = conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels)
self.conv3 = conv3x3_block(
in_channels=mid_channels,
out_channels=out_channels)
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=1)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.pool(x)
return x
class SENet(nn.Module):
"""
SENet model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
cardinality,
bottleneck_width,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(SENet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", SEInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
identity_conv3x3 = (i != 0)
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), SENetUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
identity_conv3x3=identity_conv3x3))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Sequential()
self.output.add_module("dropout", nn.Dropout(p=0.2))
self.output.add_module("fc", nn.Linear(
in_features=in_channels,
out_features=num_classes))
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_senet(blocks,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create SENet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 16:
layers = [1, 1, 1, 1]
cardinality = 32
elif blocks == 28:
layers = [2, 2, 2, 2]
cardinality = 32
elif blocks == 40:
layers = [3, 3, 3, 3]
cardinality = 32
elif blocks == 52:
layers = [3, 4, 6, 3]
cardinality = 32
elif blocks == 103:
layers = [3, 4, 23, 3]
cardinality = 32
elif blocks == 154:
layers = [3, 8, 36, 3]
cardinality = 64
else:
raise ValueError("Unsupported SENet with number of blocks: {}".format(blocks))
bottleneck_width = 4
init_block_channels = 128
channels_per_layers = [256, 512, 1024, 2048]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = SENet(
channels=channels,
init_block_channels=init_block_channels,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def senet16(**kwargs):
"""
SENet-16 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_senet(blocks=16, model_name="senet16", **kwargs)
def senet28(**kwargs):
"""
SENet-28 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_senet(blocks=28, model_name="senet28", **kwargs)
def senet40(**kwargs):
"""
SENet-40 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_senet(blocks=40, model_name="senet40", **kwargs)
def senet52(**kwargs):
"""
SENet-52 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_senet(blocks=52, model_name="senet52", **kwargs)
def senet103(**kwargs):
"""
SENet-103 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_senet(blocks=103, model_name="senet103", **kwargs)
def senet154(**kwargs):
"""
SENet-154 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_senet(blocks=154, model_name="senet154", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
senet16,
senet28,
senet40,
senet52,
senet103,
senet154,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != senet16 or weight_count == 31366168)
assert (model != senet28 or weight_count == 36453768)
assert (model != senet40 or weight_count == 41541368)
assert (model != senet52 or weight_count == 44659416)
assert (model != senet103 or weight_count == 60963096)
assert (model != senet154 or weight_count == 115088984)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 13,095 | 28.696145 | 115 | py |
null | qimera-main/pytorchcv/models/sepreresnet.py | """
SE-PreResNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
"""
__all__ = ['SEPreResNet', 'sepreresnet10', 'sepreresnet12', 'sepreresnet14', 'sepreresnet16', 'sepreresnet18',
'sepreresnet26', 'sepreresnetbc26b', 'sepreresnet34', 'sepreresnetbc38b', 'sepreresnet50', 'sepreresnet50b',
'sepreresnet101', 'sepreresnet101b', 'sepreresnet152', 'sepreresnet152b', 'sepreresnet200',
'sepreresnet200b', 'SEPreResUnit']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1, SEBlock
from .preresnet import PreResBlock, PreResBottleneck, PreResInitBlock, PreResActivation
class SEPreResUnit(nn.Module):
"""
SE-PreResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer of the block.
"""
def __init__(self,
in_channels,
out_channels,
stride,
bottleneck,
conv1_stride):
super(SEPreResUnit, self).__init__()
self.resize_identity = (in_channels != out_channels) or (stride != 1)
if bottleneck:
self.body = PreResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
conv1_stride=conv1_stride)
else:
self.body = PreResBlock(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
self.se = SEBlock(channels=out_channels)
if self.resize_identity:
self.identity_conv = conv1x1(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
def forward(self, x):
identity = x
x, x_pre_activ = self.body(x)
x = self.se(x)
if self.resize_identity:
identity = self.identity_conv(x_pre_activ)
x = x + identity
return x
class SEPreResNet(nn.Module):
"""
SE-PreResNet model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer in units.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
conv1_stride,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(SEPreResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", PreResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 1 if (i == 0) or (j != 0) else 2
stage.add_module("unit{}".format(j + 1), SEPreResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck,
conv1_stride=conv1_stride))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("post_activ", PreResActivation(in_channels=in_channels))
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_sepreresnet(blocks,
bottleneck=None,
conv1_stride=True,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create SE-PreResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
bottleneck : bool, default None
Whether to use a bottleneck or simple block in units.
conv1_stride : bool, default True
Whether to use stride in the first or the second convolution layer in units.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if bottleneck is None:
bottleneck = (blocks >= 50)
if blocks == 10:
layers = [1, 1, 1, 1]
elif blocks == 12:
layers = [2, 1, 1, 1]
elif blocks == 14 and not bottleneck:
layers = [2, 2, 1, 1]
elif (blocks == 14) and bottleneck:
layers = [1, 1, 1, 1]
elif blocks == 16:
layers = [2, 2, 2, 1]
elif blocks == 18:
layers = [2, 2, 2, 2]
elif (blocks == 26) and not bottleneck:
layers = [3, 3, 3, 3]
elif (blocks == 26) and bottleneck:
layers = [2, 2, 2, 2]
elif blocks == 34:
layers = [3, 4, 6, 3]
elif (blocks == 38) and bottleneck:
layers = [3, 3, 3, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
elif blocks == 200:
layers = [3, 24, 36, 3]
elif blocks == 269:
layers = [3, 30, 48, 8]
else:
raise ValueError("Unsupported SE-PreResNet with number of blocks: {}".format(blocks))
if bottleneck:
assert (sum(layers) * 3 + 2 == blocks)
else:
assert (sum(layers) * 2 + 2 == blocks)
init_block_channels = 64
channels_per_layers = [64, 128, 256, 512]
if bottleneck:
bottleneck_factor = 4
channels_per_layers = [ci * bottleneck_factor for ci in channels_per_layers]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = SEPreResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def sepreresnet10(**kwargs):
"""
SE-PreResNet-10 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=10, model_name="sepreresnet10", **kwargs)
def sepreresnet12(**kwargs):
"""
SE-PreResNet-12 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=12, model_name="sepreresnet12", **kwargs)
def sepreresnet14(**kwargs):
"""
SE-PreResNet-14 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=14, model_name="sepreresnet14", **kwargs)
def sepreresnet16(**kwargs):
"""
SE-PreResNet-16 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=16, model_name="sepreresnet16", **kwargs)
def sepreresnet18(**kwargs):
"""
SE-PreResNet-18 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=18, model_name="sepreresnet18", **kwargs)
def sepreresnet26(**kwargs):
"""
SE-PreResNet-26 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=26, bottleneck=False, model_name="sepreresnet26", **kwargs)
def sepreresnetbc26b(**kwargs):
"""
SE-PreResNet-BC-26b model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=26, bottleneck=True, conv1_stride=False, model_name="sepreresnetbc26b", **kwargs)
def sepreresnet34(**kwargs):
"""
SE-PreResNet-34 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=34, model_name="sepreresnet34", **kwargs)
def sepreresnetbc38b(**kwargs):
"""
SE-PreResNet-BC-38b model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=38, bottleneck=True, conv1_stride=False, model_name="sepreresnetbc38b", **kwargs)
def sepreresnet50(**kwargs):
"""
SE-PreResNet-50 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=50, model_name="sepreresnet50", **kwargs)
def sepreresnet50b(**kwargs):
"""
SE-PreResNet-50 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation
Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=50, conv1_stride=False, model_name="sepreresnet50b", **kwargs)
def sepreresnet101(**kwargs):
"""
SE-PreResNet-101 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=101, model_name="sepreresnet101", **kwargs)
def sepreresnet101b(**kwargs):
"""
SE-PreResNet-101 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation
Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=101, conv1_stride=False, model_name="sepreresnet101b", **kwargs)
def sepreresnet152(**kwargs):
"""
SE-PreResNet-152 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=152, model_name="sepreresnet152", **kwargs)
def sepreresnet152b(**kwargs):
"""
SE-PreResNet-152 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation
Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=152, conv1_stride=False, model_name="sepreresnet152b", **kwargs)
def sepreresnet200(**kwargs):
"""
SE-PreResNet-200 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. It's an
experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=200, model_name="sepreresnet200", **kwargs)
def sepreresnet200b(**kwargs):
"""
SE-PreResNet-200 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation
Networks,' https://arxiv.org/abs/1709.01507. It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=200, conv1_stride=False, model_name="sepreresnet200b", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
sepreresnet10,
sepreresnet12,
sepreresnet14,
sepreresnet16,
sepreresnet18,
sepreresnet26,
sepreresnetbc26b,
sepreresnet34,
sepreresnetbc38b,
sepreresnet50,
sepreresnet50b,
sepreresnet101,
sepreresnet101b,
sepreresnet152,
sepreresnet152b,
sepreresnet200,
sepreresnet200b,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != sepreresnet10 or weight_count == 5461668)
assert (model != sepreresnet12 or weight_count == 5536232)
assert (model != sepreresnet14 or weight_count == 5833840)
assert (model != sepreresnet16 or weight_count == 7022976)
assert (model != sepreresnet18 or weight_count == 11776928)
assert (model != sepreresnet26 or weight_count == 18092188)
assert (model != sepreresnetbc26b or weight_count == 17388424)
assert (model != sepreresnet34 or weight_count == 21957204)
assert (model != sepreresnetbc38b or weight_count == 24019064)
assert (model != sepreresnet50 or weight_count == 28080472)
assert (model != sepreresnet50b or weight_count == 28080472)
assert (model != sepreresnet101 or weight_count == 49319320)
assert (model != sepreresnet101b or weight_count == 49319320)
assert (model != sepreresnet152 or weight_count == 66814296)
assert (model != sepreresnet152b or weight_count == 66814296)
assert (model != sepreresnet200 or weight_count == 71828312)
assert (model != sepreresnet200b or weight_count == 71828312)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 18,420 | 32.371377 | 119 | py |
null | qimera-main/pytorchcv/models/sepreresnet_cifar.py | """
SE-PreResNet for CIFAR/SVHN, implemented in PyTorch.
Original paper: 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
"""
__all__ = ['CIFARSEPreResNet', 'sepreresnet20_cifar10', 'sepreresnet20_cifar100', 'sepreresnet20_svhn',
'sepreresnet56_cifar10', 'sepreresnet56_cifar100', 'sepreresnet56_svhn',
'sepreresnet110_cifar10', 'sepreresnet110_cifar100', 'sepreresnet110_svhn',
'sepreresnet164bn_cifar10', 'sepreresnet164bn_cifar100', 'sepreresnet164bn_svhn',
'sepreresnet272bn_cifar10', 'sepreresnet272bn_cifar100', 'sepreresnet272bn_svhn',
'sepreresnet542bn_cifar10', 'sepreresnet542bn_cifar100', 'sepreresnet542bn_svhn',
'sepreresnet1001_cifar10', 'sepreresnet1001_cifar100', 'sepreresnet1001_svhn',
'sepreresnet1202_cifar10', 'sepreresnet1202_cifar100', 'sepreresnet1202_svhn']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv3x3_block
from .sepreresnet import SEPreResUnit
class CIFARSEPreResNet(nn.Module):
"""
SE-PreResNet model for CIFAR from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
num_classes : int, default 10
Number of classification num_classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
in_channels=3,
in_size=(32, 32),
num_classes=10):
super(CIFARSEPreResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), SEPreResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck,
conv1_stride=False))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=8,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_sepreresnet_cifar(num_classes,
blocks,
bottleneck,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create SE-PreResNet model for CIFAR with specific parameters.
Parameters:
----------
num_classes : int
Number of classification num_classes.
blocks : int
Number of blocks.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
assert (num_classes in [10, 100])
if bottleneck:
assert ((blocks - 2) % 9 == 0)
layers = [(blocks - 2) // 9] * 3
else:
assert ((blocks - 2) % 6 == 0)
layers = [(blocks - 2) // 6] * 3
channels_per_layers = [16, 32, 64]
init_block_channels = 16
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if bottleneck:
channels = [[cij * 4 for cij in ci] for ci in channels]
net = CIFARSEPreResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
num_classes=num_classes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def sepreresnet20_cifar10(num_classes=10, **kwargs):
"""
SE-PreResNet-20 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=20, bottleneck=False,
model_name="sepreresnet20_cifar10", **kwargs)
def sepreresnet20_cifar100(num_classes=100, **kwargs):
"""
SE-PreResNet-20 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 100
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=20, bottleneck=False,
model_name="sepreresnet20_cifar100", **kwargs)
def sepreresnet20_svhn(num_classes=10, **kwargs):
"""
SE-PreResNet-20 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=20, bottleneck=False, model_name="sepreresnet20_svhn",
**kwargs)
def sepreresnet56_cifar10(num_classes=10, **kwargs):
"""
SE-PreResNet-56 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=56, bottleneck=False,
model_name="sepreresnet56_cifar10", **kwargs)
def sepreresnet56_cifar100(num_classes=100, **kwargs):
"""
SE-PreResNet-56 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 100
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=56, bottleneck=False,
model_name="sepreresnet56_cifar100", **kwargs)
def sepreresnet56_svhn(num_classes=10, **kwargs):
"""
SE-PreResNet-56 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=56, bottleneck=False, model_name="sepreresnet56_svhn",
**kwargs)
def sepreresnet110_cifar10(num_classes=10, **kwargs):
"""
SE-PreResNet-110 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=110, bottleneck=False,
model_name="sepreresnet110_cifar10", **kwargs)
def sepreresnet110_cifar100(num_classes=100, **kwargs):
"""
SE-PreResNet-110 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 100
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=110, bottleneck=False,
model_name="sepreresnet110_cifar100", **kwargs)
def sepreresnet110_svhn(num_classes=10, **kwargs):
"""
SE-PreResNet-110 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=110, bottleneck=False,
model_name="sepreresnet110_svhn", **kwargs)
def sepreresnet164bn_cifar10(num_classes=10, **kwargs):
"""
SE-PreResNet-164(BN) model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=164, bottleneck=True,
model_name="sepreresnet164bn_cifar10", **kwargs)
def sepreresnet164bn_cifar100(num_classes=100, **kwargs):
"""
SE-PreResNet-164(BN) model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 100
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=164, bottleneck=True,
model_name="sepreresnet164bn_cifar100", **kwargs)
def sepreresnet164bn_svhn(num_classes=10, **kwargs):
"""
SE-PreResNet-164(BN) model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=164, bottleneck=True,
model_name="sepreresnet164bn_svhn", **kwargs)
def sepreresnet272bn_cifar10(num_classes=10, **kwargs):
"""
SE-PreResNet-272(BN) model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=272, bottleneck=True,
model_name="sepreresnet272bn_cifar10", **kwargs)
def sepreresnet272bn_cifar100(num_classes=100, **kwargs):
"""
SE-PreResNet-272(BN) model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 100
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=272, bottleneck=True,
model_name="sepreresnet272bn_cifar100", **kwargs)
def sepreresnet272bn_svhn(num_classes=10, **kwargs):
"""
SE-PreResNet-272(BN) model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=272, bottleneck=True,
model_name="sepreresnet272bn_svhn", **kwargs)
def sepreresnet542bn_cifar10(num_classes=10, **kwargs):
"""
SE-PreResNet-542(BN) model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=542, bottleneck=True,
model_name="sepreresnet542bn_cifar10", **kwargs)
def sepreresnet542bn_cifar100(num_classes=100, **kwargs):
"""
SE-PreResNet-542(BN) model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 100
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=542, bottleneck=True,
model_name="sepreresnet542bn_cifar100", **kwargs)
def sepreresnet542bn_svhn(num_classes=10, **kwargs):
"""
SE-PreResNet-542(BN) model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=542, bottleneck=True,
model_name="sepreresnet542bn_svhn", **kwargs)
def sepreresnet1001_cifar10(num_classes=10, **kwargs):
"""
SE-PreResNet-1001 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=1001, bottleneck=True,
model_name="sepreresnet1001_cifar10", **kwargs)
def sepreresnet1001_cifar100(num_classes=100, **kwargs):
"""
SE-PreResNet-1001 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 100
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=1001, bottleneck=True,
model_name="sepreresnet1001_cifar100", **kwargs)
def sepreresnet1001_svhn(num_classes=10, **kwargs):
"""
SE-PreResNet-1001 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=1001, bottleneck=True,
model_name="sepreresnet1001_svhn", **kwargs)
def sepreresnet1202_cifar10(num_classes=10, **kwargs):
"""
SE-PreResNet-1202 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=1202, bottleneck=False,
model_name="sepreresnet1202_cifar10", **kwargs)
def sepreresnet1202_cifar100(num_classes=100, **kwargs):
"""
SE-PreResNet-1202 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 100
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=1202, bottleneck=False,
model_name="sepreresnet1202_cifar100", **kwargs)
def sepreresnet1202_svhn(num_classes=10, **kwargs):
"""
SE-PreResNet-1202 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sepreresnet_cifar(num_classes=num_classes, blocks=1202, bottleneck=False,
model_name="sepreresnet1202_svhn", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
(sepreresnet20_cifar10, 10),
(sepreresnet20_cifar100, 100),
(sepreresnet20_svhn, 10),
(sepreresnet56_cifar10, 10),
(sepreresnet56_cifar100, 100),
(sepreresnet56_svhn, 10),
(sepreresnet110_cifar10, 10),
(sepreresnet110_cifar100, 100),
(sepreresnet110_svhn, 10),
(sepreresnet164bn_cifar10, 10),
(sepreresnet164bn_cifar100, 100),
(sepreresnet164bn_svhn, 10),
(sepreresnet272bn_cifar10, 10),
(sepreresnet272bn_cifar100, 100),
(sepreresnet272bn_svhn, 10),
(sepreresnet542bn_cifar10, 10),
(sepreresnet542bn_cifar100, 100),
(sepreresnet542bn_svhn, 10),
(sepreresnet1001_cifar10, 10),
(sepreresnet1001_cifar100, 100),
(sepreresnet1001_svhn, 10),
(sepreresnet1202_cifar10, 10),
(sepreresnet1202_cifar100, 100),
(sepreresnet1202_svhn, 10),
]
for model, num_num_classes in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != sepreresnet20_cifar10 or weight_count == 274559)
assert (model != sepreresnet20_cifar100 or weight_count == 280409)
assert (model != sepreresnet20_svhn or weight_count == 274559)
assert (model != sepreresnet56_cifar10 or weight_count == 862601)
assert (model != sepreresnet56_cifar100 or weight_count == 868451)
assert (model != sepreresnet56_svhn or weight_count == 862601)
assert (model != sepreresnet110_cifar10 or weight_count == 1744664)
assert (model != sepreresnet110_cifar100 or weight_count == 1750514)
assert (model != sepreresnet110_svhn or weight_count == 1744664)
assert (model != sepreresnet164bn_cifar10 or weight_count == 1904882)
assert (model != sepreresnet164bn_cifar100 or weight_count == 1928012)
assert (model != sepreresnet164bn_svhn or weight_count == 1904882)
assert (model != sepreresnet272bn_cifar10 or weight_count == 3152450)
assert (model != sepreresnet272bn_cifar100 or weight_count == 3175580)
assert (model != sepreresnet272bn_svhn or weight_count == 3152450)
assert (model != sepreresnet542bn_cifar10 or weight_count == 6271370)
assert (model != sepreresnet542bn_cifar100 or weight_count == 6294500)
assert (model != sepreresnet542bn_svhn or weight_count == 6271370)
assert (model != sepreresnet1001_cifar10 or weight_count == 11573534)
assert (model != sepreresnet1001_cifar100 or weight_count == 11596664)
assert (model != sepreresnet1001_svhn or weight_count == 11573534)
assert (model != sepreresnet1202_cifar10 or weight_count == 19581938)
assert (model != sepreresnet1202_cifar100 or weight_count == 19587788)
assert (model != sepreresnet1202_svhn or weight_count == 19581938)
x = torch.randn(1, 3, 32, 32)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, num_num_classes))
if __name__ == "__main__":
_test()
| 24,663 | 37.298137 | 119 | py |
null | qimera-main/pytorchcv/models/seresnet.py | """
SE-ResNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
"""
__all__ = ['SEResNet', 'seresnet10', 'seresnet12', 'seresnet14', 'seresnet16', 'seresnet18', 'seresnet26',
'seresnetbc26b', 'seresnet34', 'seresnetbc38b', 'seresnet50', 'seresnet50b', 'seresnet101', 'seresnet101b',
'seresnet152', 'seresnet152b', 'seresnet200', 'seresnet200b', 'SEResUnit', 'get_seresnet']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, SEBlock
from .resnet import ResBlock, ResBottleneck, ResInitBlock
class SEResUnit(nn.Module):
"""
SE-ResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer of the block.
"""
def __init__(self,
in_channels,
out_channels,
stride,
bottleneck,
conv1_stride):
super(SEResUnit, self).__init__()
self.resize_identity = (in_channels != out_channels) or (stride != 1)
if bottleneck:
self.body = ResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
conv1_stride=conv1_stride)
else:
self.body = ResBlock(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
self.se = SEBlock(channels=out_channels)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
activation=None)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = self.se(x)
x = x + identity
x = self.activ(x)
return x
class SEResNet(nn.Module):
"""
SE-ResNet model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer in units.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
conv1_stride,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(SEResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), SEResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck,
conv1_stride=conv1_stride))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_seresnet(blocks,
bottleneck=None,
conv1_stride=True,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create SE-ResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
bottleneck : bool, default None
Whether to use a bottleneck or simple block in units.
conv1_stride : bool, default True
Whether to use stride in the first or the second convolution layer in units.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if bottleneck is None:
bottleneck = (blocks >= 50)
if blocks == 10:
layers = [1, 1, 1, 1]
elif blocks == 12:
layers = [2, 1, 1, 1]
elif blocks == 14 and not bottleneck:
layers = [2, 2, 1, 1]
elif (blocks == 14) and bottleneck:
layers = [1, 1, 1, 1]
elif blocks == 16:
layers = [2, 2, 2, 1]
elif blocks == 18:
layers = [2, 2, 2, 2]
elif (blocks == 26) and not bottleneck:
layers = [3, 3, 3, 3]
elif (blocks == 26) and bottleneck:
layers = [2, 2, 2, 2]
elif blocks == 34:
layers = [3, 4, 6, 3]
elif (blocks == 38) and bottleneck:
layers = [3, 3, 3, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
elif blocks == 200:
layers = [3, 24, 36, 3]
else:
raise ValueError("Unsupported SE-ResNet with number of blocks: {}".format(blocks))
if bottleneck:
assert (sum(layers) * 3 + 2 == blocks)
else:
assert (sum(layers) * 2 + 2 == blocks)
init_block_channels = 64
channels_per_layers = [64, 128, 256, 512]
if bottleneck:
bottleneck_factor = 4
channels_per_layers = [ci * bottleneck_factor for ci in channels_per_layers]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = SEResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def seresnet10(**kwargs):
"""
SE-ResNet-10 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(blocks=10, model_name="seresnet10", **kwargs)
def seresnet12(**kwargs):
"""
SE-ResNet-12 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(blocks=12, model_name="seresnet12", **kwargs)
def seresnet14(**kwargs):
"""
SE-ResNet-14 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(blocks=14, model_name="seresnet14", **kwargs)
def seresnet16(**kwargs):
"""
SE-ResNet-16 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(blocks=16, model_name="seresnet16", **kwargs)
def seresnet18(**kwargs):
"""
SE-ResNet-18 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(blocks=18, model_name="seresnet18", **kwargs)
def seresnet26(**kwargs):
"""
SE-ResNet-26 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(blocks=26, bottleneck=False, model_name="seresnet26", **kwargs)
def seresnetbc26b(**kwargs):
"""
SE-ResNet-BC-26b model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
It's an experimental model (bottleneck compressed).
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(blocks=26, bottleneck=True, conv1_stride=False, model_name="seresnetbc26b", **kwargs)
def seresnet34(**kwargs):
"""
SE-ResNet-34 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(blocks=34, model_name="seresnet34", **kwargs)
def seresnetbc38b(**kwargs):
"""
SE-ResNet-BC-38b model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
It's an experimental model (bottleneck compressed).
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(blocks=38, bottleneck=True, conv1_stride=False, model_name="seresnetbc38b", **kwargs)
def seresnet50(**kwargs):
"""
SE-ResNet-50 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(blocks=50, model_name="seresnet50", **kwargs)
def seresnet50b(**kwargs):
"""
SE-ResNet-50 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation
Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(blocks=50, conv1_stride=False, model_name="seresnet50b", **kwargs)
def seresnet101(**kwargs):
"""
SE-ResNet-101 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(blocks=101, model_name="seresnet101", **kwargs)
def seresnet101b(**kwargs):
"""
SE-ResNet-101 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation
Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(blocks=101, conv1_stride=False, model_name="seresnet101b", **kwargs)
def seresnet152(**kwargs):
"""
SE-ResNet-152 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(blocks=152, model_name="seresnet152", **kwargs)
def seresnet152b(**kwargs):
"""
SE-ResNet-152 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation
Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(blocks=152, conv1_stride=False, model_name="seresnet152b", **kwargs)
def seresnet200(**kwargs):
"""
SE-ResNet-200 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(blocks=200, model_name="seresnet200", **kwargs)
def seresnet200b(**kwargs):
"""
SE-ResNet-200 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation
Networks,' https://arxiv.org/abs/1709.01507. It's an experimental model.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(blocks=200, conv1_stride=False, model_name="seresnet200b", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
seresnet10,
seresnet12,
seresnet14,
seresnet16,
seresnet18,
seresnet26,
seresnetbc26b,
seresnet34,
seresnetbc38b,
seresnet50,
seresnet50b,
seresnet101,
seresnet101b,
seresnet152,
seresnet152b,
seresnet200,
seresnet200b,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != seresnet10 or weight_count == 5463332)
assert (model != seresnet12 or weight_count == 5537896)
assert (model != seresnet14 or weight_count == 5835504)
assert (model != seresnet16 or weight_count == 7024640)
assert (model != seresnet18 or weight_count == 11778592)
assert (model != seresnet26 or weight_count == 18093852)
assert (model != seresnetbc26b or weight_count == 17395976)
assert (model != seresnet34 or weight_count == 21958868)
assert (model != seresnetbc38b or weight_count == 24026616)
assert (model != seresnet50 or weight_count == 28088024)
assert (model != seresnet50b or weight_count == 28088024)
assert (model != seresnet101 or weight_count == 49326872)
assert (model != seresnet101b or weight_count == 49326872)
assert (model != seresnet152 or weight_count == 66821848)
assert (model != seresnet152b or weight_count == 66821848)
assert (model != seresnet200 or weight_count == 71835864)
assert (model != seresnet200b or weight_count == 71835864)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 18,211 | 31.579606 | 118 | py |
null | qimera-main/pytorchcv/models/seresnet_cifar.py | """
SE-ResNet for CIFAR/SVHN, implemented in PyTorch.
Original paper: 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
"""
__all__ = ['CIFARSEResNet', 'seresnet20_cifar10', 'seresnet20_cifar100', 'seresnet20_svhn',
'seresnet56_cifar10', 'seresnet56_cifar100', 'seresnet56_svhn',
'seresnet110_cifar10', 'seresnet110_cifar100', 'seresnet110_svhn',
'seresnet164bn_cifar10', 'seresnet164bn_cifar100', 'seresnet164bn_svhn',
'seresnet272bn_cifar10', 'seresnet272bn_cifar100', 'seresnet272bn_svhn',
'seresnet542bn_cifar10', 'seresnet542bn_cifar100', 'seresnet542bn_svhn',
'seresnet1001_cifar10', 'seresnet1001_cifar100', 'seresnet1001_svhn',
'seresnet1202_cifar10', 'seresnet1202_cifar100', 'seresnet1202_svhn']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv3x3_block
from .seresnet import SEResUnit
class CIFARSEResNet(nn.Module):
"""
SE-ResNet model for CIFAR from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
num_classes : int, default 10
Number of classification num_classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
in_channels=3,
in_size=(32, 32),
num_classes=10):
super(CIFARSEResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), SEResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck,
conv1_stride=False))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=8,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_seresnet_cifar(num_classes,
blocks,
bottleneck,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create SE-ResNet model for CIFAR with specific parameters.
Parameters:
----------
num_classes : int
Number of classification num_classes.
blocks : int
Number of blocks.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
assert (num_classes in [10, 100])
if bottleneck:
assert ((blocks - 2) % 9 == 0)
layers = [(blocks - 2) // 9] * 3
else:
assert ((blocks - 2) % 6 == 0)
layers = [(blocks - 2) // 6] * 3
channels_per_layers = [16, 32, 64]
init_block_channels = 16
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if bottleneck:
channels = [[cij * 4 for cij in ci] for ci in channels]
net = CIFARSEResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
num_classes=num_classes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def seresnet20_cifar10(num_classes=10, **kwargs):
"""
SE-ResNet-20 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=20, bottleneck=False, model_name="seresnet20_cifar10",
**kwargs)
def seresnet20_cifar100(num_classes=100, **kwargs):
"""
SE-ResNet-20 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 100
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=20, bottleneck=False, model_name="seresnet20_cifar100",
**kwargs)
def seresnet20_svhn(num_classes=10, **kwargs):
"""
SE-ResNet-20 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=20, bottleneck=False, model_name="seresnet20_svhn",
**kwargs)
def seresnet56_cifar10(num_classes=10, **kwargs):
"""
SE-ResNet-56 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=56, bottleneck=False, model_name="seresnet56_cifar10",
**kwargs)
def seresnet56_cifar100(num_classes=100, **kwargs):
"""
SE-ResNet-56 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 100
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=56, bottleneck=False, model_name="seresnet56_cifar100",
**kwargs)
def seresnet56_svhn(num_classes=10, **kwargs):
"""
SE-ResNet-56 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=56, bottleneck=False, model_name="seresnet56_svhn",
**kwargs)
def seresnet110_cifar10(num_classes=10, **kwargs):
"""
SE-ResNet-110 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=110, bottleneck=False, model_name="seresnet110_cifar10",
**kwargs)
def seresnet110_cifar100(num_classes=100, **kwargs):
"""
SE-ResNet-110 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 100
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=110, bottleneck=False, model_name="seresnet110_cifar100",
**kwargs)
def seresnet110_svhn(num_classes=10, **kwargs):
"""
SE-ResNet-110 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=110, bottleneck=False, model_name="seresnet110_svhn",
**kwargs)
def seresnet164bn_cifar10(num_classes=10, **kwargs):
"""
SE-ResNet-164(BN) model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=164, bottleneck=True, model_name="seresnet164bn_cifar10",
**kwargs)
def seresnet164bn_cifar100(num_classes=100, **kwargs):
"""
SE-ResNet-164(BN) model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 100
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=164, bottleneck=True, model_name="seresnet164bn_cifar100",
**kwargs)
def seresnet164bn_svhn(num_classes=10, **kwargs):
"""
SE-ResNet-164(BN) model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=164, bottleneck=True, model_name="seresnet164bn_svhn",
**kwargs)
def seresnet272bn_cifar10(num_classes=10, **kwargs):
"""
SE-ResNet-272(BN) model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=272, bottleneck=True, model_name="seresnet272bn_cifar10",
**kwargs)
def seresnet272bn_cifar100(num_classes=100, **kwargs):
"""
SE-ResNet-272(BN) model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 100
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=272, bottleneck=True, model_name="seresnet272bn_cifar100",
**kwargs)
def seresnet272bn_svhn(num_classes=10, **kwargs):
"""
SE-ResNet-272(BN) model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=272, bottleneck=True, model_name="seresnet272bn_svhn",
**kwargs)
def seresnet542bn_cifar10(num_classes=10, **kwargs):
"""
SE-ResNet-542(BN) model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=542, bottleneck=True, model_name="seresnet542bn_cifar10",
**kwargs)
def seresnet542bn_cifar100(num_classes=100, **kwargs):
"""
SE-ResNet-542(BN) model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 100
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=542, bottleneck=True, model_name="seresnet542bn_cifar100",
**kwargs)
def seresnet542bn_svhn(num_classes=10, **kwargs):
"""
SE-ResNet-542(BN) model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=542, bottleneck=True, model_name="seresnet542bn_svhn",
**kwargs)
def seresnet1001_cifar10(num_classes=10, **kwargs):
"""
SE-ResNet-1001 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=1001, bottleneck=True, model_name="seresnet1001_cifar10",
**kwargs)
def seresnet1001_cifar100(num_classes=100, **kwargs):
"""
SE-ResNet-1001 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 100
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=1001, bottleneck=True, model_name="seresnet1001_cifar100",
**kwargs)
def seresnet1001_svhn(num_classes=10, **kwargs):
"""
SE-ResNet-1001 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=1001, bottleneck=True, model_name="seresnet1001_svhn",
**kwargs)
def seresnet1202_cifar10(num_classes=10, **kwargs):
"""
SE-ResNet-1202 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=1202, bottleneck=False, model_name="seresnet1202_cifar10",
**kwargs)
def seresnet1202_cifar100(num_classes=100, **kwargs):
"""
SE-ResNet-1202 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 100
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=1202, bottleneck=False,
model_name="seresnet1202_cifar100", **kwargs)
def seresnet1202_svhn(num_classes=10, **kwargs):
"""
SE-ResNet-1202 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 10
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet_cifar(num_classes=num_classes, blocks=1202, bottleneck=False, model_name="seresnet1202_svhn",
**kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
(seresnet20_cifar10, 10),
(seresnet20_cifar100, 100),
(seresnet20_svhn, 10),
(seresnet56_cifar10, 10),
(seresnet56_cifar100, 100),
(seresnet56_svhn, 10),
(seresnet110_cifar10, 10),
(seresnet110_cifar100, 100),
(seresnet110_svhn, 10),
(seresnet164bn_cifar10, 10),
(seresnet164bn_cifar100, 100),
(seresnet164bn_svhn, 10),
(seresnet272bn_cifar10, 10),
(seresnet272bn_cifar100, 100),
(seresnet272bn_svhn, 10),
(seresnet542bn_cifar10, 10),
(seresnet542bn_cifar100, 100),
(seresnet542bn_svhn, 10),
(seresnet1001_cifar10, 10),
(seresnet1001_cifar100, 100),
(seresnet1001_svhn, 10),
(seresnet1202_cifar10, 10),
(seresnet1202_cifar100, 100),
(seresnet1202_svhn, 10),
]
for model, num_num_classes in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != seresnet20_cifar10 or weight_count == 274847)
assert (model != seresnet20_cifar100 or weight_count == 280697)
assert (model != seresnet20_svhn or weight_count == 274847)
assert (model != seresnet56_cifar10 or weight_count == 862889)
assert (model != seresnet56_cifar100 or weight_count == 868739)
assert (model != seresnet56_svhn or weight_count == 862889)
assert (model != seresnet110_cifar10 or weight_count == 1744952)
assert (model != seresnet110_cifar100 or weight_count == 1750802)
assert (model != seresnet110_svhn or weight_count == 1744952)
assert (model != seresnet164bn_cifar10 or weight_count == 1906258)
assert (model != seresnet164bn_cifar100 or weight_count == 1929388)
assert (model != seresnet164bn_svhn or weight_count == 1906258)
assert (model != seresnet272bn_cifar10 or weight_count == 3153826)
assert (model != seresnet272bn_cifar100 or weight_count == 3176956)
assert (model != seresnet272bn_svhn or weight_count == 3153826)
assert (model != seresnet542bn_cifar10 or weight_count == 6272746)
assert (model != seresnet542bn_cifar100 or weight_count == 6295876)
assert (model != seresnet542bn_svhn or weight_count == 6272746)
assert (model != seresnet1001_cifar10 or weight_count == 11574910)
assert (model != seresnet1001_cifar100 or weight_count == 11598040)
assert (model != seresnet1001_svhn or weight_count == 11574910)
assert (model != seresnet1202_cifar10 or weight_count == 19582226)
assert (model != seresnet1202_cifar100 or weight_count == 19588076)
assert (model != seresnet1202_svhn or weight_count == 19582226)
x = torch.randn(1, 3, 32, 32)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, num_num_classes))
if __name__ == "__main__":
_test()
| 24,036 | 36.324534 | 120 | py |
null | qimera-main/pytorchcv/models/seresnet_cub.py | """
SE-ResNet for CUB-200-2011, implemented in PyTorch.
Original paper: 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
"""
__all__ = ['seresnet10_cub', 'seresnet12_cub', 'seresnet14_cub', 'seresnetbc14b_cub', 'seresnet16_cub',
'seresnet18_cub', 'seresnet26_cub', 'seresnetbc26b_cub', 'seresnet34_cub', 'seresnetbc38b_cub',
'seresnet50_cub', 'seresnet50b_cub', 'seresnet101_cub', 'seresnet101b_cub', 'seresnet152_cub',
'seresnet152b_cub', 'seresnet200_cub', 'seresnet200b_cub']
from .seresnet import get_seresnet
def seresnet10_cub(num_classes=200, **kwargs):
"""
SE-ResNet-10 model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
It's an experimental model.
Parameters:
----------
num_classes : int, default 200
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(num_classes=num_classes, blocks=10, model_name="seresnet10_cub", **kwargs)
def seresnet12_cub(num_classes=200, **kwargs):
"""
SE-ResNet-12 model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
It's an experimental model.
Parameters:
----------
num_classes : int, default 200
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(num_classes=num_classes, blocks=12, model_name="seresnet12_cub", **kwargs)
def seresnet14_cub(num_classes=200, **kwargs):
"""
SE-ResNet-14 model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
It's an experimental model.
Parameters:
----------
num_classes : int, default 200
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(num_classes=num_classes, blocks=14, model_name="seresnet14_cub", **kwargs)
def seresnetbc14b_cub(num_classes=200, **kwargs):
"""
SE-ResNet-BC-14b model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
It's an experimental model (bottleneck compressed).
Parameters:
----------
num_classes : int, default 200
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(num_classes=num_classes, blocks=14, bottleneck=True, conv1_stride=False,
model_name="seresnetbc14b_cub", **kwargs)
def seresnet16_cub(num_classes=200, **kwargs):
"""
SE-ResNet-16 model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
It's an experimental model.
Parameters:
----------
num_classes : int, default 200
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(num_classes=num_classes, blocks=16, model_name="seresnet16_cub", **kwargs)
def seresnet18_cub(num_classes=200, **kwargs):
"""
SE-ResNet-18 model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 200
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(num_classes=num_classes, blocks=18, model_name="seresnet18_cub", **kwargs)
def seresnet26_cub(num_classes=200, **kwargs):
"""
SE-ResNet-26 model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
It's an experimental model.
Parameters:
----------
num_classes : int, default 200
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(num_classes=num_classes, blocks=26, bottleneck=False, model_name="seresnet26_cub", **kwargs)
def seresnetbc26b_cub(num_classes=200, **kwargs):
"""
SE-ResNet-BC-26b model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
It's an experimental model (bottleneck compressed).
Parameters:
----------
num_classes : int, default 200
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(num_classes=num_classes, blocks=26, bottleneck=True, conv1_stride=False,
model_name="seresnetbc26b_cub", **kwargs)
def seresnet34_cub(num_classes=200, **kwargs):
"""
SE-ResNet-34 model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 200
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(num_classes=num_classes, blocks=34, model_name="seresnet34_cub", **kwargs)
def seresnetbc38b_cub(num_classes=200, **kwargs):
"""
SE-ResNet-BC-38b model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
It's an experimental model (bottleneck compressed).
Parameters:
----------
num_classes : int, default 200
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(num_classes=num_classes, blocks=38, bottleneck=True, conv1_stride=False,
model_name="seresnetbc38b_cub", **kwargs)
def seresnet50_cub(num_classes=200, **kwargs):
"""
SE-ResNet-50 model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 200
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(num_classes=num_classes, blocks=50, model_name="seresnet50_cub", **kwargs)
def seresnet50b_cub(num_classes=200, **kwargs):
"""
SE-ResNet-50 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation Networks,'
https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 200
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(num_classes=num_classes, blocks=50, conv1_stride=False, model_name="seresnet50b_cub", **kwargs)
def seresnet101_cub(num_classes=200, **kwargs):
"""
SE-ResNet-101 model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 200
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(num_classes=num_classes, blocks=101, model_name="seresnet101_cub", **kwargs)
def seresnet101b_cub(num_classes=200, **kwargs):
"""
SE-ResNet-101 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation
Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 200
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(num_classes=num_classes, blocks=101, conv1_stride=False, model_name="seresnet101b_cub",
**kwargs)
def seresnet152_cub(num_classes=200, **kwargs):
"""
SE-ResNet-152 model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 200
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(num_classes=num_classes, blocks=152, model_name="seresnet152_cub", **kwargs)
def seresnet152b_cub(num_classes=200, **kwargs):
"""
SE-ResNet-152 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation
Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
num_classes : int, default 200
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(num_classes=num_classes, blocks=152, conv1_stride=False, model_name="seresnet152b_cub",
**kwargs)
def seresnet200_cub(num_classes=200, **kwargs):
"""
SE-ResNet-200 model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
It's an experimental model.
Parameters:
----------
num_classes : int, default 200
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(num_classes=num_classes, blocks=200, model_name="seresnet200_cub", **kwargs)
def seresnet200b_cub(num_classes=200, **kwargs):
"""
SE-ResNet-200 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation
Networks,' https://arxiv.org/abs/1709.01507. It's an experimental model.
Parameters:
----------
num_classes : int, default 200
Number of classification num_classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnet(num_classes=num_classes, blocks=200, conv1_stride=False, model_name="seresnet200b_cub",
**kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
seresnet10_cub,
seresnet12_cub,
seresnet14_cub,
seresnetbc14b_cub,
seresnet16_cub,
seresnet18_cub,
seresnet26_cub,
seresnetbc26b_cub,
seresnet34_cub,
seresnetbc38b_cub,
seresnet50_cub,
seresnet50b_cub,
seresnet101_cub,
seresnet101b_cub,
seresnet152_cub,
seresnet152b_cub,
seresnet200_cub,
seresnet200b_cub,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != seresnet10_cub or weight_count == 5052932)
assert (model != seresnet12_cub or weight_count == 5127496)
assert (model != seresnet14_cub or weight_count == 5425104)
assert (model != seresnetbc14b_cub or weight_count == 9126136)
assert (model != seresnet16_cub or weight_count == 6614240)
assert (model != seresnet18_cub or weight_count == 11368192)
assert (model != seresnet26_cub or weight_count == 17683452)
assert (model != seresnetbc26b_cub or weight_count == 15756776)
assert (model != seresnet34_cub or weight_count == 21548468)
assert (model != seresnetbc38b_cub or weight_count == 22387416)
assert (model != seresnet50_cub or weight_count == 26448824)
assert (model != seresnet50b_cub or weight_count == 26448824)
assert (model != seresnet101_cub or weight_count == 47687672)
assert (model != seresnet101b_cub or weight_count == 47687672)
assert (model != seresnet152_cub or weight_count == 65182648)
assert (model != seresnet152b_cub or weight_count == 65182648)
assert (model != seresnet200_cub or weight_count == 70196664)
assert (model != seresnet200b_cub or weight_count == 70196664)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 200))
if __name__ == "__main__":
_test()
| 14,391 | 35.808184 | 120 | py |
null | qimera-main/pytorchcv/models/seresnext.py | """
SE-ResNeXt for ImageNet-1K, implemented in PyTorch.
Original paper: 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
"""
__all__ = ['SEResNeXt', 'seresnext50_32x4d', 'seresnext101_32x4d', 'seresnext101_64x4d']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, SEBlock
from .resnet import ResInitBlock
from .resnext import ResNeXtBottleneck
class SEResNeXtUnit(nn.Module):
"""
SE-ResNeXt unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
"""
def __init__(self,
in_channels,
out_channels,
stride,
cardinality,
bottleneck_width):
super(SEResNeXtUnit, self).__init__()
self.resize_identity = (in_channels != out_channels) or (stride != 1)
self.body = ResNeXtBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
cardinality=cardinality,
bottleneck_width=bottleneck_width)
self.se = SEBlock(channels=out_channels)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
activation=None)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = self.se(x)
x = x + identity
x = self.activ(x)
return x
class SEResNeXt(nn.Module):
"""
SE-ResNeXt model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
cardinality,
bottleneck_width,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(SEResNeXt, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), SEResNeXtUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
cardinality=cardinality,
bottleneck_width=bottleneck_width))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_seresnext(blocks,
cardinality,
bottleneck_width,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create SE-ResNeXt model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
else:
raise ValueError("Unsupported SE-ResNeXt with number of blocks: {}".format(blocks))
init_block_channels = 64
channels_per_layers = [256, 512, 1024, 2048]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = SEResNeXt(
channels=channels,
init_block_channels=init_block_channels,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def seresnext50_32x4d(**kwargs):
"""
SE-ResNeXt-50 (32x4d) model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnext(blocks=50, cardinality=32, bottleneck_width=4, model_name="seresnext50_32x4d", **kwargs)
def seresnext101_32x4d(**kwargs):
"""
SE-ResNeXt-101 (32x4d) model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnext(blocks=101, cardinality=32, bottleneck_width=4, model_name="seresnext101_32x4d", **kwargs)
def seresnext101_64x4d(**kwargs):
"""
SE-ResNeXt-101 (64x4d) model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_seresnext(blocks=101, cardinality=64, bottleneck_width=4, model_name="seresnext101_64x4d", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
seresnext50_32x4d,
seresnext101_32x4d,
seresnext101_64x4d,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != seresnext50_32x4d or weight_count == 27559896)
assert (model != seresnext101_32x4d or weight_count == 48955416)
assert (model != seresnext101_64x4d or weight_count == 88232984)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 8,721 | 29.929078 | 115 | py |
null | qimera-main/pytorchcv/models/shakedropresnet_cifar.py | """
ShakeDrop-ResNet for CIFAR/SVHN, implemented in PyTorch.
Original paper: 'ShakeDrop Regularization for Deep Residual Learning,' https://arxiv.org/abs/1802.02375.
"""
__all__ = ['CIFARShakeDropResNet', 'shakedropresnet20_cifar10', 'shakedropresnet20_cifar100', 'shakedropresnet20_svhn']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, conv3x3_block
from .resnet import ResBlock, ResBottleneck
class ShakeDrop(torch.autograd.Function):
"""
ShakeDrop function.
"""
@staticmethod
def forward(ctx, x, b, alpha):
y = (b + alpha - b * alpha) * x
ctx.save_for_backward(b)
return y
@staticmethod
def backward(ctx, dy):
beta = torch.rand(dy.size(0), dtype=dy.dtype, device=dy.device).view(-1, 1, 1, 1)
b, = ctx.saved_tensors
return (b + beta - b * beta) * dy, None, None
class ShakeDropResUnit(nn.Module):
"""
ShakeDrop-ResNet unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
life_prob : float
Residual branch life probability.
"""
def __init__(self,
in_channels,
out_channels,
stride,
bottleneck,
life_prob):
super(ShakeDropResUnit, self).__init__()
self.life_prob = life_prob
self.resize_identity = (in_channels != out_channels) or (stride != 1)
body_class = ResBottleneck if bottleneck else ResBlock
self.body = body_class(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
activation=None)
self.activ = nn.ReLU(inplace=True)
self.shake_drop = ShakeDrop.apply
def forward(self, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
if self.training:
b = torch.bernoulli(torch.full((1,), self.life_prob, dtype=x.dtype, device=x.device))
alpha = torch.empty(x.size(0), dtype=x.dtype, device=x.device).view(-1, 1, 1, 1).uniform_(-1.0, 1.0)
x = self.shake_drop(x, b, alpha)
else:
x = self.life_prob * x
x = x + identity
x = self.activ(x)
return x
class CIFARShakeDropResNet(nn.Module):
"""
ShakeDrop-ResNet model for CIFAR from 'ShakeDrop Regularization for Deep Residual Learning,'
https://arxiv.org/abs/1802.02375.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
life_probs : list of float
Residual branch life probability for each unit.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
num_classes : int, default 10
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
life_probs,
in_channels=3,
in_size=(32, 32),
num_classes=10):
super(CIFARShakeDropResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
k = 0
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), ShakeDropResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck,
life_prob=life_probs[k]))
in_channels = out_channels
k += 1
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=8,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_shakedropresnet_cifar(classes,
blocks,
bottleneck,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create ShakeDrop-ResNet model for CIFAR with specific parameters.
Parameters:
----------
classes : int
Number of classification classes.
blocks : int
Number of blocks.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
assert (classes in [10, 100])
if bottleneck:
assert ((blocks - 2) % 9 == 0)
layers = [(blocks - 2) // 9] * 3
else:
assert ((blocks - 2) % 6 == 0)
layers = [(blocks - 2) // 6] * 3
init_block_channels = 16
channels_per_layers = [16, 32, 64]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if bottleneck:
channels = [[cij * 4 for cij in ci] for ci in channels]
total_layers = sum(layers)
final_death_prob = 0.5
life_probs = [1.0 - float(i + 1) / float(total_layers) * final_death_prob for i in range(total_layers)]
net = CIFARShakeDropResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
life_probs=life_probs,
num_classes=classes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def shakedropresnet20_cifar10(classes=10, **kwargs):
"""
ShakeDrop-ResNet-20 model for CIFAR-10 from 'ShakeDrop Regularization for Deep Residual Learning,'
https://arxiv.org/abs/1802.02375.
Parameters:
----------
classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shakedropresnet_cifar(classes=classes, blocks=20, bottleneck=False,
model_name="shakedropresnet20_cifar10", **kwargs)
def shakedropresnet20_cifar100(classes=100, **kwargs):
"""
ShakeDrop-ResNet-20 model for CIFAR-100 from 'ShakeDrop Regularization for Deep Residual Learning,'
https://arxiv.org/abs/1802.02375.
Parameters:
----------
classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shakedropresnet_cifar(classes=classes, blocks=20, bottleneck=False,
model_name="shakedropresnet20_cifar100", **kwargs)
def shakedropresnet20_svhn(classes=10, **kwargs):
"""
ShakeDrop-ResNet-20 model for SVHN from 'ShakeDrop Regularization for Deep Residual Learning,'
https://arxiv.org/abs/1802.02375.
Parameters:
----------
classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shakedropresnet_cifar(classes=classes, blocks=20, bottleneck=False,
model_name="shakedropresnet20_svhn", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
(shakedropresnet20_cifar10, 10),
(shakedropresnet20_cifar100, 100),
(shakedropresnet20_svhn, 10),
]
for model, num_classes in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != shakedropresnet20_cifar10 or weight_count == 272474)
assert (model != shakedropresnet20_cifar100 or weight_count == 278324)
assert (model != shakedropresnet20_svhn or weight_count == 272474)
x = torch.randn(14, 3, 32, 32)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (14, num_classes))
if __name__ == "__main__":
_test()
| 10,750 | 31.677812 | 119 | py |
null | qimera-main/pytorchcv/models/shakeshakeresnet_cifar.py | """
Shake-Shake-ResNet for CIFAR/SVHN, implemented in PyTorch.
Original paper: 'Shake-Shake regularization,' https://arxiv.org/abs/1705.07485.
"""
__all__ = ['CIFARShakeShakeResNet', 'shakeshakeresnet20_2x16d_cifar10', 'shakeshakeresnet20_2x16d_cifar100',
'shakeshakeresnet20_2x16d_svhn', 'shakeshakeresnet26_2x32d_cifar10', 'shakeshakeresnet26_2x32d_cifar100',
'shakeshakeresnet26_2x32d_svhn']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1, conv3x3_block
from .resnet import ResBlock, ResBottleneck
class ShakeShake(torch.autograd.Function):
"""
Shake-Shake function.
"""
@staticmethod
def forward(ctx, x1, x2, alpha):
y = alpha * x1 + (1 - alpha) * x2
return y
@staticmethod
def backward(ctx, dy):
beta = torch.rand(dy.size(0), dtype=dy.dtype, device=dy.device).view(-1, 1, 1, 1)
return beta * dy, (1 - beta) * dy, None
class ShakeShakeShortcut(nn.Module):
"""
Shake-Shake-ResNet shortcut.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
"""
def __init__(self,
in_channels,
out_channels,
stride):
super(ShakeShakeShortcut, self).__init__()
assert (out_channels % 2 == 0)
mid_channels = out_channels // 2
self.pool = nn.AvgPool2d(
kernel_size=1,
stride=stride)
self.conv1 = conv1x1(
in_channels=in_channels,
out_channels=mid_channels)
self.conv2 = conv1x1(
in_channels=in_channels,
out_channels=mid_channels)
self.bn = nn.BatchNorm2d(num_features=out_channels)
self.pad = nn.ZeroPad2d(padding=(1, 0, 1, 0))
def forward(self, x):
x1 = self.pool(x)
x1 = self.conv1(x1)
x2 = x[:, :, :-1, :-1].contiguous()
x2 = self.pad(x2)
x2 = self.pool(x2)
x2 = self.conv2(x2)
x = torch.cat((x1, x2), dim=1)
x = self.bn(x)
return x
class ShakeShakeResUnit(nn.Module):
"""
Shake-Shake-ResNet unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
"""
def __init__(self,
in_channels,
out_channels,
stride,
bottleneck):
super(ShakeShakeResUnit, self).__init__()
self.resize_identity = (in_channels != out_channels) or (stride != 1)
branch_class = ResBottleneck if bottleneck else ResBlock
self.branch1 = branch_class(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
self.branch2 = branch_class(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
if self.resize_identity:
self.identity_branch = ShakeShakeShortcut(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
self.activ = nn.ReLU(inplace=True)
self.shake_shake = ShakeShake.apply
def forward(self, x):
if self.resize_identity:
identity = self.identity_branch(x)
else:
identity = x
x1 = self.branch1(x)
x2 = self.branch2(x)
if self.training:
alpha = torch.rand(x1.size(0), dtype=x1.dtype, device=x1.device).view(-1, 1, 1, 1)
x = self.shake_shake(x1, x2, alpha)
else:
x = 0.5 * (x1 + x2)
x = x + identity
x = self.activ(x)
return x
class CIFARShakeShakeResNet(nn.Module):
"""
Shake-Shake-ResNet model for CIFAR from 'Shake-Shake regularization,' https://arxiv.org/abs/1705.07485.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
num_classes : int, default 10
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
in_channels=3,
in_size=(32, 32),
num_classes=10):
super(CIFARShakeShakeResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), ShakeShakeResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=8,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_shakeshakeresnet_cifar(classes,
blocks,
bottleneck,
first_stage_channels=16,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create Shake-Shake-ResNet model for CIFAR with specific parameters.
Parameters:
----------
classes : int
Number of classification classes.
blocks : int
Number of blocks.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
first_stage_channels : int, default 16
Number of output channels for the first stage.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
assert (classes in [10, 100])
if bottleneck:
assert ((blocks - 2) % 9 == 0)
layers = [(blocks - 2) // 9] * 3
else:
assert ((blocks - 2) % 6 == 0)
layers = [(blocks - 2) // 6] * 3
init_block_channels = 16
from functools import reduce
channels_per_layers = reduce(lambda x, y: x + [x[-1] * 2], range(2), [first_stage_channels])
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if bottleneck:
channels = [[cij * 4 for cij in ci] for ci in channels]
net = CIFARShakeShakeResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
num_classes=classes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def shakeshakeresnet20_2x16d_cifar10(classes=10, **kwargs):
"""
Shake-Shake-ResNet-20-2x16d model for CIFAR-10 from 'Shake-Shake regularization,' https://arxiv.org/abs/1705.07485.
Parameters:
----------
classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shakeshakeresnet_cifar(classes=classes, blocks=20, bottleneck=False, first_stage_channels=16,
model_name="shakeshakeresnet20_2x16d_cifar10", **kwargs)
def shakeshakeresnet20_2x16d_cifar100(classes=100, **kwargs):
"""
Shake-Shake-ResNet-20-2x16d model for CIFAR-100 from 'Shake-Shake regularization,' https://arxiv.org/abs/1705.07485.
Parameters:
----------
classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shakeshakeresnet_cifar(classes=classes, blocks=20, bottleneck=False, first_stage_channels=16,
model_name="shakeshakeresnet20_2x16d_cifar100", **kwargs)
def shakeshakeresnet20_2x16d_svhn(classes=10, **kwargs):
"""
Shake-Shake-ResNet-20-2x16d model for SVHN from 'Shake-Shake regularization,' https://arxiv.org/abs/1705.07485.
Parameters:
----------
classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shakeshakeresnet_cifar(classes=classes, blocks=20, bottleneck=False, first_stage_channels=16,
model_name="shakeshakeresnet20_2x16d_svhn", **kwargs)
def shakeshakeresnet26_2x32d_cifar10(classes=10, **kwargs):
"""
Shake-Shake-ResNet-26-2x32d model for CIFAR-10 from 'Shake-Shake regularization,' https://arxiv.org/abs/1705.07485.
Parameters:
----------
classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shakeshakeresnet_cifar(classes=classes, blocks=26, bottleneck=False, first_stage_channels=32,
model_name="shakeshakeresnet26_2x32d_cifar10", **kwargs)
def shakeshakeresnet26_2x32d_cifar100(classes=100, **kwargs):
"""
Shake-Shake-ResNet-26-2x32d model for CIFAR-100 from 'Shake-Shake regularization,' https://arxiv.org/abs/1705.07485.
Parameters:
----------
classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shakeshakeresnet_cifar(classes=classes, blocks=26, bottleneck=False, first_stage_channels=32,
model_name="shakeshakeresnet26_2x32d_cifar100", **kwargs)
def shakeshakeresnet26_2x32d_svhn(classes=10, **kwargs):
"""
Shake-Shake-ResNet-26-2x32d model for SVHN from 'Shake-Shake regularization,' https://arxiv.org/abs/1705.07485.
Parameters:
----------
classes : int, default 10
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shakeshakeresnet_cifar(classes=classes, blocks=26, bottleneck=False, first_stage_channels=32,
model_name="shakeshakeresnet26_2x32d_svhn", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
(shakeshakeresnet20_2x16d_cifar10, 10),
(shakeshakeresnet20_2x16d_cifar100, 100),
(shakeshakeresnet20_2x16d_svhn, 10),
(shakeshakeresnet26_2x32d_cifar10, 10),
(shakeshakeresnet26_2x32d_cifar100, 100),
(shakeshakeresnet26_2x32d_svhn, 10),
]
for model, num_classes in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != shakeshakeresnet20_2x16d_cifar10 or weight_count == 541082)
assert (model != shakeshakeresnet20_2x16d_cifar100 or weight_count == 546932)
assert (model != shakeshakeresnet20_2x16d_svhn or weight_count == 541082)
assert (model != shakeshakeresnet26_2x32d_cifar10 or weight_count == 2923162)
assert (model != shakeshakeresnet26_2x32d_cifar100 or weight_count == 2934772)
assert (model != shakeshakeresnet26_2x32d_svhn or weight_count == 2923162)
x = torch.randn(14, 3, 32, 32)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (14, num_classes))
if __name__ == "__main__":
_test()
| 14,392 | 33.269048 | 120 | py |
null | qimera-main/pytorchcv/models/sharesnet.py | """
ShaResNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'ShaResNet: reducing residual network parameter number by sharing weights,'
https://arxiv.org/abs/1702.08782.
"""
__all__ = ['ShaResNet', 'sharesnet18', 'sharesnet34', 'sharesnet50', 'sharesnet50b', 'sharesnet101', 'sharesnet101b',
'sharesnet152', 'sharesnet152b']
import os
from inspect import isfunction
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, conv3x3_block
from .resnet import ResInitBlock
class ShaConvBlock(nn.Module):
"""
Shared convolution block with Batch normalization and ReLU/ReLU6 activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
bias : bool, default False
Whether the layer uses a bias vector.
activation : function or str or None, default nn.ReLU(inplace=True)
Activation function or name of activation function.
activate : bool, default True
Whether activate the convolution block.
shared_conv : Module, default None
Shared convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
stride,
padding,
dilation=1,
groups=1,
bias=False,
activation=(lambda: nn.ReLU(inplace=True)),
activate=True,
shared_conv=None):
super(ShaConvBlock, self).__init__()
self.activate = activate
if shared_conv is None:
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
groups=groups,
bias=bias)
else:
self.conv = shared_conv
self.bn = nn.BatchNorm2d(num_features=out_channels)
if self.activate:
assert (activation is not None)
if isfunction(activation):
self.activ = activation()
elif isinstance(activation, str):
if activation == "relu":
self.activ = nn.ReLU(inplace=True)
elif activation == "relu6":
self.activ = nn.ReLU6(inplace=True)
else:
raise NotImplementedError()
else:
self.activ = activation
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
if self.activate:
x = self.activ(x)
return x
def sha_conv3x3_block(in_channels,
out_channels,
stride=1,
padding=1,
dilation=1,
groups=1,
bias=False,
activation=(lambda: nn.ReLU(inplace=True)),
activate=True,
shared_conv=None):
"""
3x3 version of the shared convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
bias : bool, default False
Whether the layer uses a bias vector.
activation : function or str or None, default nn.ReLU(inplace=True)
Activation function or name of activation function.
activate : bool, default True
Whether activate the convolution block.
shared_conv : Module, default None
Shared convolution layer.
"""
return ShaConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=stride,
padding=padding,
dilation=dilation,
groups=groups,
bias=bias,
activation=activation,
activate=activate,
shared_conv=shared_conv)
class ShaResBlock(nn.Module):
"""
Simple ShaResNet block for residual path in ShaResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
shared_conv : Module, default None
Shared convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
stride,
shared_conv=None):
super(ShaResBlock, self).__init__()
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
self.conv2 = sha_conv3x3_block(
in_channels=out_channels,
out_channels=out_channels,
activation=None,
activate=False,
shared_conv=shared_conv)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class ShaResBottleneck(nn.Module):
"""
ShaResNet bottleneck block for residual path in ShaResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
bottleneck_factor : int, default 4
Bottleneck factor.
conv1_stride : bool, default False
Whether to use stride in the first or the second convolution layer of the block.
shared_conv : Module, default None
Shared convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
stride,
conv1_stride=False,
bottleneck_factor=4,
shared_conv=None):
super(ShaResBottleneck, self).__init__()
assert (conv1_stride or not ((stride > 1) and (shared_conv is not None)))
mid_channels = out_channels // bottleneck_factor
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
stride=(stride if conv1_stride else 1))
self.conv2 = sha_conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
stride=(1 if conv1_stride else stride),
shared_conv=shared_conv)
self.conv3 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
activation=None)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class ShaResUnit(nn.Module):
"""
ShaResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer of the block.
shared_conv : Module, default None
Shared convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
stride,
bottleneck,
conv1_stride,
shared_conv=None):
super(ShaResUnit, self).__init__()
self.resize_identity = (in_channels != out_channels) or (stride != 1)
if bottleneck:
self.body = ShaResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
conv1_stride=conv1_stride,
shared_conv=shared_conv)
else:
self.body = ShaResBlock(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
shared_conv=shared_conv)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
activation=None)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = x + identity
x = self.activ(x)
return x
class ShaResNet(nn.Module):
"""
ShaResNet model from 'ShaResNet: reducing residual network parameter number by sharing weights,'
https://arxiv.org/abs/1702.08782.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer in units.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
conv1_stride,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(ShaResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
shared_conv = None
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
unit = ShaResUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
shared_conv=shared_conv)
if (shared_conv is None) and not (bottleneck and not conv1_stride and stride > 1):
shared_conv = unit.body.conv2.conv
stage.add_module("unit{}".format(j + 1), unit)
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_sharesnet(blocks,
conv1_stride=True,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create ShaResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
conv1_stride : bool, default True
Whether to use stride in the first or the second convolution layer in units.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 18:
layers = [2, 2, 2, 2]
elif blocks == 34:
layers = [3, 4, 6, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
elif blocks == 200:
layers = [3, 24, 36, 3]
else:
raise ValueError("Unsupported ShaResNet with number of blocks: {}".format(blocks))
init_block_channels = 64
if blocks < 50:
channels_per_layers = [64, 128, 256, 512]
bottleneck = False
else:
channels_per_layers = [256, 512, 1024, 2048]
bottleneck = True
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = ShaResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def sharesnet18(**kwargs):
"""
ShaResNet-18 model from 'ShaResNet: reducing residual network parameter number by sharing weights,'
https://arxiv.org/abs/1702.08782.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sharesnet(blocks=18, model_name="sharesnet18", **kwargs)
def sharesnet34(**kwargs):
"""
ShaResNet-34 model from 'ShaResNet: reducing residual network parameter number by sharing weights,'
https://arxiv.org/abs/1702.08782.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sharesnet(blocks=34, model_name="sharesnet34", **kwargs)
def sharesnet50(**kwargs):
"""
ShaResNet-50 model from 'ShaResNet: reducing residual network parameter number by sharing weights,'
https://arxiv.org/abs/1702.08782.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sharesnet(blocks=50, model_name="sharesnet50", **kwargs)
def sharesnet50b(**kwargs):
"""
ShaResNet-50b model with stride at the second convolution in bottleneck block from 'ShaResNet: reducing residual
network parameter number by sharing weights,' https://arxiv.org/abs/1702.08782.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sharesnet(blocks=50, conv1_stride=False, model_name="sharesnet50b", **kwargs)
def sharesnet101(**kwargs):
"""
ShaResNet-101 model from 'ShaResNet: reducing residual network parameter number by sharing weights,'
https://arxiv.org/abs/1702.08782.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sharesnet(blocks=101, model_name="sharesnet101", **kwargs)
def sharesnet101b(**kwargs):
"""
ShaResNet-101b model with stride at the second convolution in bottleneck block from 'ShaResNet: reducing residual
network parameter number by sharing weights,' https://arxiv.org/abs/1702.08782.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sharesnet(blocks=101, conv1_stride=False, model_name="sharesnet101b", **kwargs)
def sharesnet152(**kwargs):
"""
ShaResNet-152 model from 'ShaResNet: reducing residual network parameter number by sharing weights,'
https://arxiv.org/abs/1702.08782.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sharesnet(blocks=152, model_name="sharesnet152", **kwargs)
def sharesnet152b(**kwargs):
"""
ShaResNet-152b model with stride at the second convolution in bottleneck block from 'ShaResNet: reducing residual
network parameter number by sharing weights,' https://arxiv.org/abs/1702.08782.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sharesnet(blocks=152, conv1_stride=False, model_name="sharesnet152b", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
sharesnet18,
sharesnet34,
sharesnet50,
sharesnet50b,
sharesnet101,
sharesnet101b,
sharesnet152,
sharesnet152b,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != sharesnet18 or weight_count == 8556072)
assert (model != sharesnet34 or weight_count == 13613864)
assert (model != sharesnet50 or weight_count == 17373224)
assert (model != sharesnet50b or weight_count == 20469800)
assert (model != sharesnet101 or weight_count == 26338344)
assert (model != sharesnet101b or weight_count == 29434920)
assert (model != sharesnet152 or weight_count == 33724456)
assert (model != sharesnet152b or weight_count == 36821032)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 19,841 | 31.263415 | 117 | py |
null | qimera-main/pytorchcv/models/shufflenet.py | """
ShuffleNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,'
https://arxiv.org/abs/1707.01083.
"""
__all__ = ['ShuffleNet', 'shufflenet_g1_w1', 'shufflenet_g2_w1', 'shufflenet_g3_w1', 'shufflenet_g4_w1',
'shufflenet_g8_w1', 'shufflenet_g1_w3d4', 'shufflenet_g3_w3d4', 'shufflenet_g1_wd2', 'shufflenet_g3_wd2',
'shufflenet_g1_wd4', 'shufflenet_g3_wd4']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1, conv3x3, depthwise_conv3x3, ChannelShuffle
class ShuffleUnit(nn.Module):
"""
ShuffleNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
groups : int
Number of groups in convolution layers.
downsample : bool
Whether do downsample.
ignore_group : bool
Whether ignore group value in the first convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
groups,
downsample,
ignore_group):
super(ShuffleUnit, self).__init__()
self.downsample = downsample
mid_channels = out_channels // 4
if downsample:
out_channels -= in_channels
self.compress_conv1 = conv1x1(
in_channels=in_channels,
out_channels=mid_channels,
groups=(1 if ignore_group else groups))
self.compress_bn1 = nn.BatchNorm2d(num_features=mid_channels)
self.c_shuffle = ChannelShuffle(
channels=mid_channels,
groups=groups)
self.dw_conv2 = depthwise_conv3x3(
channels=mid_channels,
stride=(2 if self.downsample else 1))
self.dw_bn2 = nn.BatchNorm2d(num_features=mid_channels)
self.expand_conv3 = conv1x1(
in_channels=mid_channels,
out_channels=out_channels,
groups=groups)
self.expand_bn3 = nn.BatchNorm2d(num_features=out_channels)
if downsample:
self.avgpool = nn.AvgPool2d(kernel_size=3, stride=2, padding=1)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
identity = x
x = self.compress_conv1(x)
x = self.compress_bn1(x)
x = self.activ(x)
x = self.c_shuffle(x)
x = self.dw_conv2(x)
x = self.dw_bn2(x)
x = self.expand_conv3(x)
x = self.expand_bn3(x)
if self.downsample:
identity = self.avgpool(identity)
x = torch.cat((x, identity), dim=1)
else:
x = x + identity
x = self.activ(x)
return x
class ShuffleInitBlock(nn.Module):
"""
ShuffleNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(ShuffleInitBlock, self).__init__()
self.conv = conv3x3(
in_channels=in_channels,
out_channels=out_channels,
stride=2)
self.bn = nn.BatchNorm2d(num_features=out_channels)
self.activ = nn.ReLU(inplace=True)
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=1)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
x = self.activ(x)
x = self.pool(x)
return x
class ShuffleNet(nn.Module):
"""
ShuffleNet model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,'
https://arxiv.org/abs/1707.01083.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
groups : int
Number of groups in convolution layers.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
groups,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(ShuffleNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", ShuffleInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
downsample = (j == 0)
ignore_group = (i == 0) and (j == 0)
stage.add_module("unit{}".format(j + 1), ShuffleUnit(
in_channels=in_channels,
out_channels=out_channels,
groups=groups,
downsample=downsample,
ignore_group=ignore_group))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_shufflenet(groups,
width_scale,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create ShuffleNet model with specific parameters.
Parameters:
----------
groups : int
Number of groups in convolution layers.
width_scale : float
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
init_block_channels = 24
layers = [4, 8, 4]
if groups == 1:
channels_per_layers = [144, 288, 576]
elif groups == 2:
channels_per_layers = [200, 400, 800]
elif groups == 3:
channels_per_layers = [240, 480, 960]
elif groups == 4:
channels_per_layers = [272, 544, 1088]
elif groups == 8:
channels_per_layers = [384, 768, 1536]
else:
raise ValueError("The {} of groups is not supported".format(groups))
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if width_scale != 1.0:
channels = [[int(cij * width_scale) for cij in ci] for ci in channels]
init_block_channels = int(init_block_channels * width_scale)
net = ShuffleNet(
channels=channels,
init_block_channels=init_block_channels,
groups=groups,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def shufflenet_g1_w1(**kwargs):
"""
ShuffleNet 1x (g=1) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,'
https://arxiv.org/abs/1707.01083.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shufflenet(groups=1, width_scale=1.0, model_name="shufflenet_g1_w1", **kwargs)
def shufflenet_g2_w1(**kwargs):
"""
ShuffleNet 1x (g=2) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,'
https://arxiv.org/abs/1707.01083.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shufflenet(groups=2, width_scale=1.0, model_name="shufflenet_g2_w1", **kwargs)
def shufflenet_g3_w1(**kwargs):
"""
ShuffleNet 1x (g=3) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,'
https://arxiv.org/abs/1707.01083.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shufflenet(groups=3, width_scale=1.0, model_name="shufflenet_g3_w1", **kwargs)
def shufflenet_g4_w1(**kwargs):
"""
ShuffleNet 1x (g=4) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,'
https://arxiv.org/abs/1707.01083.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shufflenet(groups=4, width_scale=1.0, model_name="shufflenet_g4_w1", **kwargs)
def shufflenet_g8_w1(**kwargs):
"""
ShuffleNet 1x (g=8) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,'
https://arxiv.org/abs/1707.01083.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shufflenet(groups=8, width_scale=1.0, model_name="shufflenet_g8_w1", **kwargs)
def shufflenet_g1_w3d4(**kwargs):
"""
ShuffleNet 0.75x (g=1) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile
Devices,' https://arxiv.org/abs/1707.01083.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shufflenet(groups=1, width_scale=0.75, model_name="shufflenet_g1_w3d4", **kwargs)
def shufflenet_g3_w3d4(**kwargs):
"""
ShuffleNet 0.75x (g=3) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile
Devices,' https://arxiv.org/abs/1707.01083.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shufflenet(groups=3, width_scale=0.75, model_name="shufflenet_g3_w3d4", **kwargs)
def shufflenet_g1_wd2(**kwargs):
"""
ShuffleNet 0.5x (g=1) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile
Devices,' https://arxiv.org/abs/1707.01083.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shufflenet(groups=1, width_scale=0.5, model_name="shufflenet_g1_wd2", **kwargs)
def shufflenet_g3_wd2(**kwargs):
"""
ShuffleNet 0.5x (g=3) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile
Devices,' https://arxiv.org/abs/1707.01083.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shufflenet(groups=3, width_scale=0.5, model_name="shufflenet_g3_wd2", **kwargs)
def shufflenet_g1_wd4(**kwargs):
"""
ShuffleNet 0.25x (g=1) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile
Devices,' https://arxiv.org/abs/1707.01083.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shufflenet(groups=1, width_scale=0.25, model_name="shufflenet_g1_wd4", **kwargs)
def shufflenet_g3_wd4(**kwargs):
"""
ShuffleNet 0.25x (g=3) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile
Devices,' https://arxiv.org/abs/1707.01083.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shufflenet(groups=3, width_scale=0.25, model_name="shufflenet_g3_wd4", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
shufflenet_g1_w1,
shufflenet_g2_w1,
shufflenet_g3_w1,
shufflenet_g4_w1,
shufflenet_g8_w1,
shufflenet_g1_w3d4,
shufflenet_g3_w3d4,
shufflenet_g1_wd2,
shufflenet_g3_wd2,
shufflenet_g1_wd4,
shufflenet_g3_wd4,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != shufflenet_g1_w1 or weight_count == 1531936)
assert (model != shufflenet_g2_w1 or weight_count == 1733848)
assert (model != shufflenet_g3_w1 or weight_count == 1865728)
assert (model != shufflenet_g4_w1 or weight_count == 1968344)
assert (model != shufflenet_g8_w1 or weight_count == 2434768)
assert (model != shufflenet_g1_w3d4 or weight_count == 975214)
assert (model != shufflenet_g3_w3d4 or weight_count == 1238266)
assert (model != shufflenet_g1_wd2 or weight_count == 534484)
assert (model != shufflenet_g3_wd2 or weight_count == 718324)
assert (model != shufflenet_g1_wd4 or weight_count == 209746)
assert (model != shufflenet_g3_wd4 or weight_count == 305902)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 15,779 | 31.875 | 120 | py |
null | qimera-main/pytorchcv/models/shufflenetv2.py | """
ShuffleNet V2 for ImageNet-1K, implemented in PyTorch.
Original paper: 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'
https://arxiv.org/abs/1807.11164.
"""
__all__ = ['ShuffleNetV2', 'shufflenetv2_wd2', 'shufflenetv2_w1', 'shufflenetv2_w3d2', 'shufflenetv2_w2']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1, depthwise_conv3x3, conv1x1_block, conv3x3_block, ChannelShuffle, SEBlock
class ShuffleUnit(nn.Module):
"""
ShuffleNetV2 unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
downsample : bool
Whether do downsample.
use_se : bool
Whether to use SE block.
use_residual : bool
Whether to use residual connection.
"""
def __init__(self,
in_channels,
out_channels,
downsample,
use_se,
use_residual):
super(ShuffleUnit, self).__init__()
self.downsample = downsample
self.use_se = use_se
self.use_residual = use_residual
mid_channels = out_channels // 2
self.compress_conv1 = conv1x1(
in_channels=(in_channels if self.downsample else mid_channels),
out_channels=mid_channels)
self.compress_bn1 = nn.BatchNorm2d(num_features=mid_channels)
self.dw_conv2 = depthwise_conv3x3(
channels=mid_channels,
stride=(2 if self.downsample else 1))
self.dw_bn2 = nn.BatchNorm2d(num_features=mid_channels)
self.expand_conv3 = conv1x1(
in_channels=mid_channels,
out_channels=mid_channels)
self.expand_bn3 = nn.BatchNorm2d(num_features=mid_channels)
if self.use_se:
self.se = SEBlock(channels=mid_channels)
if downsample:
self.dw_conv4 = depthwise_conv3x3(
channels=in_channels,
stride=2)
self.dw_bn4 = nn.BatchNorm2d(num_features=in_channels)
self.expand_conv5 = conv1x1(
in_channels=in_channels,
out_channels=mid_channels)
self.expand_bn5 = nn.BatchNorm2d(num_features=mid_channels)
self.activ = nn.ReLU(inplace=True)
self.c_shuffle = ChannelShuffle(
channels=out_channels,
groups=2)
def forward(self, x):
if self.downsample:
y1 = self.dw_conv4(x)
y1 = self.dw_bn4(y1)
y1 = self.expand_conv5(y1)
y1 = self.expand_bn5(y1)
y1 = self.activ(y1)
x2 = x
else:
y1, x2 = torch.chunk(x, chunks=2, dim=1)
y2 = self.compress_conv1(x2)
y2 = self.compress_bn1(y2)
y2 = self.activ(y2)
y2 = self.dw_conv2(y2)
y2 = self.dw_bn2(y2)
y2 = self.expand_conv3(y2)
y2 = self.expand_bn3(y2)
y2 = self.activ(y2)
if self.use_se:
y2 = self.se(y2)
if self.use_residual and not self.downsample:
y2 = y2 + x2
x = torch.cat((y1, y2), dim=1)
x = self.c_shuffle(x)
return x
class ShuffleInitBlock(nn.Module):
"""
ShuffleNetV2 specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(ShuffleInitBlock, self).__init__()
self.conv = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
stride=2)
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=0,
ceil_mode=True)
def forward(self, x):
x = self.conv(x)
x = self.pool(x)
return x
class ShuffleNetV2(nn.Module):
"""
ShuffleNetV2 model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'
https://arxiv.org/abs/1807.11164.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
final_block_channels : int
Number of output channels for the final block of the feature extractor.
use_se : bool, default False
Whether to use SE block.
use_residual : bool, default False
Whether to use residual connections.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
final_block_channels,
use_se=False,
use_residual=False,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(ShuffleNetV2, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", ShuffleInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
downsample = (j == 0)
stage.add_module("unit{}".format(j + 1), ShuffleUnit(
in_channels=in_channels,
out_channels=out_channels,
downsample=downsample,
use_se=use_se,
use_residual=use_residual))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_block', conv1x1_block(
in_channels=in_channels,
out_channels=final_block_channels))
in_channels = final_block_channels
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_shufflenetv2(width_scale,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create ShuffleNetV2 model with specific parameters.
Parameters:
----------
width_scale : float
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
init_block_channels = 24
final_block_channels = 1024
layers = [4, 8, 4]
channels_per_layers = [116, 232, 464]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if width_scale != 1.0:
channels = [[int(cij * width_scale) for cij in ci] for ci in channels]
if width_scale > 1.5:
final_block_channels = int(final_block_channels * width_scale)
net = ShuffleNetV2(
channels=channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def shufflenetv2_wd2(**kwargs):
"""
ShuffleNetV2 0.5x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'
https://arxiv.org/abs/1807.11164.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shufflenetv2(width_scale=(12.0 / 29.0), model_name="shufflenetv2_wd2", **kwargs)
def shufflenetv2_w1(**kwargs):
"""
ShuffleNetV2 1x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'
https://arxiv.org/abs/1807.11164.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shufflenetv2(width_scale=1.0, model_name="shufflenetv2_w1", **kwargs)
def shufflenetv2_w3d2(**kwargs):
"""
ShuffleNetV2 1.5x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'
https://arxiv.org/abs/1807.11164.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shufflenetv2(width_scale=(44.0 / 29.0), model_name="shufflenetv2_w3d2", **kwargs)
def shufflenetv2_w2(**kwargs):
"""
ShuffleNetV2 2x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'
https://arxiv.org/abs/1807.11164.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shufflenetv2(width_scale=(61.0 / 29.0), model_name="shufflenetv2_w2", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
shufflenetv2_wd2,
shufflenetv2_w1,
shufflenetv2_w3d2,
shufflenetv2_w2,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != shufflenetv2_wd2 or weight_count == 1366792)
assert (model != shufflenetv2_w1 or weight_count == 2278604)
assert (model != shufflenetv2_w3d2 or weight_count == 4406098)
assert (model != shufflenetv2_w2 or weight_count == 7601686)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 11,722 | 30.942779 | 115 | py |
null | qimera-main/pytorchcv/models/shufflenetv2b.py | """
ShuffleNet V2 for ImageNet-1K, implemented in PyTorch. The alternative version.
Original paper: 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'
https://arxiv.org/abs/1807.11164.
"""
__all__ = ['ShuffleNetV2b', 'shufflenetv2b_wd2', 'shufflenetv2b_w1', 'shufflenetv2b_w3d2', 'shufflenetv2b_w2']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, conv3x3_block, dwconv3x3_block, ChannelShuffle, ChannelShuffle2, SEBlock
class ShuffleUnit(nn.Module):
"""
ShuffleNetV2(b) unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
downsample : bool
Whether do downsample.
use_se : bool
Whether to use SE block.
use_residual : bool
Whether to use residual connection.
shuffle_group_first : bool
Whether to use channel shuffle in group first mode.
"""
def __init__(self,
in_channels,
out_channels,
downsample,
use_se,
use_residual,
shuffle_group_first):
super(ShuffleUnit, self).__init__()
self.downsample = downsample
self.use_se = use_se
self.use_residual = use_residual
mid_channels = out_channels // 2
in_channels2 = in_channels // 2
assert (in_channels % 2 == 0)
y2_in_channels = (in_channels if downsample else in_channels2)
y2_out_channels = out_channels - y2_in_channels
self.conv1 = conv1x1_block(
in_channels=y2_in_channels,
out_channels=mid_channels)
self.dconv = dwconv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
stride=(2 if self.downsample else 1),
activation=None)
self.conv2 = conv1x1_block(
in_channels=mid_channels,
out_channels=y2_out_channels)
if self.use_se:
self.se = SEBlock(channels=y2_out_channels)
if downsample:
self.shortcut_dconv = dwconv3x3_block(
in_channels=in_channels,
out_channels=in_channels,
stride=2,
activation=None)
self.shortcut_conv = conv1x1_block(
in_channels=in_channels,
out_channels=in_channels)
if shuffle_group_first:
self.c_shuffle = ChannelShuffle(
channels=out_channels,
groups=2)
else:
self.c_shuffle = ChannelShuffle2(
channels=out_channels,
groups=2)
def forward(self, x):
if self.downsample:
y1 = self.shortcut_dconv(x)
y1 = self.shortcut_conv(y1)
x2 = x
else:
y1, x2 = torch.chunk(x, chunks=2, dim=1)
y2 = self.conv1(x2)
y2 = self.dconv(y2)
y2 = self.conv2(y2)
if self.use_se:
y2 = self.se(y2)
if self.use_residual and not self.downsample:
y2 = y2 + x2
x = torch.cat((y1, y2), dim=1)
x = self.c_shuffle(x)
return x
class ShuffleInitBlock(nn.Module):
"""
ShuffleNetV2(b) specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(ShuffleInitBlock, self).__init__()
self.conv = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
stride=2)
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=1,
ceil_mode=False)
def forward(self, x):
x = self.conv(x)
x = self.pool(x)
return x
class ShuffleNetV2b(nn.Module):
"""
ShuffleNetV2(b) model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'
https://arxiv.org/abs/1807.11164.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
final_block_channels : int
Number of output channels for the final block of the feature extractor.
use_se : bool, default False
Whether to use SE block.
use_residual : bool, default False
Whether to use residual connections.
shuffle_group_first : bool, default True
Whether to use channel shuffle in group first mode.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
final_block_channels,
use_se=False,
use_residual=False,
shuffle_group_first=True,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(ShuffleNetV2b, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", ShuffleInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
downsample = (j == 0)
stage.add_module("unit{}".format(j + 1), ShuffleUnit(
in_channels=in_channels,
out_channels=out_channels,
downsample=downsample,
use_se=use_se,
use_residual=use_residual,
shuffle_group_first=shuffle_group_first))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_block', conv1x1_block(
in_channels=in_channels,
out_channels=final_block_channels))
in_channels = final_block_channels
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_shufflenetv2b(width_scale,
shuffle_group_first=True,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create ShuffleNetV2(b) model with specific parameters.
Parameters:
----------
width_scale : float
Scale factor for width of layers.
shuffle_group_first : bool, default True
Whether to use channel shuffle in group first mode.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
init_block_channels = 24
final_block_channels = 1024
layers = [4, 8, 4]
channels_per_layers = [116, 232, 464]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if width_scale != 1.0:
channels = [[int(cij * width_scale) for cij in ci] for ci in channels]
if width_scale > 1.5:
final_block_channels = int(final_block_channels * width_scale)
net = ShuffleNetV2b(
channels=channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
shuffle_group_first=shuffle_group_first,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def shufflenetv2b_wd2(**kwargs):
"""
ShuffleNetV2(b) 0.5x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'
https://arxiv.org/abs/1807.11164.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shufflenetv2b(
width_scale=(12.0 / 29.0),
shuffle_group_first=True,
model_name="shufflenetv2b_wd2",
**kwargs)
def shufflenetv2b_w1(**kwargs):
"""
ShuffleNetV2(b) 1x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'
https://arxiv.org/abs/1807.11164.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shufflenetv2b(
width_scale=1.0,
shuffle_group_first=True,
model_name="shufflenetv2b_w1",
**kwargs)
def shufflenetv2b_w3d2(**kwargs):
"""
ShuffleNetV2(b) 1.5x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'
https://arxiv.org/abs/1807.11164.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shufflenetv2b(
width_scale=(44.0 / 29.0),
shuffle_group_first=True,
model_name="shufflenetv2b_w3d2",
**kwargs)
def shufflenetv2b_w2(**kwargs):
"""
ShuffleNetV2(b) 2x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'
https://arxiv.org/abs/1807.11164.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_shufflenetv2b(
width_scale=(61.0 / 29.0),
shuffle_group_first=True,
model_name="shufflenetv2b_w2",
**kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
shufflenetv2b_wd2,
shufflenetv2b_w1,
shufflenetv2b_w3d2,
shufflenetv2b_w2,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != shufflenetv2b_wd2 or weight_count == 1366792)
assert (model != shufflenetv2b_w1 or weight_count == 2279760)
assert (model != shufflenetv2b_w3d2 or weight_count == 4410194)
assert (model != shufflenetv2b_w2 or weight_count == 7611290)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 12,431 | 30.553299 | 115 | py |
null | qimera-main/pytorchcv/models/sknet.py | """
SKNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'Selective Kernel Networks,' https://arxiv.org/abs/1903.06586.
"""
__all__ = ['SKNet', 'sknet50', 'sknet101', 'sknet152']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1, conv1x1_block, conv3x3_block, Concurrent
from .resnet import ResInitBlock
class SKConvBlock(nn.Module):
"""
SKNet specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
groups : int, default 32
Number of groups in branches.
num_branches : int, default 2
Number of branches (`M` parameter in the paper).
reduction : int, default 16
Reduction value for intermediate channels (`r` parameter in the paper).
min_channels : int, default 32
Minimal number of intermediate channels (`L` parameter in the paper).
"""
def __init__(self,
in_channels,
out_channels,
stride,
groups=32,
num_branches=2,
reduction=16,
min_channels=32):
super(SKConvBlock, self).__init__()
self.num_branches = num_branches
self.out_channels = out_channels
mid_channels = max(in_channels // reduction, min_channels)
self.branches = Concurrent(stack=True)
for i in range(num_branches):
dilation = 1 + i
self.branches.add_module("branch{}".format(i + 2), conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
padding=dilation,
dilation=dilation,
groups=groups))
self.pool = nn.AdaptiveAvgPool2d(output_size=1)
self.fc1 = conv1x1_block(
in_channels=out_channels,
out_channels=mid_channels)
self.fc2 = conv1x1(
in_channels=mid_channels,
out_channels=(out_channels * num_branches))
self.softmax = nn.Softmax(dim=1)
def forward(self, x):
y = self.branches(x)
u = y.sum(dim=1)
s = self.pool(u)
z = self.fc1(s)
w = self.fc2(z)
batch = w.size(0)
w = w.view(batch, self.num_branches, self.out_channels)
w = self.softmax(w)
w = w.unsqueeze(-1).unsqueeze(-1)
y = y * w
y = y.sum(dim=1)
return y
class SKNetBottleneck(nn.Module):
"""
SKNet bottleneck block for residual path in SKNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
bottleneck_factor : int, default 2
Bottleneck factor.
"""
def __init__(self,
in_channels,
out_channels,
stride,
bottleneck_factor=2):
super(SKNetBottleneck, self).__init__()
mid_channels = out_channels // bottleneck_factor
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels)
self.conv2 = SKConvBlock(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride)
self.conv3 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
activation=None)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class SKNetUnit(nn.Module):
"""
SKNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
"""
def __init__(self,
in_channels,
out_channels,
stride):
super(SKNetUnit, self).__init__()
self.resize_identity = (in_channels != out_channels) or (stride != 1)
self.body = SKNetBottleneck(
in_channels=in_channels,
out_channels=out_channels,
stride=stride)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
activation=None)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = x + identity
x = self.activ(x)
return x
class SKNet(nn.Module):
"""
SKNet model from 'Selective Kernel Networks,' https://arxiv.org/abs/1903.06586.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(SKNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), SKNetUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_sknet(blocks,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create SKNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
else:
raise ValueError("Unsupported SKNet with number of blocks: {}".format(blocks))
init_block_channels = 64
channels_per_layers = [256, 512, 1024, 2048]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = SKNet(
channels=channels,
init_block_channels=init_block_channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def sknet50(**kwargs):
"""
SKNet-50 model from 'Selective Kernel Networks,' https://arxiv.org/abs/1903.06586.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sknet(blocks=50, model_name="sknet50", **kwargs)
def sknet101(**kwargs):
"""
SKNet-101 model from 'Selective Kernel Networks,' https://arxiv.org/abs/1903.06586.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sknet(blocks=101, model_name="sknet101", **kwargs)
def sknet152(**kwargs):
"""
SKNet-152 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sknet(blocks=152, model_name="sknet152", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
sknet50,
sknet101,
sknet152,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != sknet50 or weight_count == 27479784)
assert (model != sknet101 or weight_count == 48736040)
assert (model != sknet152 or weight_count == 66295656)
x = torch.randn(14, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (14, 1000))
if __name__ == "__main__":
_test()
| 10,909 | 28.486486 | 115 | py |
null | qimera-main/pytorchcv/models/sparsenet.py | """
SparseNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'Sparsely Aggregated Convolutional Networks,' https://arxiv.org/abs/1801.05895.
"""
__all__ = ['SparseNet', 'sparsenet121', 'sparsenet161', 'sparsenet169', 'sparsenet201', 'sparsenet264']
import os
import math
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import pre_conv1x1_block, pre_conv3x3_block
from .preresnet import PreResInitBlock, PreResActivation
from .densenet import TransitionBlock
def sparsenet_exponential_fetch(lst):
"""
SparseNet's specific exponential fetch.
Parameters:
----------
lst : list
List of something.
Returns
-------
list
Filtered list.
"""
return [lst[len(lst) - 2**i] for i in range(1 + math.floor(math.log(len(lst), 2)))]
class SparseBlock(nn.Module):
"""
SparseNet block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
dropout_rate : float
Parameter of Dropout layer. Faction of the input units to drop.
"""
def __init__(self,
in_channels,
out_channels,
dropout_rate):
super(SparseBlock, self).__init__()
self.use_dropout = (dropout_rate != 0.0)
bn_size = 4
mid_channels = out_channels * bn_size
self.conv1 = pre_conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels)
self.conv2 = pre_conv3x3_block(
in_channels=mid_channels,
out_channels=out_channels)
if self.use_dropout:
self.dropout = nn.Dropout(p=dropout_rate)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
if self.use_dropout:
x = self.dropout(x)
return x
class SparseStage(nn.Module):
"""
SparseNet stage.
Parameters:
----------
in_channels : int
Number of input channels.
channels_per_stage : list of int
Number of output channels for each unit in stage.
growth_rate : int
Growth rate for blocks.
dropout_rate : float
Parameter of Dropout layer. Faction of the input units to drop.
do_transition : bool
Whether use transition block.
"""
def __init__(self,
in_channels,
channels_per_stage,
growth_rate,
dropout_rate,
do_transition):
super(SparseStage, self).__init__()
self.do_transition = do_transition
if self.do_transition:
self.trans = TransitionBlock(
in_channels=in_channels,
out_channels=(in_channels // 2))
in_channels = in_channels // 2
self.blocks = nn.Sequential()
for i, out_channels in enumerate(channels_per_stage):
self.blocks.add_module("block{}".format(i + 1), SparseBlock(
in_channels=in_channels,
out_channels=growth_rate,
dropout_rate=dropout_rate))
in_channels = out_channels
def forward(self, x):
if self.do_transition:
x = self.trans(x)
outs = [x]
for block in self.blocks._modules.values():
y = block(x)
outs.append(y)
flt_outs = sparsenet_exponential_fetch(outs)
x = torch.cat(tuple(flt_outs), dim=1)
return x
class SparseNet(nn.Module):
"""
SparseNet model from 'Sparsely Aggregated Convolutional Networks,' https://arxiv.org/abs/1801.05895.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
growth_rate : int
Growth rate for blocks.
dropout_rate : float, default 0.0
Parameter of Dropout layer. Faction of the input units to drop.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
growth_rate,
dropout_rate=0.0,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(SparseNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", PreResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = SparseStage(
in_channels=in_channels,
channels_per_stage=channels_per_stage,
growth_rate=growth_rate,
dropout_rate=dropout_rate,
do_transition=(i != 0))
in_channels = channels_per_stage[-1]
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module("post_activ", PreResActivation(in_channels=in_channels))
self.features.add_module("final_pool", nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_sparsenet(num_layers,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create SparseNet model with specific parameters.
Parameters:
----------
num_layers : int
Number of layers.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if num_layers == 121:
init_block_channels = 64
growth_rate = 32
layers = [6, 12, 24, 16]
elif num_layers == 161:
init_block_channels = 96
growth_rate = 48
layers = [6, 12, 36, 24]
elif num_layers == 169:
init_block_channels = 64
growth_rate = 32
layers = [6, 12, 32, 32]
elif num_layers == 201:
init_block_channels = 64
growth_rate = 32
layers = [6, 12, 48, 32]
elif num_layers == 264:
init_block_channels = 64
growth_rate = 32
layers = [6, 12, 64, 48]
else:
raise ValueError("Unsupported SparseNet version with number of layers {}".format(num_layers))
from functools import reduce
channels = reduce(
lambda xi, yi: xi + [reduce(
lambda xj, yj: xj + [sum(sparsenet_exponential_fetch([xj[0]] + [yj[0]] * (yj[1] + 1)))],
zip([growth_rate] * yi, range(yi)),
[xi[-1][-1] // 2])[1:]],
layers,
[[init_block_channels * 2]])[1:]
net = SparseNet(
channels=channels,
init_block_channels=init_block_channels,
growth_rate=growth_rate,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def sparsenet121(**kwargs):
"""
SparseNet-121 model from 'Sparsely Aggregated Convolutional Networks,' https://arxiv.org/abs/1801.05895.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sparsenet(num_layers=121, model_name="sparsenet121", **kwargs)
def sparsenet161(**kwargs):
"""
SparseNet-161 model from 'Sparsely Aggregated Convolutional Networks,' https://arxiv.org/abs/1801.05895.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sparsenet(num_layers=161, model_name="sparsenet161", **kwargs)
def sparsenet169(**kwargs):
"""
SparseNet-169 model from 'Sparsely Aggregated Convolutional Networks,' https://arxiv.org/abs/1801.05895.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sparsenet(num_layers=169, model_name="sparsenet169", **kwargs)
def sparsenet201(**kwargs):
"""
SparseNet-201 model from 'Sparsely Aggregated Convolutional Networks,' https://arxiv.org/abs/1801.05895.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sparsenet(num_layers=201, model_name="sparsenet201", **kwargs)
def sparsenet264(**kwargs):
"""
SparseNet-264 model from 'Sparsely Aggregated Convolutional Networks,' https://arxiv.org/abs/1801.05895.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_sparsenet(num_layers=264, model_name="sparsenet264", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
sparsenet121,
sparsenet161,
sparsenet169,
sparsenet201,
sparsenet264,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != sparsenet121 or weight_count == 3250824)
assert (model != sparsenet161 or weight_count == 9853288)
assert (model != sparsenet169 or weight_count == 4709864)
assert (model != sparsenet201 or weight_count == 5703144)
assert (model != sparsenet264 or weight_count == 7717224)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 11,645 | 29.566929 | 115 | py |
null | qimera-main/pytorchcv/models/spnasnet.py | """
Single-Path NASNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'Single-Path NAS: Designing Hardware-Efficient ConvNets in less than 4 Hours,'
https://arxiv.org/abs/1904.02877.
"""
__all__ = ['SPNASNet', 'spnasnet']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1_block, conv3x3_block, dwconv3x3_block, dwconv5x5_block
class SPNASUnit(nn.Module):
"""
Single-Path NASNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the second convolution layer.
use_kernel3 : bool
Whether to use 3x3 (instead of 5x5) kernel.
exp_factor : int
Expansion factor for each unit.
use_skip : bool, default True
Whether to use skip connection.
activation : str, default 'relu'
Activation function or name of activation function.
"""
def __init__(self,
in_channels,
out_channels,
stride,
use_kernel3,
exp_factor,
use_skip=True,
activation="relu"):
super(SPNASUnit, self).__init__()
assert (exp_factor >= 1)
self.residual = (in_channels == out_channels) and (stride == 1) and use_skip
self.use_exp_conv = exp_factor > 1
mid_channels = exp_factor * in_channels
if self.use_exp_conv:
self.exp_conv = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
activation=activation)
if use_kernel3:
self.conv1 = dwconv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride,
activation=activation)
else:
self.conv1 = dwconv5x5_block(
in_channels=mid_channels,
out_channels=mid_channels,
stride=stride,
activation=activation)
self.conv2 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
activation=None)
def forward(self, x):
if self.residual:
identity = x
if self.use_exp_conv:
x = self.exp_conv(x)
x = self.conv1(x)
x = self.conv2(x)
if self.residual:
x = x + identity
return x
class SPNASInitBlock(nn.Module):
"""
Single-Path NASNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
mid_channels : int
Number of middle channels.
"""
def __init__(self,
in_channels,
out_channels,
mid_channels):
super(SPNASInitBlock, self).__init__()
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=mid_channels,
stride=2)
self.conv2 = SPNASUnit(
in_channels=mid_channels,
out_channels=out_channels,
stride=1,
use_kernel3=True,
exp_factor=1,
use_skip=False)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class SPNASFinalBlock(nn.Module):
"""
Single-Path NASNet specific final block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
mid_channels : int
Number of middle channels.
"""
def __init__(self,
in_channels,
out_channels,
mid_channels):
super(SPNASFinalBlock, self).__init__()
self.conv1 = SPNASUnit(
in_channels=in_channels,
out_channels=mid_channels,
stride=1,
use_kernel3=True,
exp_factor=6,
use_skip=False)
self.conv2 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class SPNASNet(nn.Module):
"""
Single-Path NASNet model from 'Single-Path NAS: Designing Hardware-Efficient ConvNets in less than 4 Hours,'
https://arxiv.org/abs/1904.02877.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : list of 2 int
Number of output channels for the initial unit.
final_block_channels : list of 2 int
Number of output channels for the final block of the feature extractor.
kernels3 : list of list of int/bool
Using 3x3 (instead of 5x5) kernel for each unit.
exp_factors : list of list of int
Expansion factor for each unit.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
final_block_channels,
kernels3,
exp_factors,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(SPNASNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", SPNASInitBlock(
in_channels=in_channels,
out_channels=init_block_channels[1],
mid_channels=init_block_channels[0]))
in_channels = init_block_channels[1]
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if ((j == 0) and (i != 3)) or ((j == len(channels_per_stage) // 2) and (i == 3)) else 1
use_kernel3 = kernels3[i][j] == 1
exp_factor = exp_factors[i][j]
stage.add_module("unit{}".format(j + 1), SPNASUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
use_kernel3=use_kernel3,
exp_factor=exp_factor))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_block', SPNASFinalBlock(
in_channels=in_channels,
out_channels=final_block_channels[1],
mid_channels=final_block_channels[0]))
in_channels = final_block_channels[1]
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_spnasnet(model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create Single-Path NASNet model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
init_block_channels = [32, 16]
final_block_channels = [320, 1280]
channels = [[24, 24, 24], [40, 40, 40, 40], [80, 80, 80, 80], [96, 96, 96, 96, 192, 192, 192, 192]]
kernels3 = [[1, 1, 1], [0, 1, 1, 1], [0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0]]
exp_factors = [[3, 3, 3], [6, 3, 3, 3], [6, 3, 3, 3], [6, 3, 3, 3, 6, 6, 6, 6]]
net = SPNASNet(
channels=channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
kernels3=kernels3,
exp_factors=exp_factors,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def spnasnet(**kwargs):
"""
Single-Path NASNet model from 'Single-Path NAS: Designing Hardware-Efficient ConvNets in less than 4 Hours,'
https://arxiv.org/abs/1904.02877.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_spnasnet(model_name="spnasnet", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
spnasnet,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != spnasnet or weight_count == 4421616)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 10,388 | 30.10479 | 115 | py |
null | qimera-main/pytorchcv/models/squeezenet.py | """
SqueezeNet for ImageNet-1K, implemented in PyTorch.
Original paper: 'SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size,'
https://arxiv.org/abs/1602.07360.
"""
__all__ = ['SqueezeNet', 'squeezenet_v1_0', 'squeezenet_v1_1', 'squeezeresnet_v1_0', 'squeezeresnet_v1_1']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
class FireConv(nn.Module):
"""
SqueezeNet specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
padding):
super(FireConv, self).__init__()
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
padding=padding)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
x = self.conv(x)
x = self.activ(x)
return x
class FireUnit(nn.Module):
"""
SqueezeNet unit, so-called 'Fire' unit.
Parameters:
----------
in_channels : int
Number of input channels.
squeeze_channels : int
Number of output channels for squeeze convolution blocks.
expand1x1_channels : int
Number of output channels for expand 1x1 convolution blocks.
expand3x3_channels : int
Number of output channels for expand 3x3 convolution blocks.
residual : bool
Whether use residual connection.
"""
def __init__(self,
in_channels,
squeeze_channels,
expand1x1_channels,
expand3x3_channels,
residual):
super(FireUnit, self).__init__()
self.residual = residual
self.squeeze = FireConv(
in_channels=in_channels,
out_channels=squeeze_channels,
kernel_size=1,
padding=0)
self.expand1x1 = FireConv(
in_channels=squeeze_channels,
out_channels=expand1x1_channels,
kernel_size=1,
padding=0)
self.expand3x3 = FireConv(
in_channels=squeeze_channels,
out_channels=expand3x3_channels,
kernel_size=3,
padding=1)
def forward(self, x):
if self.residual:
identity = x
x = self.squeeze(x)
y1 = self.expand1x1(x)
y2 = self.expand3x3(x)
out = torch.cat((y1, y2), dim=1)
if self.residual:
out = out + identity
return out
class SqueezeInitBlock(nn.Module):
"""
SqueezeNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size):
super(SqueezeInitBlock, self).__init__()
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=2)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
x = self.conv(x)
x = self.activ(x)
return x
class SqueezeNet(nn.Module):
"""
SqueezeNet model from 'SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size,'
https://arxiv.org/abs/1602.07360.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
residuals : bool
Whether to use residual units.
init_block_kernel_size : int or tuple/list of 2 int
The dimensions of the convolution window for the initial unit.
init_block_channels : int
Number of output channels for the initial unit.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
residuals,
init_block_kernel_size,
init_block_channels,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(SqueezeNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", SqueezeInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
kernel_size=init_block_kernel_size))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
stage.add_module("pool{}".format(i + 1), nn.MaxPool2d(
kernel_size=3,
stride=2,
ceil_mode=True))
for j, out_channels in enumerate(channels_per_stage):
expand_channels = out_channels // 2
squeeze_channels = out_channels // 8
stage.add_module("unit{}".format(j + 1), FireUnit(
in_channels=in_channels,
squeeze_channels=squeeze_channels,
expand1x1_channels=expand_channels,
expand3x3_channels=expand_channels,
residual=((residuals is not None) and (residuals[i][j] == 1))))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('dropout', nn.Dropout(p=0.5))
self.output = nn.Sequential()
self.output.add_module('final_conv', nn.Conv2d(
in_channels=in_channels,
out_channels=num_classes,
kernel_size=1))
self.output.add_module('final_activ', nn.ReLU(inplace=True))
self.output.add_module('final_pool', nn.AvgPool2d(
kernel_size=13,
stride=1))
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
if 'final_conv' in name:
init.normal_(module.weight, mean=0.0, std=0.01)
else:
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = self.output(x)
x = x.view(x.size(0), -1)
return x
def get_squeezenet(version,
residual=False,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create SqueezeNet model with specific parameters.
Parameters:
----------
version : str
Version of SqueezeNet ('1.0' or '1.1').
residual : bool, default False
Whether to use residual connections.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if version == '1.0':
channels = [[128, 128, 256], [256, 384, 384, 512], [512]]
residuals = [[0, 1, 0], [1, 0, 1, 0], [1]]
init_block_kernel_size = 7
init_block_channels = 96
elif version == '1.1':
channels = [[128, 128], [256, 256], [384, 384, 512, 512]]
residuals = [[0, 1], [0, 1], [0, 1, 0, 1]]
init_block_kernel_size = 3
init_block_channels = 64
else:
raise ValueError("Unsupported SqueezeNet version {}".format(version))
if not residual:
residuals = None
net = SqueezeNet(
channels=channels,
residuals=residuals,
init_block_kernel_size=init_block_kernel_size,
init_block_channels=init_block_channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def squeezenet_v1_0(**kwargs):
"""
SqueezeNet 'vanilla' model from 'SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model
size,' https://arxiv.org/abs/1602.07360.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_squeezenet(version="1.0", residual=False, model_name="squeezenet_v1_0", **kwargs)
def squeezenet_v1_1(**kwargs):
"""
SqueezeNet v1.1 model from 'SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model
size,' https://arxiv.org/abs/1602.07360.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_squeezenet(version="1.1", residual=False, model_name="squeezenet_v1_1", **kwargs)
def squeezeresnet_v1_0(**kwargs):
"""
SqueezeNet model with residual connections from 'SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and
<0.5MB model size,' https://arxiv.org/abs/1602.07360.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_squeezenet(version="1.0", residual=True, model_name="squeezeresnet_v1_0", **kwargs)
def squeezeresnet_v1_1(**kwargs):
"""
SqueezeNet v1.1 model with residual connections from 'SqueezeNet: AlexNet-level accuracy with 50x fewer parameters
and <0.5MB model size,' https://arxiv.org/abs/1602.07360.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_squeezenet(version="1.1", residual=True, model_name="squeezeresnet_v1_1", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
pretrained = False
models = [
squeezenet_v1_0,
squeezenet_v1_1,
squeezeresnet_v1_0,
squeezeresnet_v1_1,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != squeezenet_v1_0 or weight_count == 1248424)
assert (model != squeezenet_v1_1 or weight_count == 1235496)
assert (model != squeezeresnet_v1_0 or weight_count == 1248424)
assert (model != squeezeresnet_v1_1 or weight_count == 1235496)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 12,164 | 30.929134 | 118 | py |
null | qimera-main/pytorchcv/models/squeezenext.py | """
SqueezeNext for ImageNet-1K, implemented in PyTorch.
Original paper: 'SqueezeNext: Hardware-Aware Neural Network Design,' https://arxiv.org/abs/1803.10615.
"""
__all__ = ['SqueezeNext', 'sqnxt23_w1', 'sqnxt23_w3d2', 'sqnxt23_w2', 'sqnxt23v5_w1', 'sqnxt23v5_w3d2', 'sqnxt23v5_w2']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import ConvBlock, conv1x1_block, conv7x7_block
class SqnxtUnit(nn.Module):
"""
SqueezeNext unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
"""
def __init__(self,
in_channels,
out_channels,
stride):
super(SqnxtUnit, self).__init__()
if stride == 2:
reduction_den = 1
self.resize_identity = True
elif in_channels > out_channels:
reduction_den = 4
self.resize_identity = True
else:
reduction_den = 2
self.resize_identity = False
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=(in_channels // reduction_den),
stride=stride,
bias=True)
self.conv2 = conv1x1_block(
in_channels=(in_channels // reduction_den),
out_channels=(in_channels // (2 * reduction_den)),
bias=True)
self.conv3 = ConvBlock(
in_channels=(in_channels // (2 * reduction_den)),
out_channels=(in_channels // reduction_den),
kernel_size=(1, 3),
stride=1,
padding=(0, 1),
bias=True)
self.conv4 = ConvBlock(
in_channels=(in_channels // reduction_den),
out_channels=(in_channels // reduction_den),
kernel_size=(3, 1),
stride=1,
padding=(1, 0),
bias=True)
self.conv5 = conv1x1_block(
in_channels=(in_channels // reduction_den),
out_channels=out_channels,
bias=True)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
bias=True)
self.activ = nn.ReLU(inplace=True)
def forward(self, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.conv4(x)
x = self.conv5(x)
x = x + identity
x = self.activ(x)
return x
class SqnxtInitBlock(nn.Module):
"""
SqueezeNext specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(SqnxtInitBlock, self).__init__()
self.conv = conv7x7_block(
in_channels=in_channels,
out_channels=out_channels,
stride=2,
padding=1,
bias=True)
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=2,
ceil_mode=True)
def forward(self, x):
x = self.conv(x)
x = self.pool(x)
return x
class SqueezeNext(nn.Module):
"""
SqueezeNext model from 'SqueezeNext: Hardware-Aware Neural Network Design,' https://arxiv.org/abs/1803.10615.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
final_block_channels : int
Number of output channels for the final block of the feature extractor.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
final_block_channels,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(SqueezeNext, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", SqnxtInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stride = 2 if (j == 0) and (i != 0) else 1
stage.add_module("unit{}".format(j + 1), SqnxtUnit(
in_channels=in_channels,
out_channels=out_channels,
stride=stride))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_block', conv1x1_block(
in_channels=in_channels,
out_channels=final_block_channels,
bias=True))
in_channels = final_block_channels
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_squeezenext(version,
width_scale,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create SqueezeNext model with specific parameters.
Parameters:
----------
version : str
Version of SqueezeNet ('23' or '23v5').
width_scale : float
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
init_block_channels = 64
final_block_channels = 128
channels_per_layers = [32, 64, 128, 256]
if version == '23':
layers = [6, 6, 8, 1]
elif version == '23v5':
layers = [2, 4, 14, 1]
else:
raise ValueError("Unsupported SqueezeNet version {}".format(version))
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if width_scale != 1:
channels = [[int(cij * width_scale) for cij in ci] for ci in channels]
init_block_channels = int(init_block_channels * width_scale)
final_block_channels = int(final_block_channels * width_scale)
net = SqueezeNext(
channels=channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def sqnxt23_w1(**kwargs):
"""
1.0-SqNxt-23 model from 'SqueezeNext: Hardware-Aware Neural Network Design,' https://arxiv.org/abs/1803.10615.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_squeezenext(version="23", width_scale=1.0, model_name="sqnxt23_w1", **kwargs)
def sqnxt23_w3d2(**kwargs):
"""
1.5-SqNxt-23 model from 'SqueezeNext: Hardware-Aware Neural Network Design,' https://arxiv.org/abs/1803.10615.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_squeezenext(version="23", width_scale=1.5, model_name="sqnxt23_w3d2", **kwargs)
def sqnxt23_w2(**kwargs):
"""
2.0-SqNxt-23 model from 'SqueezeNext: Hardware-Aware Neural Network Design,' https://arxiv.org/abs/1803.10615.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_squeezenext(version="23", width_scale=2.0, model_name="sqnxt23_w2", **kwargs)
def sqnxt23v5_w1(**kwargs):
"""
1.0-SqNxt-23v5 model from 'SqueezeNext: Hardware-Aware Neural Network Design,' https://arxiv.org/abs/1803.10615.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_squeezenext(version="23v5", width_scale=1.0, model_name="sqnxt23v5_w1", **kwargs)
def sqnxt23v5_w3d2(**kwargs):
"""
1.5-SqNxt-23v5 model from 'SqueezeNext: Hardware-Aware Neural Network Design,' https://arxiv.org/abs/1803.10615.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_squeezenext(version="23v5", width_scale=1.5, model_name="sqnxt23v5_w3d2", **kwargs)
def sqnxt23v5_w2(**kwargs):
"""
2.0-SqNxt-23v5 model from 'SqueezeNext: Hardware-Aware Neural Network Design,' https://arxiv.org/abs/1803.10615.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_squeezenext(version="23v5", width_scale=2.0, model_name="sqnxt23v5_w2", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
sqnxt23_w1,
sqnxt23_w3d2,
sqnxt23_w2,
sqnxt23v5_w1,
sqnxt23v5_w3d2,
sqnxt23v5_w2,
]
for model in models:
net = model(pretrained=pretrained)
# net.eval()
net.train()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != sqnxt23_w1 or weight_count == 724056)
assert (model != sqnxt23_w3d2 or weight_count == 1511824)
assert (model != sqnxt23_w2 or weight_count == 2583752)
assert (model != sqnxt23v5_w1 or weight_count == 921816)
assert (model != sqnxt23v5_w3d2 or weight_count == 1953616)
assert (model != sqnxt23v5_w2 or weight_count == 3366344)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 12,238 | 30.543814 | 119 | py |
null | qimera-main/pytorchcv/models/superpointnet.py | """
SuperPointNet for HPatches (image matching), implemented in PyTorch.
Original paper: 'SuperPoint: Self-Supervised Interest Point Detection and Description,'
https://arxiv.org/abs/1712.07629.
"""
__all__ = ['SuperPointNet', 'superpointnet']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
from .common import conv1x1, conv3x3_block
class SPHead(nn.Module):
"""
SuperPointNet head block.
Parameters:
----------
in_channels : int
Number of input channels.
mid_channels : int
Number of middle channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
mid_channels,
out_channels):
super(SPHead, self).__init__()
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=mid_channels,
bias=True,
use_bn=False)
self.conv2 = conv1x1(
in_channels=mid_channels,
out_channels=out_channels,
bias=True)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class SPDetector(nn.Module):
"""
SuperPointNet detector.
Parameters:
----------
in_channels : int
Number of input channels.
mid_channels : int
Number of middle channels.
conf_thresh : float, default 0.015
Confidence threshold.
nms_dist : int, default 4
NMS distance.
border_size : int, default 4
Image border size to remove points.
reduction : int, default 8
Feature reduction factor.
"""
def __init__(self,
in_channels,
mid_channels,
conf_thresh=0.015,
nms_dist=4,
border_size=4,
reduction=8):
super(SPDetector, self).__init__()
self.conf_thresh = conf_thresh
self.nms_dist = nms_dist
self.border_size = border_size
self.reduction = reduction
num_classes = reduction * reduction + 1
self.detector = SPHead(
in_channels=in_channels,
mid_channels=mid_channels,
out_channels=num_classes)
def forward(self, x):
batch = x.size(0)
x_height, x_width = x.size()[-2:]
img_height = x_height * self.reduction
img_width = x_width * self.reduction
semi = self.detector(x)
dense = semi.softmax(dim=1)
nodust = dense[:, :-1, :, :]
heatmap = nodust.permute(0, 2, 3, 1)
heatmap = heatmap.reshape((-1, x_height, x_width, self.reduction, self.reduction))
heatmap = heatmap.permute(0, 1, 3, 2, 4)
heatmap = heatmap.reshape((-1, 1, x_height * self.reduction, x_width * self.reduction))
heatmap_mask = (heatmap >= self.conf_thresh)
pad = self.nms_dist
bord = self.border_size + pad
heatmap_mask2 = F.pad(heatmap_mask, pad=(pad, pad, pad, pad))
pts_list = []
confs_list = []
for i in range(batch):
heatmap_i = heatmap[i, 0]
heatmap_mask_i = heatmap_mask[i, 0]
heatmap_mask2_i = heatmap_mask2[i, 0]
src_pts = torch.nonzero(heatmap_mask_i)
src_confs = torch.masked_select(heatmap_i, heatmap_mask_i)
src_inds = torch.argsort(src_confs, descending=True)
dst_inds = torch.zeros_like(src_inds)
dst_pts_count = 0
for ind_j in src_inds:
pt = src_pts[ind_j] + pad
assert (pad <= pt[0] < heatmap_mask2_i.shape[0] - pad)
assert (pad <= pt[1] < heatmap_mask2_i.shape[1] - pad)
assert (0 <= pt[0] - pad < img_height)
assert (0 <= pt[1] - pad < img_width)
if heatmap_mask2_i[pt[0], pt[1]] == 1:
heatmap_mask2_i[(pt[0] - pad):(pt[0] + pad + 1), (pt[1] - pad):(pt[1] + pad + 1)] = 0
if (bord < pt[0] - pad <= img_height - bord) and (bord < pt[1] - pad <= img_width - bord):
dst_inds[dst_pts_count] = ind_j
dst_pts_count += 1
dst_inds = dst_inds[:dst_pts_count]
dst_pts = torch.index_select(src_pts, dim=0, index=dst_inds)
dst_confs = torch.index_select(src_confs, dim=0, index=dst_inds)
pts_list.append(dst_pts)
confs_list.append(dst_confs)
return pts_list, confs_list
class SPDescriptor(nn.Module):
"""
SuperPointNet descriptor generator.
Parameters:
----------
in_channels : int
Number of input channels.
mid_channels : int
Number of middle channels.
descriptor_length : int, default 256
Descriptor length.
transpose_descriptors : bool, default True
Whether transpose descriptors with respect to points.
reduction : int, default 8
Feature reduction factor.
"""
def __init__(self,
in_channels,
mid_channels,
descriptor_length=256,
transpose_descriptors=True,
reduction=8):
super(SPDescriptor, self).__init__()
self.desc_length = descriptor_length
self.transpose_descriptors = transpose_descriptors
self.reduction = reduction
self.head = SPHead(
in_channels=in_channels,
mid_channels=mid_channels,
out_channels=descriptor_length)
def forward(self, x, pts_list):
x_height, x_width = x.size()[-2:]
coarse_desc_map = self.head(x)
coarse_desc_map = F.normalize(coarse_desc_map)
descriptors_list = []
for i, pts in enumerate(pts_list):
pts = pts.float()
pts[:, 0] = pts[:, 0] / (0.5 * x_height * self.reduction) - 1.0
pts[:, 1] = pts[:, 1] / (0.5 * x_width * self.reduction) - 1.0
if self.transpose_descriptors:
pts = torch.index_select(pts, dim=1, index=torch.tensor([1, 0], device=pts.device))
pts = pts.unsqueeze(0).unsqueeze(0)
descriptors = F.grid_sample(coarse_desc_map[i:(i + 1)], pts)
descriptors = descriptors.squeeze(0).squeeze(1)
descriptors = descriptors.transpose(0, 1)
descriptors = F.normalize(descriptors)
descriptors_list.append(descriptors)
return descriptors_list
class SuperPointNet(nn.Module):
"""
SuperPointNet model from 'SuperPoint: Self-Supervised Interest Point Detection and Description,'
https://arxiv.org/abs/1712.07629.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
final_block_channels : int
Number of output channels for the final units.
transpose_descriptors : bool, default True
Whether transpose descriptors with respect to points.
in_channels : int, default 1
Number of input channels.
"""
def __init__(self,
channels,
final_block_channels,
transpose_descriptors=True,
in_channels=1):
super(SuperPointNet, self).__init__()
self.features = nn.Sequential()
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
if (j == 0) and (i != 0):
stage.add_module("reduce{}".format(i + 1), nn.MaxPool2d(
kernel_size=2,
stride=2))
stage.add_module("unit{}".format(j + 1), conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
bias=True,
use_bn=False))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.detector = SPDetector(
in_channels=in_channels,
mid_channels=final_block_channels)
self.descriptor = SPDescriptor(
in_channels=in_channels,
mid_channels=final_block_channels,
transpose_descriptors=transpose_descriptors)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
assert (x.size(1) == 1)
x = self.features(x)
pts_list, confs_list = self.detector(x)
descriptors_list = self.descriptor(x, pts_list)
return pts_list, confs_list, descriptors_list
def get_superpointnet(model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create SuperPointNet model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
channels_per_layers = [64, 64, 128, 128]
layers = [2, 2, 2, 2]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
final_block_channels = 256
net = SuperPointNet(
channels=channels,
final_block_channels=final_block_channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def superpointnet(**kwargs):
"""
SuperPointNet model from 'SuperPoint: Self-Supervised Interest Point Detection and Description,'
https://arxiv.org/abs/1712.07629.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_superpointnet(model_name="superpointnet", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
superpointnet,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != superpointnet or weight_count == 1300865)
# x = torch.randn(1, 1, 224, 224)
x = torch.randn(1, 1, 1000, 2000)
y = net(x)
# y.sum().backward()
assert (len(y) == 3)
if __name__ == "__main__":
_test()
| 11,418 | 31.719198 | 115 | py |
null | qimera-main/pytorchcv/models/vgg.py | """
VGG for ImageNet-1K, implemented in PyTorch.
Original paper: 'Very Deep Convolutional Networks for Large-Scale Image Recognition,'
https://arxiv.org/abs/1409.1556.
"""
__all__ = ['VGG', 'vgg11', 'vgg13', 'vgg16', 'vgg19', 'bn_vgg11', 'bn_vgg13', 'bn_vgg16', 'bn_vgg19', 'bn_vgg11b',
'bn_vgg13b', 'bn_vgg16b', 'bn_vgg19b']
import os
import torch.nn as nn
import torch.nn.init as init
from .common import conv3x3_block
class VGGDense(nn.Module):
"""
VGG specific dense block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(VGGDense, self).__init__()
self.fc = nn.Linear(
in_features=in_channels,
out_features=out_channels)
self.activ = nn.ReLU(inplace=True)
self.dropout = nn.Dropout(p=0.5)
def forward(self, x):
x = self.fc(x)
x = self.activ(x)
x = self.dropout(x)
return x
class VGGOutputBlock(nn.Module):
"""
VGG specific output block.
Parameters:
----------
in_channels : int
Number of input channels.
classes : int
Number of classification classes.
"""
def __init__(self,
in_channels,
classes):
super(VGGOutputBlock, self).__init__()
mid_channels = 4096
self.fc1 = VGGDense(
in_channels=in_channels,
out_channels=mid_channels)
self.fc2 = VGGDense(
in_channels=mid_channels,
out_channels=mid_channels)
self.fc3 = nn.Linear(
in_features=mid_channels,
out_features=classes)
def forward(self, x):
x = self.fc1(x)
x = self.fc2(x)
x = self.fc3(x)
return x
class VGG(nn.Module):
"""
VGG models from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,'
https://arxiv.org/abs/1409.1556.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
bias : bool, default True
Whether the convolution layer uses a bias vector.
use_bn : bool, default False
Whether to use BatchNorm layers.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
bias=True,
use_bn=False,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(VGG, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
stage.add_module("unit{}".format(j + 1), conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
bias=bias,
use_bn=use_bn))
in_channels = out_channels
stage.add_module("pool{}".format(i + 1), nn.MaxPool2d(
kernel_size=2,
stride=2,
padding=0))
self.features.add_module("stage{}".format(i + 1), stage)
self.output = VGGOutputBlock(
in_channels=(in_channels * 7 * 7),
classes=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_vgg(blocks,
bias=True,
use_bn=False,
model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create VGG model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
bias : bool, default True
Whether the convolution layer uses a bias vector.
use_bn : bool, default False
Whether to use BatchNorm layers.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
if blocks == 11:
layers = [1, 1, 2, 2, 2]
elif blocks == 13:
layers = [2, 2, 2, 2, 2]
elif blocks == 16:
layers = [2, 2, 3, 3, 3]
elif blocks == 19:
layers = [2, 2, 4, 4, 4]
else:
raise ValueError("Unsupported VGG with number of blocks: {}".format(blocks))
channels_per_layers = [64, 128, 256, 512, 512]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = VGG(
channels=channels,
bias=bias,
use_bn=use_bn,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def vgg11(**kwargs):
"""
VGG-11 model from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,'
https://arxiv.org/abs/1409.1556.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_vgg(blocks=11, model_name="vgg11", **kwargs)
def vgg13(**kwargs):
"""
VGG-13 model from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,'
https://arxiv.org/abs/1409.1556.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_vgg(blocks=13, model_name="vgg13", **kwargs)
def vgg16(**kwargs):
"""
VGG-16 model from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,'
https://arxiv.org/abs/1409.1556.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_vgg(blocks=16, model_name="vgg16", **kwargs)
def vgg19(**kwargs):
"""
VGG-19 model from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,'
https://arxiv.org/abs/1409.1556.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_vgg(blocks=19, model_name="vgg19", **kwargs)
def bn_vgg11(**kwargs):
"""
VGG-11 model with batch normalization from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,'
https://arxiv.org/abs/1409.1556.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_vgg(blocks=11, bias=False, use_bn=True, model_name="bn_vgg11", **kwargs)
def bn_vgg13(**kwargs):
"""
VGG-13 model with batch normalization from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,'
https://arxiv.org/abs/1409.1556.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_vgg(blocks=13, bias=False, use_bn=True, model_name="bn_vgg13", **kwargs)
def bn_vgg16(**kwargs):
"""
VGG-16 model with batch normalization from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,'
https://arxiv.org/abs/1409.1556.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_vgg(blocks=16, bias=False, use_bn=True, model_name="bn_vgg16", **kwargs)
def bn_vgg19(**kwargs):
"""
VGG-19 model with batch normalization from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,'
https://arxiv.org/abs/1409.1556.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_vgg(blocks=19, bias=False, use_bn=True, model_name="bn_vgg19", **kwargs)
def bn_vgg11b(**kwargs):
"""
VGG-11 model with batch normalization and biases in convolution layers from 'Very Deep Convolutional Networks for
Large-Scale Image Recognition,' https://arxiv.org/abs/1409.1556.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_vgg(blocks=11, bias=True, use_bn=True, model_name="bn_vgg11b", **kwargs)
def bn_vgg13b(**kwargs):
"""
VGG-13 model with batch normalization and biases in convolution layers from 'Very Deep Convolutional Networks for
Large-Scale Image Recognition,' https://arxiv.org/abs/1409.1556.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_vgg(blocks=13, bias=True, use_bn=True, model_name="bn_vgg13b", **kwargs)
def bn_vgg16b(**kwargs):
"""
VGG-16 model with batch normalization and biases in convolution layers from 'Very Deep Convolutional Networks for
Large-Scale Image Recognition,' https://arxiv.org/abs/1409.1556.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_vgg(blocks=16, bias=True, use_bn=True, model_name="bn_vgg16b", **kwargs)
def bn_vgg19b(**kwargs):
"""
VGG-19 model with batch normalization and biases in convolution layers from 'Very Deep Convolutional Networks for
Large-Scale Image Recognition,' https://arxiv.org/abs/1409.1556.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_vgg(blocks=19, bias=True, use_bn=True, model_name="bn_vgg19b", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
pretrained = False
models = [
vgg11,
vgg13,
vgg16,
vgg19,
bn_vgg11,
bn_vgg13,
bn_vgg16,
bn_vgg19,
bn_vgg11b,
bn_vgg13b,
bn_vgg16b,
bn_vgg19b,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != vgg11 or weight_count == 132863336)
assert (model != vgg13 or weight_count == 133047848)
assert (model != vgg16 or weight_count == 138357544)
assert (model != vgg19 or weight_count == 143667240)
assert (model != bn_vgg11 or weight_count == 132866088)
assert (model != bn_vgg13 or weight_count == 133050792)
assert (model != bn_vgg16 or weight_count == 138361768)
assert (model != bn_vgg19 or weight_count == 143672744)
assert (model != bn_vgg11b or weight_count == 132868840)
assert (model != bn_vgg13b or weight_count == 133053736)
assert (model != bn_vgg16b or weight_count == 138365992)
assert (model != bn_vgg19b or weight_count == 143678248)
x = torch.randn(1, 3, 224, 224)
y = net(x)
y.sum().backward()
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
| 13,528 | 29.678005 | 117 | py |