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.3 kB

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

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台