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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 typing import Tuple, Union
  9. from ..functional import relu
  10. from .batchnorm import BatchNorm2d
  11. from .conv import Conv2d
  12. from .module import Module
  13. class _ConvBnActivation2d(Module):
  14. def __init__(
  15. self,
  16. in_channels: int,
  17. out_channels: int,
  18. kernel_size: Union[int, Tuple[int, int]],
  19. stride: Union[int, Tuple[int, int]] = 1,
  20. padding: Union[int, Tuple[int, int]] = 0,
  21. dilation: Union[int, Tuple[int, int]] = 1,
  22. groups: int = 1,
  23. bias: bool = True,
  24. conv_mode: str = "cross_correlation",
  25. compute_mode: str = "default",
  26. eps=1e-5,
  27. momentum=0.9,
  28. affine=True,
  29. track_running_stats=True,
  30. padding_mode: str = "zeros",
  31. **kwargs
  32. ):
  33. super().__init__(**kwargs)
  34. self.conv = Conv2d(
  35. in_channels,
  36. out_channels,
  37. kernel_size,
  38. stride,
  39. padding,
  40. dilation,
  41. groups,
  42. bias,
  43. conv_mode,
  44. compute_mode,
  45. padding_mode,
  46. **kwargs,
  47. )
  48. self.bn = BatchNorm2d(out_channels, eps, momentum, affine, track_running_stats)
  49. class ConvBn2d(_ConvBnActivation2d):
  50. r"""A fused :class:`~.Module` including :class:`~.module.Conv2d` and :class:`~.module.BatchNorm2d`.
  51. Could be replaced with :class:`~.QATModule` version :class:`~.qat.ConvBn2d` using
  52. :func:`~.quantize.quantize_qat`.
  53. """
  54. def forward(self, inp):
  55. return self.bn(self.conv(inp))
  56. class ConvBnRelu2d(_ConvBnActivation2d):
  57. r"""A fused :class:`~.Module` including :class:`~.module.Conv2d`, :class:`~.module.BatchNorm2d` and :func:`~.relu`.
  58. Could be replaced with :class:`~.QATModule` version :class:`~.qat.ConvBnRelu2d` using :func:`~.quantize.quantize_qat`.
  59. """
  60. def forward(self, inp):
  61. return relu(self.bn(self.conv(inp)))