用kafka接收消息
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

135 lines
5.2KB

  1. "ESPNetv2: A Light-weight, Power Efficient, and General Purpose for Semantic Segmentation"
  2. import torch
  3. import torch.nn as nn
  4. import torch.nn.functional as F
  5. from core.models.base_models import eespnet, EESP
  6. from core.nn import _ConvBNPReLU, _BNPReLU
  7. class ESPNetV2(nn.Module):
  8. r"""ESPNetV2
  9. Parameters
  10. ----------
  11. nclass : int
  12. Number of categories for the training dataset.
  13. backbone : string
  14. Pre-trained dilated backbone network type (default:'resnet50'; 'resnet50',
  15. 'resnet101' or 'resnet152').
  16. norm_layer : object
  17. Normalization layer used in backbone network (default: :class:`nn.BatchNorm`;
  18. for Synchronized Cross-GPU BachNormalization).
  19. aux : bool
  20. Auxiliary loss.
  21. Reference:
  22. Sachin Mehta, et al. "ESPNetv2: A Light-weight, Power Efficient, and General Purpose Convolutional Neural Network."
  23. arXiv preprint arXiv:1811.11431 (2018).
  24. """
  25. def __init__(self, nclass, backbone='', aux=False, jpu=False, pretrained_base=False, **kwargs):
  26. super(ESPNetV2, self).__init__()
  27. self.pretrained = eespnet(pretrained=pretrained_base, **kwargs)
  28. self.proj_L4_C = _ConvBNPReLU(256, 128, 1, **kwargs)
  29. self.pspMod = nn.Sequential(
  30. EESP(256, 128, stride=1, k=4, r_lim=7, **kwargs),
  31. _PSPModule(128, 128, **kwargs))
  32. self.project_l3 = nn.Sequential(
  33. nn.Dropout2d(0.1),
  34. nn.Conv2d(128, nclass, 1, bias=False))
  35. self.act_l3 = _BNPReLU(nclass, **kwargs)
  36. self.project_l2 = _ConvBNPReLU(64 + nclass, nclass, 1, **kwargs)
  37. self.project_l1 = nn.Sequential(
  38. nn.Dropout2d(0.1),
  39. nn.Conv2d(32 + nclass, nclass, 1, bias=False))
  40. self.aux = aux
  41. self.__setattr__('exclusive', ['proj_L4_C', 'pspMod', 'project_l3', 'act_l3', 'project_l2', 'project_l1'])
  42. def forward(self, x):
  43. size = x.size()[2:]
  44. out_l1, out_l2, out_l3, out_l4 = self.pretrained(x, seg=True)
  45. out_l4_proj = self.proj_L4_C(out_l4)
  46. up_l4_to_l3 = F.interpolate(out_l4_proj, scale_factor=2, mode='bilinear', align_corners=True)
  47. merged_l3_upl4 = self.pspMod(torch.cat([out_l3, up_l4_to_l3], 1))
  48. proj_merge_l3_bef_act = self.project_l3(merged_l3_upl4)
  49. proj_merge_l3 = self.act_l3(proj_merge_l3_bef_act)
  50. out_up_l3 = F.interpolate(proj_merge_l3, scale_factor=2, mode='bilinear', align_corners=True)
  51. merge_l2 = self.project_l2(torch.cat([out_l2, out_up_l3], 1))
  52. out_up_l2 = F.interpolate(merge_l2, scale_factor=2, mode='bilinear', align_corners=True)
  53. merge_l1 = self.project_l1(torch.cat([out_l1, out_up_l2], 1))
  54. outputs = list()
  55. merge1_l1 = F.interpolate(merge_l1, scale_factor=2, mode='bilinear', align_corners=True)
  56. outputs.append(merge1_l1)
  57. if self.aux:
  58. # different from paper
  59. auxout = F.interpolate(proj_merge_l3_bef_act, size, mode='bilinear', align_corners=True)
  60. outputs.append(auxout)
  61. #return tuple(outputs)
  62. return outputs[0]
  63. # different from PSPNet
  64. class _PSPModule(nn.Module):
  65. def __init__(self, in_channels, out_channels=1024, sizes=(1, 2, 4, 8), **kwargs):
  66. super(_PSPModule, self).__init__()
  67. self.stages = nn.ModuleList(
  68. [nn.Conv2d(in_channels, in_channels, 3, 1, 1, groups=in_channels, bias=False) for _ in sizes])
  69. self.project = _ConvBNPReLU(in_channels * (len(sizes) + 1), out_channels, 1, 1, **kwargs)
  70. def forward(self, x):
  71. size = x.size()[2:]
  72. feats = [x]
  73. for stage in self.stages:
  74. x = F.avg_pool2d(x, kernel_size=3, stride=2, padding=1)
  75. upsampled = F.interpolate(stage(x), size, mode='bilinear', align_corners=True)
  76. feats.append(upsampled)
  77. return self.project(torch.cat(feats, dim=1))
  78. def get_espnet(dataset='pascal_voc', backbone='', pretrained=False, root='~/.torch/models',
  79. pretrained_base=False, **kwargs):
  80. acronyms = {
  81. 'pascal_voc': 'pascal_voc',
  82. 'pascal_aug': 'pascal_aug',
  83. 'ade20k': 'ade',
  84. 'coco': 'coco',
  85. 'citys': 'citys',
  86. }
  87. from core.data.dataloader import datasets
  88. model = ESPNetV2(datasets[dataset].NUM_CLASS, backbone=backbone, pretrained_base=pretrained_base, **kwargs)
  89. if pretrained:
  90. from .model_store import get_model_file
  91. device = torch.device(kwargs['local_rank'])
  92. model.load_state_dict(torch.load(get_model_file('espnet_%s_%s' % (backbone, acronyms[dataset]), root=root),
  93. map_location=device))
  94. return model
  95. def get_espnet_citys(**kwargs):
  96. return get_espnet('citys', **kwargs)
  97. if __name__ == '__main__':
  98. #model = get_espnet_citys()
  99. input = torch.rand(2, 3, 224, 224)
  100. model =ESPNetV2(4, pretrained_base=False)
  101. # target = torch.zeros(4, 512, 512).cuda()
  102. # model.eval()
  103. # print(model)
  104. loss = model(input)
  105. print(loss, loss.shape)
  106. # from torchsummary import summary
  107. #
  108. # summary(model, (3, 224, 224)) # 打印表格,按顺序输出每层的输出形状和参数
  109. import torch
  110. from thop import profile
  111. from torchsummary import summary
  112. flop, params = profile(model, input_size=(1, 3, 512, 512))
  113. print('flops:{:.3f}G\nparams:{:.3f}M'.format(flop / 1e9, params / 1e6))