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_relu.py 7.4 kB

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

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