You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

conv_bn.py 7.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  2. #
  3. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  4. #
  5. # Unless required by applicable law or agreed to in writing,
  6. # software distributed under the License is distributed on an
  7. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8. from ...functional import ones, relu, sqrt, sum, zeros
  9. from .. import conv_bn as Float
  10. from .module import QATModule
  11. class _ConvBnActivation2d(Float._ConvBnActivation2d, QATModule):
  12. def get_batch_mean_var(self, inp):
  13. def _sum_channel(inp, axis=0, keepdims=True):
  14. if isinstance(axis, int):
  15. out = sum(inp, axis=axis, keepdims=keepdims)
  16. elif isinstance(axis, tuple):
  17. for idx, elem in enumerate(axis):
  18. out = sum(inp if idx == 0 else out, axis=elem, keepdims=keepdims)
  19. return out
  20. sum1 = _sum_channel(inp, (0, 2, 3))
  21. sum2 = _sum_channel(inp ** 2, (0, 2, 3))
  22. reduce_size = inp.size / inp.shape[1]
  23. batch_mean = sum1 / reduce_size
  24. batch_var = (sum2 - sum1 ** 2 / reduce_size) / reduce_size
  25. return batch_mean, batch_var
  26. def fold_weight_bias(self, bn_mean, bn_var):
  27. # get fold bn conv param
  28. # bn_istd = 1 / bn_std
  29. # w_fold = gamma / bn_std * W
  30. # b_fold = gamma * (b - bn_mean) / bn_std + beta
  31. gamma = self.bn.weight
  32. if gamma is None:
  33. gamma = ones((self.bn.num_features), dtype="float32")
  34. gamma = gamma.reshape(1, -1, 1, 1)
  35. beta = self.bn.bias
  36. if beta is None:
  37. beta = zeros((self.bn.num_features), dtype="float32")
  38. beta = beta.reshape(1, -1, 1, 1)
  39. if bn_mean is None:
  40. bn_mean = zeros((1, self.bn.num_features, 1, 1), dtype="float32")
  41. if bn_var is None:
  42. bn_var = ones((1, self.bn.num_features, 1, 1), dtype="float32")
  43. conv_bias = self.conv.bias
  44. if conv_bias is None:
  45. conv_bias = zeros(self.conv._infer_bias_shape(), dtype="float32")
  46. bn_istd = 1.0 / sqrt(bn_var + self.bn.eps)
  47. # bn_istd = 1 / bn_std
  48. # w_fold = gamma / bn_std * W
  49. scale_factor = gamma * bn_istd
  50. if self.conv.groups == 1:
  51. w_fold = self.conv.weight * scale_factor.reshape(-1, 1, 1, 1)
  52. else:
  53. w_fold = self.conv.weight * scale_factor.reshape(
  54. self.conv.groups, -1, 1, 1, 1
  55. )
  56. w_fold = self.apply_quant_weight(w_fold)
  57. # b_fold = gamma * (b - bn_mean) / bn_std + beta
  58. b_fold = beta + gamma * (conv_bias - bn_mean) * bn_istd
  59. return w_fold, b_fold
  60. def update_running_mean_and_running_var(
  61. self, bn_mean, bn_var, num_elements_per_channel
  62. ):
  63. # update running mean and running var. no grad, use unbiased bn var
  64. bn_mean = bn_mean.detach()
  65. bn_var = (
  66. bn_var.detach() * num_elements_per_channel / (num_elements_per_channel - 1)
  67. )
  68. exponential_average_factor = 1 - self.bn.momentum
  69. self.bn.running_mean *= self.bn.momentum
  70. self.bn.running_mean += exponential_average_factor * bn_mean
  71. self.bn.running_var *= self.bn.momentum
  72. self.bn.running_var += exponential_average_factor * bn_var
  73. def calc_conv_bn_qat(self, inp, approx=True):
  74. if self.training and not approx:
  75. conv = self.conv(inp)
  76. bn_mean, bn_var = self.get_batch_mean_var(conv)
  77. num_elements_per_channel = conv.size / conv.shape[1]
  78. self.update_running_mean_and_running_var(
  79. bn_mean, bn_var, num_elements_per_channel
  80. )
  81. else:
  82. bn_mean, bn_var = self.bn.running_mean, self.bn.running_var
  83. # get gamma and beta in BatchNorm
  84. gamma = self.bn.weight
  85. if gamma is None:
  86. gamma = ones((self.bn.num_features), dtype="float32")
  87. gamma = gamma.reshape(1, -1, 1, 1)
  88. beta = self.bn.bias
  89. if beta is None:
  90. beta = zeros((self.bn.num_features), dtype="float32")
  91. beta = beta.reshape(1, -1, 1, 1)
  92. # conv_bias
  93. conv_bias = self.conv.bias
  94. if conv_bias is None:
  95. conv_bias = zeros(self.conv._infer_bias_shape(), dtype="float32")
  96. bn_istd = 1.0 / sqrt(bn_var + self.bn.eps)
  97. # bn_istd = 1 / bn_std
  98. # w_fold = gamma / bn_std * W
  99. scale_factor = gamma * bn_istd
  100. if self.conv.groups == 1:
  101. w_fold = self.conv.weight * scale_factor.reshape(-1, 1, 1, 1)
  102. else:
  103. w_fold = self.conv.weight * scale_factor.reshape(
  104. self.conv.groups, -1, 1, 1, 1
  105. )
  106. b_fold = None
  107. if not (self.training and approx):
  108. # b_fold = gamma * (conv_bias - bn_mean) / bn_std + beta
  109. b_fold = beta + gamma * (conv_bias - bn_mean) * bn_istd
  110. w_qat = self.apply_quant_weight(w_fold)
  111. b_qat = self.apply_quant_bias(b_fold, inp, w_qat)
  112. conv = self.conv.calc_conv(inp, w_qat, b_qat)
  113. if not (self.training and approx):
  114. return conv
  115. # rescale conv to get original conv output
  116. orig_conv = conv / scale_factor.reshape(1, -1, 1, 1)
  117. if self.conv.bias is not None:
  118. orig_conv = orig_conv + self.conv.bias
  119. # calculate batch norm
  120. conv = self.bn(orig_conv)
  121. return conv
  122. @classmethod
  123. def from_float_module(cls, float_module: Float._ConvBnActivation2d):
  124. qat_module = cls(
  125. float_module.conv.in_channels,
  126. float_module.conv.out_channels,
  127. float_module.conv.kernel_size,
  128. float_module.conv.stride,
  129. float_module.conv.padding,
  130. float_module.conv.dilation,
  131. float_module.conv.groups,
  132. float_module.conv.bias is not None,
  133. float_module.conv.conv_mode,
  134. float_module.conv.compute_mode,
  135. padding_mode=float_module.conv.padding_mode,
  136. name=float_module.name,
  137. )
  138. qat_module.conv.weight = float_module.conv.weight
  139. qat_module.conv.bias = float_module.conv.bias
  140. qat_module.bn = float_module.bn
  141. return qat_module
  142. class ConvBn2d(_ConvBnActivation2d):
  143. r"""A fused :class:`~.QATModule` including :class:`~.module.Conv2d` and :class:`~.module.BatchNorm2d` with QAT support.
  144. Could be applied with :class:`~.Observer` and :class:`~.quantization.fake_quant.FakeQuantize`.
  145. """
  146. def forward(self, inp):
  147. return self.apply_quant_activation(self.calc_conv_bn_qat(inp))
  148. class ConvBnRelu2d(_ConvBnActivation2d):
  149. r"""A fused :class:`~.QATModule` including :class:`~.module.Conv2d`, :class:`~.module.BatchNorm2d` and :func:`~.relu` with QAT support.
  150. Could be applied with :class:`~.Observer` and :class:`~.quantization.fake_quant.FakeQuantize`.
  151. """
  152. def forward(self, inp):
  153. return self.apply_quant_activation(relu(self.calc_conv_bn_qat(inp)))