fusion.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. from __future__ import annotations
  2. import copy
  3. from typing import TypeVar
  4. import torch
  5. __all__ = [
  6. "fuse_conv_bn_eval",
  7. "fuse_conv_bn_weights",
  8. "fuse_linear_bn_eval",
  9. "fuse_linear_bn_weights",
  10. ]
  11. ConvT = TypeVar("ConvT", bound="torch.nn.modules.conv._ConvNd")
  12. LinearT = TypeVar("LinearT", bound="torch.nn.Linear")
  13. def fuse_conv_bn_eval(
  14. conv: ConvT,
  15. bn: torch.nn.modules.batchnorm._BatchNorm,
  16. transpose: bool = False,
  17. ) -> ConvT:
  18. r"""Fuse a convolutional module and a BatchNorm module into a single, new convolutional module.
  19. Args:
  20. conv (torch.nn.modules.conv._ConvNd): A convolutional module.
  21. bn (torch.nn.modules.batchnorm._BatchNorm): A BatchNorm module.
  22. transpose (bool, optional): If True, transpose the convolutional weight. Defaults to False.
  23. Returns:
  24. torch.nn.modules.conv._ConvNd: The fused convolutional module.
  25. .. note::
  26. Both ``conv`` and ``bn`` must be in eval mode, and ``bn`` must have its running buffers computed.
  27. """
  28. assert not (conv.training or bn.training), "Fusion only for eval!"
  29. fused_conv = copy.deepcopy(conv)
  30. assert bn.running_mean is not None and bn.running_var is not None
  31. fused_conv.weight, fused_conv.bias = fuse_conv_bn_weights(
  32. fused_conv.weight,
  33. fused_conv.bias,
  34. bn.running_mean,
  35. bn.running_var,
  36. bn.eps,
  37. bn.weight,
  38. bn.bias,
  39. transpose,
  40. )
  41. return fused_conv
  42. def fuse_conv_bn_weights(
  43. conv_w: torch.Tensor,
  44. conv_b: torch.Tensor | None,
  45. bn_rm: torch.Tensor,
  46. bn_rv: torch.Tensor,
  47. bn_eps: float,
  48. bn_w: torch.Tensor | None,
  49. bn_b: torch.Tensor | None,
  50. transpose: bool = False,
  51. ) -> tuple[torch.nn.Parameter, torch.nn.Parameter]:
  52. r"""Fuse convolutional module parameters and BatchNorm module parameters into new convolutional module parameters.
  53. Args:
  54. conv_w (torch.Tensor): Convolutional weight.
  55. conv_b (Optional[torch.Tensor]): Convolutional bias.
  56. bn_rm (torch.Tensor): BatchNorm running mean.
  57. bn_rv (torch.Tensor): BatchNorm running variance.
  58. bn_eps (float): BatchNorm epsilon.
  59. bn_w (Optional[torch.Tensor]): BatchNorm weight.
  60. bn_b (Optional[torch.Tensor]): BatchNorm bias.
  61. transpose (bool, optional): If True, transpose the conv weight. Defaults to False.
  62. Returns:
  63. Tuple[torch.nn.Parameter, torch.nn.Parameter]: Fused convolutional weight and bias.
  64. """
  65. conv_weight_dtype = conv_w.dtype
  66. conv_bias_dtype = conv_b.dtype if conv_b is not None else conv_weight_dtype
  67. if conv_b is None:
  68. conv_b = torch.zeros_like(bn_rm)
  69. if bn_w is None:
  70. bn_w = torch.ones_like(bn_rm)
  71. if bn_b is None:
  72. bn_b = torch.zeros_like(bn_rm)
  73. bn_var_rsqrt = torch.rsqrt(bn_rv + bn_eps)
  74. if transpose:
  75. shape = [1, -1] + [1] * (len(conv_w.shape) - 2)
  76. else:
  77. shape = [-1, 1] + [1] * (len(conv_w.shape) - 2)
  78. fused_conv_w = (conv_w * (bn_w * bn_var_rsqrt).reshape(shape)).to(
  79. dtype=conv_weight_dtype
  80. )
  81. fused_conv_b = ((conv_b - bn_rm) * bn_var_rsqrt * bn_w + bn_b).to(
  82. dtype=conv_bias_dtype
  83. )
  84. return (
  85. torch.nn.Parameter(fused_conv_w, conv_w.requires_grad),
  86. torch.nn.Parameter(fused_conv_b, conv_b.requires_grad),
  87. )
  88. def fuse_linear_bn_eval(
  89. linear: LinearT,
  90. bn: torch.nn.modules.batchnorm._BatchNorm,
  91. ) -> LinearT:
  92. r"""Fuse a linear module and a BatchNorm module into a single, new linear module.
  93. Args:
  94. linear (torch.nn.Linear): A Linear module.
  95. bn (torch.nn.modules.batchnorm._BatchNorm): A BatchNorm module.
  96. Returns:
  97. torch.nn.Linear: The fused linear module.
  98. .. note::
  99. Both ``linear`` and ``bn`` must be in eval mode, and ``bn`` must have its running buffers computed.
  100. """
  101. assert not (linear.training or bn.training), "Fusion only for eval!"
  102. fused_linear = copy.deepcopy(linear)
  103. """
  104. Linear-BN needs to be fused while preserving the shapes of linear weight/bias.
  105. To preserve the shapes of linear weight/bias, the channel dim of bn needs to be broadcastable with the last dim of linear,
  106. because bn operates over the channel dim, (N, C_in, H, W) while linear operates over the last dim, (*, H_in).
  107. To be broadcastable, the number of features in bn and
  108. the number of output features from linear must satisfy the following condition:
  109. 1. they are equal, or
  110. 2. the number of features in bn is 1
  111. Otherwise, skip the folding path
  112. """
  113. assert linear.out_features == bn.num_features or bn.num_features == 1, (
  114. "To fuse, linear.out_features == bn.num_features or bn.num_features == 1"
  115. )
  116. assert bn.running_mean is not None and bn.running_var is not None
  117. fused_linear.weight, fused_linear.bias = fuse_linear_bn_weights(
  118. fused_linear.weight,
  119. fused_linear.bias,
  120. bn.running_mean,
  121. bn.running_var,
  122. bn.eps,
  123. bn.weight,
  124. bn.bias,
  125. )
  126. return fused_linear
  127. def fuse_linear_bn_weights(
  128. linear_w: torch.Tensor,
  129. linear_b: torch.Tensor | None,
  130. bn_rm: torch.Tensor,
  131. bn_rv: torch.Tensor,
  132. bn_eps: float,
  133. bn_w: torch.Tensor,
  134. bn_b: torch.Tensor,
  135. ) -> tuple[torch.nn.Parameter, torch.nn.Parameter]:
  136. r"""Fuse linear module parameters and BatchNorm module parameters into new linear module parameters.
  137. Args:
  138. linear_w (torch.Tensor): Linear weight.
  139. linear_b (Optional[torch.Tensor]): Linear bias.
  140. bn_rm (torch.Tensor): BatchNorm running mean.
  141. bn_rv (torch.Tensor): BatchNorm running variance.
  142. bn_eps (float): BatchNorm epsilon.
  143. bn_w (torch.Tensor): BatchNorm weight.
  144. bn_b (torch.Tensor): BatchNorm bias.
  145. Returns:
  146. Tuple[torch.nn.Parameter, torch.nn.Parameter]: Fused linear weight and bias.
  147. """
  148. linear_weight_dtype = linear_w.dtype
  149. linear_bias_dtype = linear_b.dtype if linear_b is not None else linear_weight_dtype
  150. if linear_b is None:
  151. linear_b = torch.zeros_like(bn_rm)
  152. bn_scale = bn_w * torch.rsqrt(bn_rv + bn_eps)
  153. fused_w = linear_w * bn_scale.unsqueeze(-1).to(dtype=linear_weight_dtype)
  154. fused_b = ((linear_b - bn_rm) * bn_scale + bn_b).to(dtype=linear_bias_dtype)
  155. return torch.nn.Parameter(fused_w, linear_w.requires_grad), torch.nn.Parameter(
  156. fused_b, linear_b.requires_grad
  157. )