text: """
  Creates a MobileNetV2 Model as defined in:
  Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen. (2018). 
  MobileNetV2: Inverted Residuals and Linear Bottlenecks
  arXiv preprint arXiv:1801.04381.
  import from https://github.com/tonylins/pytorch-mobilenet-v2
  """
  
  import torch
  import torch.nn as nn
  import math
  import os.path
  
  __all__ = ['mobilenetv2']
  
  
  def _make_divisible(v, divisor, min_value=None):
      """
      This function is taken from the original tf repo.
      It ensures that all layers have a channel number that is divisible by 8
      It can be seen here:
      https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
      :param v:
      :param divisor:
      :param min_value:
      :return:
      """
      if min_value is None:
          min_value = divisor
      new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
      # Make sure that round down does not go down by more than 10%.
      if new_v < 0.9 * v:
          new_v += divisor
      return new_v
  
  
  def conv_3x3_bn(inp, oup, stride):
      return nn.Sequential(
          nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
          nn.BatchNorm2d(oup),
          nn.ReLU6(inplace=True)
      )
  
  
  def conv_1x1_bn(inp, oup):
      return nn.Sequential(
          nn.Conv2d(inp, oup, 1, 1, 0, bias=False),
          nn.BatchNorm2d(oup),
          nn.ReLU6(inplace=True)
      )
  
  
  class InvertedResidual(nn.Module):
      def __init__(self, inp, oup, stride, expand_ratio):
          super(InvertedResidual, self).__init__()
          assert stride in [1, 2]
  
          hidden_dim = round(inp * expand_ratio)
          self.identity = stride == 1 and inp == oup
  
          if expand_ratio == 1:
              self.conv = nn.Sequential(
                  # dw
                  nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),
                  nn.BatchNorm2d(hidden_dim),
                  nn.ReLU6(inplace=True),
                  # pw-linear
                  nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
                  nn.BatchNorm2d(oup),
              )
          else:
              self.conv = nn.Sequential(
                  # pw
                  nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False),
                  nn.BatchNorm2d(hidden_dim),
                  nn.ReLU6(inplace=True),
                  # dw
                  nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),
                  nn.BatchNorm2d(hidden_dim),
                  nn.ReLU6(inplace=True),
                  # pw-linear
                  nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
                  nn.BatchNorm2d(oup),
              )
  
      def forward(self, x):
          if self.identity:
              return x + self.conv(x)
          else:
              return self.conv(x)
  
  
  class fc_block(nn.Module):
      def __init__(self, inplanes, planes, drop_rate=0.15):
          super(fc_block, self).__init__()
          self.fc = nn.Linear(inplanes, planes)
          self.bn = nn.BatchNorm1d(planes)
          if drop_rate > 0:
              self.dropout = nn.Dropout(drop_rate)
          self.relu = nn.ReLU(inplace=True)
          self.drop_rate = drop_rate
  
      def forward(self, x):
          x = self.fc(x)
          x = self.bn(x)
          if self.drop_rate > 0:
              x = self.dropout(x)
          x = self.relu(x)
          return x
  
  
  class MobileNetV2(nn.Module):
      def __init__(self, num_attributes=2, input_size=224, width_mult=0.01):
          super(MobileNetV2, self).__init__()
          # setting of inverted residual blocks
          self.cfgs = [
              # t, c, n, s
              [1,  16, 1, 1],
              [1,  24, 2, 2],
              [1,  32, 3, 2],
              [1,  64, 4, 2],
              # [6,  96, 3, 1],
              # [6, 160, 3, 2],
              # [6, 320, 1, 1],
          ]
  
          # building first layer
          input_channel = _make_divisible(32 * width_mult, 8)
          layers = [conv_3x3_bn(3, input_channel, 2)]
          # building inverted residual blocks
          block = InvertedResidual
          for t, c, n, s in self.cfgs:
              output_channel = _make_divisible(c * width_mult, 8)
              layers.append(block(input_channel, output_channel, s, t))
              input_channel = output_channel
              for i in range(1, n):
                  layers.append(block(input_channel, output_channel, 1, t))
                  input_channel = output_channel
          self.features = nn.Sequential(*layers)
          # building last several layers
          output_channel = _make_divisible(1280 * width_mult, 8) if width_mult > 1.0 else 1280
          self.conv = conv_1x1_bn(input_channel, output_channel)
          self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
          self.stem = fc_block(output_channel, 2)
          for i in range(num_attributes):
              setattr(self, 'classifier' + str(i).zfill(2), nn.Sequential(fc_block(2, 2), nn.Linear(2, 2)))
          self.num_attributes = num_attributes
  
          self._initialize_weights()
  
      def forward(self, x):
          x = self.features(x)
          x = self.conv(x)
          x = self.avgpool(x)
          x = x.view(x.size(0), -1)
          x = self.stem(x)
  
          y = []
          for i in range(self.num_attributes):
              classifier = getattr(self, 'classifier' + str(i).zfill(2))
              y.append(classifier(x))
  
          return y
  
      def _initialize_weights(self):
          for m in self.modules():
              if isinstance(m, nn.Conv2d):
                  n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                  m.weight.data.normal_(0, math.sqrt(2. / n))
                  if m.bias is not None:
                      m.bias.data.zero_()
              elif isinstance(m, nn.BatchNorm2d):
                  m.weight.data.fill_(1)
                  m.bias.data.zero_()
              elif isinstance(m, nn.Linear):
                  n = m.weight.size(1)
                  m.weight.data.normal_(0, 0.01)
                  m.bias.data.zero_()
  
  
  def init_pretrained_weights(model, path=os.path.expanduser('/home/chenxin/disk1/github/face-attribute-prediction/checkpoints/model_best.pth.tar')):
      """
      Initialize model with pretrained weights.
      Layers that don't match with pretrained layers in name or size are kept unchanged.
      """
      #pretrain_dict = model_zoo.load_url(model_url)
      pretrain_dict = torch.load(path)
      model_dict = model.state_dict()
      pretrain_dict = {k: v for k, v in pretrain_dict.items() if k in model_dict and model_dict[k].size() == v.size()}
      model_dict.update(pretrain_dict)
      model.load_state_dict(model_dict)
      print("Initialized model with pretrained weights from {}".format(path))
  
  
  def mobilenetv2(pretrained=True, **kwargs):
      """
      Constructs a MobileNet V2 model
      """
      model = MobileNetV2(**kwargs)
      if pretrained:
          init_pretrained_weights(model)
      return model
  
  