models.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. import math
  2. import torch
  3. import torch.nn.functional as F
  4. from torch import nn
  5. from torch.nn import Parameter
  6. from .config import device, num_classes
  7. def create_model(opt):
  8. if opt.model == 'pix2pixHD':
  9. #from .pix2pixHD_model import Pix2PixHDModel, InferenceModel
  10. from .fs_model import fsModel
  11. model = fsModel()
  12. else:
  13. from .ui_model import UIModel
  14. model = UIModel()
  15. model.initialize(opt)
  16. if opt.verbose:
  17. print("model [%s] was created" % (model.name()))
  18. if opt.isTrain and len(opt.gpu_ids) and not opt.fp16:
  19. model = torch.nn.DataParallel(model, device_ids=opt.gpu_ids)
  20. return model
  21. class SEBlock(nn.Module):
  22. def __init__(self, channel, reduction=16):
  23. super(SEBlock, self).__init__()
  24. self.avg_pool = nn.AdaptiveAvgPool2d(1)
  25. self.fc = nn.Sequential(
  26. nn.Linear(channel, channel // reduction),
  27. nn.PReLU(),
  28. nn.Linear(channel // reduction, channel),
  29. nn.Sigmoid()
  30. )
  31. def forward(self, x):
  32. b, c, _, _ = x.size()
  33. y = self.avg_pool(x).view(b, c)
  34. y = self.fc(y).view(b, c, 1, 1)
  35. return x * y
  36. class IRBlock(nn.Module):
  37. expansion = 1
  38. def __init__(self, inplanes, planes, stride=1, downsample=None, use_se=True):
  39. super(IRBlock, self).__init__()
  40. self.bn0 = nn.BatchNorm2d(inplanes)
  41. self.conv1 = conv3x3(inplanes, inplanes)
  42. self.bn1 = nn.BatchNorm2d(inplanes)
  43. self.prelu = nn.PReLU()
  44. self.conv2 = conv3x3(inplanes, planes, stride)
  45. self.bn2 = nn.BatchNorm2d(planes)
  46. self.downsample = downsample
  47. self.stride = stride
  48. self.use_se = use_se
  49. if self.use_se:
  50. self.se = SEBlock(planes)
  51. def forward(self, x):
  52. residual = x
  53. out = self.bn0(x)
  54. out = self.conv1(out)
  55. out = self.bn1(out)
  56. out = self.prelu(out)
  57. out = self.conv2(out)
  58. out = self.bn2(out)
  59. if self.use_se:
  60. out = self.se(out)
  61. if self.downsample is not None:
  62. residual = self.downsample(x)
  63. out += residual
  64. out = self.prelu(out)
  65. return out
  66. class ResNet(nn.Module):
  67. def __init__(self, block, layers, use_se=True):
  68. self.inplanes = 64
  69. self.use_se = use_se
  70. super(ResNet, self).__init__()
  71. self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, bias=False)
  72. self.bn1 = nn.BatchNorm2d(64)
  73. self.prelu = nn.PReLU()
  74. self.maxpool = nn.MaxPool2d(kernel_size=2, stride=2)
  75. self.layer1 = self._make_layer(block, 64, layers[0])
  76. self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
  77. self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
  78. self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
  79. self.bn2 = nn.BatchNorm2d(512)
  80. self.dropout = nn.Dropout()
  81. self.fc = nn.Linear(512 * 7 * 7, 512)
  82. self.bn3 = nn.BatchNorm1d(512)
  83. for m in self.modules():
  84. if isinstance(m, nn.Conv2d):
  85. nn.init.xavier_normal_(m.weight)
  86. elif isinstance(m, nn.BatchNorm2d) or isinstance(m, nn.BatchNorm1d):
  87. nn.init.constant_(m.weight, 1)
  88. nn.init.constant_(m.bias, 0)
  89. elif isinstance(m, nn.Linear):
  90. nn.init.xavier_normal_(m.weight)
  91. nn.init.constant_(m.bias, 0)
  92. def _make_layer(self, block, planes, blocks, stride=1):
  93. downsample = None
  94. if stride != 1 or self.inplanes != planes * block.expansion:
  95. downsample = nn.Sequential(
  96. nn.Conv2d(self.inplanes, planes * block.expansion,
  97. kernel_size=1, stride=stride, bias=False),
  98. nn.BatchNorm2d(planes * block.expansion),
  99. )
  100. layers = []
  101. layers.append(block(self.inplanes, planes, stride, downsample, use_se=self.use_se))
  102. self.inplanes = planes
  103. for i in range(1, blocks):
  104. layers.append(block(self.inplanes, planes, use_se=self.use_se))
  105. return nn.Sequential(*layers)
  106. def forward(self, x):
  107. x = self.conv1(x)
  108. x = self.bn1(x)
  109. x = self.prelu(x)
  110. x = self.maxpool(x)
  111. x = self.layer1(x)
  112. x = self.layer2(x)
  113. x = self.layer3(x)
  114. x = self.layer4(x)
  115. x = self.bn2(x)
  116. x = self.dropout(x)
  117. x = x.view(x.size(0), -1)
  118. x = self.fc(x)
  119. x = self.bn3(x)
  120. return x
  121. class ArcMarginModel(nn.Module):
  122. def __init__(self, args):
  123. super(ArcMarginModel, self).__init__()
  124. self.weight = Parameter(torch.FloatTensor(num_classes, args.emb_size))
  125. nn.init.xavier_uniform_(self.weight)
  126. self.easy_margin = args.easy_margin
  127. self.m = args.margin_m
  128. self.s = args.margin_s
  129. self.cos_m = math.cos(self.m)
  130. self.sin_m = math.sin(self.m)
  131. self.th = math.cos(math.pi - self.m)
  132. self.mm = math.sin(math.pi - self.m) * self.m
  133. def forward(self, input, label):
  134. x = F.normalize(input)
  135. W = F.normalize(self.weight)
  136. cosine = F.linear(x, W)
  137. sine = torch.sqrt(1.0 - torch.pow(cosine, 2))
  138. phi = cosine * self.cos_m - sine * self.sin_m # cos(theta + m)
  139. if self.easy_margin:
  140. phi = torch.where(cosine > 0, phi, cosine)
  141. else:
  142. phi = torch.where(cosine > self.th, phi, cosine - self.mm)
  143. one_hot = torch.zeros(cosine.size(), device=device)
  144. one_hot.scatter_(1, label.view(-1, 1).long(), 1)
  145. output = (one_hot * phi) + ((1.0 - one_hot) * cosine)
  146. output *= self.s
  147. return output