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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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 ...core import ones, zeros
  9. from ...functional import add_update, relu, sqrt, sum, zero_grad
  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.shapeof().prod() / inp.shapeof(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 = zero_grad(bn_mean)
  66. bn_var = (
  67. zero_grad(bn_var)
  68. * num_elements_per_channel
  69. / (num_elements_per_channel - 1)
  70. )
  71. exponential_average_factor = 1 - self.bn.momentum
  72. add_update(
  73. self.bn.running_mean,
  74. delta=bn_mean,
  75. alpha=1 - exponential_average_factor,
  76. beta=exponential_average_factor,
  77. )
  78. add_update(
  79. self.bn.running_var,
  80. delta=bn_var,
  81. alpha=1 - exponential_average_factor,
  82. beta=exponential_average_factor,
  83. )
  84. def calc_conv_bn_qat(self, inp, approx=True):
  85. if self.training and not approx:
  86. conv = self.conv(inp)
  87. bn_mean, bn_var = self.get_batch_mean_var(conv)
  88. num_elements_per_channel = conv.shapeof().prod() / conv.shapeof(1)
  89. self.update_running_mean_and_running_var(
  90. bn_mean, bn_var, num_elements_per_channel
  91. )
  92. else:
  93. bn_mean, bn_var = self.bn.running_mean, self.bn.running_var
  94. # get gamma and beta in BatchNorm
  95. gamma = self.bn.weight
  96. if gamma is None:
  97. gamma = ones((self.bn.num_features), dtype="float32")
  98. gamma = gamma.reshape(1, -1, 1, 1)
  99. beta = self.bn.bias
  100. if beta is None:
  101. beta = zeros((self.bn.num_features), dtype="float32")
  102. beta = beta.reshape(1, -1, 1, 1)
  103. # conv_bias
  104. conv_bias = self.conv.bias
  105. if conv_bias is None:
  106. conv_bias = zeros(self.conv._infer_bias_shape(), dtype="float32")
  107. bn_istd = 1.0 / sqrt(bn_var + self.bn.eps)
  108. # bn_istd = 1 / bn_std
  109. # w_fold = gamma / bn_std * W
  110. scale_factor = gamma * bn_istd
  111. if self.conv.groups == 1:
  112. w_fold = self.conv.weight * scale_factor.reshape(-1, 1, 1, 1)
  113. else:
  114. w_fold = self.conv.weight * scale_factor.reshape(
  115. self.conv.groups, -1, 1, 1, 1
  116. )
  117. b_fold = None
  118. if not (self.training and approx):
  119. # b_fold = gamma * (conv_bias - bn_mean) / bn_std + beta
  120. b_fold = beta + gamma * (conv_bias - bn_mean) * bn_istd
  121. w_qat = self.apply_quant_weight(w_fold)
  122. conv = self.conv.calc_conv(inp, w_qat, b_fold)
  123. if not (self.training and approx):
  124. return conv
  125. # rescale conv to get original conv output
  126. orig_conv = conv / scale_factor.reshape(1, -1, 1, 1)
  127. if self.conv.bias is not None:
  128. orig_conv = orig_conv + self.conv.bias
  129. # calculate batch norm
  130. bn_mean, bn_var = self.get_batch_mean_var(orig_conv)
  131. bn_istd = 1.0 / sqrt(bn_var + self.bn.eps)
  132. conv = gamma * bn_istd * (orig_conv - bn_mean) + beta
  133. num_elements_per_channel = conv.shapeof().prod() / conv.shapeof(1)
  134. self.update_running_mean_and_running_var(
  135. bn_mean, bn_var, num_elements_per_channel
  136. )
  137. return conv
  138. @classmethod
  139. def from_float_module(cls, float_module: Float._ConvBnActivation2d):
  140. r"""
  141. Return a :class:`~.QATModule` instance converted from
  142. a float :class:`~.Module` instance.
  143. """
  144. qat_module = cls(
  145. float_module.conv.in_channels,
  146. float_module.conv.out_channels,
  147. float_module.conv.kernel_size,
  148. float_module.conv.stride,
  149. float_module.conv.padding,
  150. float_module.conv.dilation,
  151. float_module.conv.groups,
  152. float_module.conv.bias is not None,
  153. float_module.conv.conv_mode.name,
  154. float_module.conv.compute_mode.name,
  155. )
  156. qat_module.conv.weight = float_module.conv.weight
  157. qat_module.conv.bias = float_module.conv.bias
  158. qat_module.bn = float_module.bn
  159. return qat_module
  160. class ConvBn2d(_ConvBnActivation2d):
  161. r"""
  162. A fused :class:`~.QATModule` including Conv2d, BatchNorm2d with QAT support.
  163. Could be applied with :class:`~.Observer` and :class:`~.FakeQuantize`.
  164. """
  165. def forward(self, inp):
  166. return self.apply_quant_activation(self.calc_conv_bn_qat(inp))
  167. class ConvBnRelu2d(_ConvBnActivation2d):
  168. r"""
  169. A fused :class:`~.QATModule` including Conv2d, BatchNorm2d and relu with QAT support.
  170. Could be applied with :class:`~.Observer` and :class:`~.FakeQuantize`.
  171. """
  172. def forward(self, inp):
  173. return self.apply_quant_activation(relu(self.calc_conv_bn_qat(inp)))

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