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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. )
  32. w_fold, b_fold = qat_module.fold_weight_bias(
  33. qat_module.bn.running_mean, qat_module.bn.running_var
  34. )
  35. weight = w_fold.astype(qat_module.get_weight_dtype())
  36. qconv.weight = Parameter(weight.numpy(), name=qat_module.conv.weight.name)
  37. qconv.bias = Parameter(b_fold.numpy())
  38. if qat_module.conv.bias is not None:
  39. qconv.bias.name = qat_module.conv.bias.name
  40. return qconv
  41. class ConvBn2d(_ConvBnActivation2d):
  42. r"""Quantized version of :class:`~.qat.ConvBn2d`."""
  43. def forward(self, inp):
  44. return self.calc_conv_quantized(inp, nonlinear_mode="identity")
  45. class ConvBnRelu2d(_ConvBnActivation2d):
  46. r"""Quantized version of :class:`~.qat.ConvBnRelu2d`."""
  47. def forward(self, inp):
  48. return self.calc_conv_quantized(inp, nonlinear_mode="relu")