naive_sync_bn.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import paddle.distributed as dist
  15. import math
  16. import paddle
  17. import paddle.nn as nn
  18. class _AllReduce(paddle.autograd.PyLayer):
  19. @staticmethod
  20. def forward(ctx, input):
  21. input_list = [paddle.zeros_like(input) for k in range(dist.get_world_size())]
  22. # Use allgather instead of allreduce since I don't trust in-place operations ..
  23. dist.all_gather(input_list, input, sync_op=True)
  24. inputs = paddle.stack(input_list, axis=0)
  25. return paddle.sum(inputs, axis=0)
  26. @staticmethod
  27. def backward(ctx, grad_output):
  28. dist.all_reduce(grad_output, sync_op=True)
  29. return grad_output
  30. def differentiable_all_reduce(input):
  31. """
  32. Differentiable counterpart of `dist.all_reduce`.
  33. """
  34. if (
  35. not dist.is_available()
  36. or not dist.is_initialized()
  37. or dist.get_world_size() == 1
  38. ):
  39. return input
  40. return _AllReduce.apply(input)
  41. class NaiveSyncBatchNorm(nn.BatchNorm2D):
  42. def __init__(self, *args, stats_mode="", **kwargs):
  43. super().__init__(*args, **kwargs)
  44. assert stats_mode in ["", "N"]
  45. self._stats_mode = stats_mode
  46. def forward(self, input):
  47. if dist.get_world_size() == 1 or not self.training:
  48. return super().forward(input)
  49. B, C = input.shape[0], input.shape[1]
  50. mean = paddle.mean(input, axis=[0, 2, 3])
  51. meansqr = paddle.mean(input * input, axis=[0, 2, 3])
  52. if self._stats_mode == "":
  53. assert (
  54. B > 0
  55. ), 'SyncBatchNorm(stats_mode="") does not support zero batch size.'
  56. vec = paddle.concat([mean, meansqr], axis=0)
  57. vec = differentiable_all_reduce(vec) * (1.0 / dist.get_world_size())
  58. mean, meansqr = paddle.split(vec, [C, C])
  59. momentum = (
  60. 1 - self._momentum
  61. ) # NOTE: paddle has reverse momentum definition
  62. else:
  63. if B == 0:
  64. vec = paddle.zeros([2 * C + 1], dtype=mean.dtype)
  65. vec = vec + input.sum() # make sure there is gradient w.r.t input
  66. else:
  67. vec = paddle.concat(
  68. [
  69. mean,
  70. meansqr,
  71. paddle.ones([1], dtype=mean.dtype),
  72. ],
  73. axis=0,
  74. )
  75. vec = differentiable_all_reduce(vec * B)
  76. total_batch = vec[-1].detach()
  77. momentum = total_batch.clip(max=1) * (
  78. 1 - self._momentum
  79. ) # no update if total_batch is 0
  80. mean, meansqr, _ = paddle.split(
  81. vec / total_batch.clip(min=1), [C, C, int(vec.shape[0] - 2 * C)]
  82. ) # avoid div-by-zero
  83. var = meansqr - mean * mean
  84. invstd = paddle.rsqrt(var + self._epsilon)
  85. scale = self.weight * invstd
  86. bias = self.bias - mean * scale
  87. scale = scale.reshape([1, -1, 1, 1])
  88. bias = bias.reshape([1, -1, 1, 1])
  89. tmp_mean = self._mean + momentum * (mean.detach() - self._mean)
  90. self._mean.set_value(tmp_mean)
  91. tmp_variance = self._variance + (momentum * (var.detach() - self._variance))
  92. self._variance.set_value(tmp_variance)
  93. ret = input * scale + bias
  94. return ret
  95. def convert_syncbn(model):
  96. for n, m in model.named_children():
  97. if isinstance(m, nn.layer.norm._BatchNormBase):
  98. syncbn = NaiveSyncBatchNorm(
  99. m._num_features, m._momentum, m._epsilon, m._weight_attr, m._bias_attr
  100. )
  101. setattr(model, n, syncbn)
  102. else:
  103. convert_syncbn(m)