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 2.1 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 ...tensor import Parameter
  9. from ..qat import conv_bn as QAT
  10. from .conv import Conv2d
  11. class _ConvBnActivation2d(Conv2d):
  12. r"""Applies a 2D convolution over a quantized input tensor, used for inference only.
  13. """
  14. @classmethod
  15. def from_qat_module(cls, qat_module: QAT._ConvBnActivation2d):
  16. r"""
  17. Return a :class:`~.QuantizedModule` instance converted from a
  18. :class:`~.QATModule` instance.
  19. """
  20. output_dtype = qat_module.get_activation_dtype()
  21. qconv = cls(
  22. qat_module.conv.in_channels,
  23. qat_module.conv.out_channels,
  24. qat_module.conv.kernel_size,
  25. qat_module.conv.stride,
  26. qat_module.conv.padding,
  27. qat_module.conv.dilation,
  28. qat_module.conv.groups,
  29. dtype=output_dtype,
  30. name=qat_module.name,
  31. padding_mode=qat_module.conv.padding_mode,
  32. )
  33. w_fold, b_fold = qat_module.fold_weight_bias(
  34. qat_module.bn.running_mean, qat_module.bn.running_var
  35. )
  36. weight = w_fold.astype(qat_module.get_weight_dtype())
  37. qconv.weight = Parameter(weight.numpy(), name=qat_module.conv.weight.name)
  38. qconv.bias = Parameter(b_fold.numpy())
  39. if qat_module.conv.bias is not None:
  40. qconv.bias.name = qat_module.conv.bias.name
  41. return qconv
  42. class ConvBn2d(_ConvBnActivation2d):
  43. r"""Quantized version of :class:`~.qat.ConvBn2d`."""
  44. def forward(self, inp):
  45. return self.calc_conv_quantized(inp, nonlinear_mode="identity")
  46. class ConvBnRelu2d(_ConvBnActivation2d):
  47. r"""Quantized version of :class:`~.qat.ConvBnRelu2d`."""
  48. def forward(self, inp):
  49. return self.calc_conv_quantized(inp, nonlinear_mode="relu")