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.

normalization.py 4.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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. import numpy as np
  9. import megengine.functional as F
  10. from megengine import Parameter
  11. from .init import ones_, zeros_
  12. from .module import Module
  13. class GroupNorm(Module):
  14. """Simple implementation of GroupNorm. Only support 4d tensor now.
  15. Reference: https://arxiv.org/pdf/1803.08494.pdf.
  16. """
  17. def __init__(self, num_groups, num_channels, eps=1e-5, affine=True, **kwargs):
  18. super().__init__(**kwargs)
  19. assert num_channels % num_groups == 0
  20. self.num_groups = num_groups
  21. self.num_channels = num_channels
  22. self.eps = eps
  23. self.affine = affine
  24. if self.affine:
  25. self.weight = Parameter(np.ones(num_channels, dtype=np.float32))
  26. self.bias = Parameter(np.zeros(num_channels, dtype=np.float32))
  27. else:
  28. self.weight = None
  29. self.bias = None
  30. self.reset_parameters()
  31. def reset_parameters(self):
  32. if self.affine:
  33. ones_(self.weight)
  34. zeros_(self.bias)
  35. def forward(self, x):
  36. N, C, H, W = x.shape
  37. assert C == self.num_channels
  38. x = x.reshape(N, self.num_groups, -1)
  39. mean = x.mean(axis=2, keepdims=True)
  40. var = (x * x).mean(axis=2, keepdims=True) - mean * mean
  41. x = (x - mean) / F.sqrt(var + self.eps)
  42. x = x.reshape(N, C, H, W)
  43. if self.affine:
  44. x = self.weight.reshape(1, -1, 1, 1) * x + self.bias.reshape(1, -1, 1, 1)
  45. return x
  46. def _module_info_string(self) -> str:
  47. s = (
  48. "groups={num_groups}, channels={num_channels}, "
  49. "eps={eps}, affine={affine}"
  50. )
  51. return s.format(**self.__dict__)
  52. class InstanceNorm(Module):
  53. """Simple implementation of InstanceNorm. Only support 4d tensor now.
  54. Reference: https://arxiv.org/abs/1607.08022.
  55. Note that InstanceNorm equals using GroupNome with num_groups=num_channels.
  56. """
  57. def __init__(self, num_channels, eps=1e-05, affine=True, **kwargs):
  58. super().__init__(**kwargs)
  59. self.num_channels = num_channels
  60. self.eps = eps
  61. self.affine = affine
  62. if self.affine:
  63. self.weight = Parameter(np.ones(num_channels, dtype="float32"))
  64. self.bias = Parameter(np.zeros(num_channels, dtype="float32"))
  65. else:
  66. self.weight = None
  67. self.bias = None
  68. self.reset_parameters()
  69. def reset_parameters(self):
  70. if self.affine:
  71. ones_(self.weight)
  72. zeros_(self.bias)
  73. def forward(self, x):
  74. N, C, H, W = x.shape
  75. assert C == self.num_channels
  76. x = x.reshape(N, C, -1)
  77. mean = x.mean(axis=2, keepdims=True)
  78. var = (x ** 2).mean(axis=2, keepdims=True) - mean * mean
  79. x = (x - mean) / F.sqrt(var + self.eps)
  80. x = x.reshape(N, C, H, W)
  81. if self.affine:
  82. x = self.weight.reshape(1, -1, 1, 1) * x + self.bias.reshape(1, -1, 1, 1)
  83. return x
  84. def _module_info_string(self) -> str:
  85. s = "channels={num_channels}, eps={eps}, affine={affine}"
  86. return s.format(**self.__dict__)
  87. class LayerNorm(Module):
  88. """Simple implementation of LayerNorm. Support tensor of any shape as input.
  89. Reference: https://arxiv.org/pdf/1803.08494.pdf.
  90. """
  91. def __init__(self, normalized_shape, eps=1e-05, affine=True, **kwargs):
  92. super().__init__(**kwargs)
  93. if isinstance(normalized_shape, int):
  94. normalized_shape = (normalized_shape,)
  95. self.normalized_shape = tuple(normalized_shape)
  96. self.eps = eps
  97. self.affine = affine
  98. if self.affine:
  99. self.weight = Parameter(np.ones(self.normalized_shape, dtype="float32"))
  100. self.bias = Parameter(np.zeros(self.normalized_shape, dtype="float32"))
  101. else:
  102. self.weight = None
  103. self.bias = None
  104. self.reset_parameters()
  105. def reset_parameters(self):
  106. if self.affine:
  107. ones_(self.weight)
  108. zeros_(self.bias)
  109. def forward(self, x):
  110. x = F.nn.layer_norm(
  111. x, self.normalized_shape, self.affine, self.weight, self.bias, self.eps
  112. )
  113. return x
  114. def _module_info_string(self) -> str:
  115. s = "normalized_shape={normalized_shape}, eps={eps}, affine={affine}"
  116. return s.format(**self.__dict__)

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