weight_init.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. import torch
  2. import math
  3. import warnings
  4. from torch import nn
  5. from torch.nn.init import _calculate_fan_in_and_fan_out
  6. def _trunc_normal_(tensor, mean, std, a, b):
  7. # Cut & paste from PyTorch official master until it's in a few official releases - RW
  8. # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
  9. def norm_cdf(x):
  10. # Computes standard normal cumulative distribution function
  11. return (1. + math.erf(x / math.sqrt(2.))) / 2.
  12. if (mean < a - 2 * std) or (mean > b + 2 * std):
  13. warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
  14. "The distribution of values may be incorrect.",
  15. stacklevel=2)
  16. # Values are generated by using a truncated uniform distribution and
  17. # then using the inverse CDF for the normal distribution.
  18. # Get upper and lower cdf values
  19. l = norm_cdf((a - mean) / std)
  20. u = norm_cdf((b - mean) / std)
  21. # Uniformly fill tensor with values from [l, u], then translate to
  22. # [2l-1, 2u-1].
  23. tensor.uniform_(2 * l - 1, 2 * u - 1)
  24. # Use inverse cdf transform for normal distribution to get truncated
  25. # standard normal
  26. tensor.erfinv_()
  27. # Transform to proper mean, std
  28. tensor.mul_(std * math.sqrt(2.))
  29. tensor.add_(mean)
  30. # Clamp to ensure it's in the proper range
  31. tensor.clamp_(min=a, max=b)
  32. return tensor
  33. def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):
  34. # type: (Tensor, float, float, float, float) -> Tensor
  35. r"""Fills the input Tensor with values drawn from a truncated
  36. normal distribution. The values are effectively drawn from the
  37. normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`
  38. with values outside :math:`[a, b]` redrawn until they are within
  39. the bounds. The method used for generating the random values works
  40. best when :math:`a \leq \text{mean} \leq b`.
  41. NOTE: this impl is similar to the PyTorch trunc_normal_, the bounds [a, b] are
  42. applied while sampling the normal with mean/std applied, therefore a, b args
  43. should be adjusted to match the range of mean, std args.
  44. Args:
  45. tensor: an n-dimensional `torch.Tensor`
  46. mean: the mean of the normal distribution
  47. std: the standard deviation of the normal distribution
  48. a: the minimum cutoff value
  49. b: the maximum cutoff value
  50. Examples:
  51. >>> w = torch.empty(3, 5)
  52. >>> nn.init.trunc_normal_(w)
  53. """
  54. with torch.no_grad():
  55. return _trunc_normal_(tensor, mean, std, a, b)
  56. def trunc_normal_tf_(tensor, mean=0., std=1., a=-2., b=2.):
  57. # type: (Tensor, float, float, float, float) -> Tensor
  58. r"""Fills the input Tensor with values drawn from a truncated
  59. normal distribution. The values are effectively drawn from the
  60. normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`
  61. with values outside :math:`[a, b]` redrawn until they are within
  62. the bounds. The method used for generating the random values works
  63. best when :math:`a \leq \text{mean} \leq b`.
  64. NOTE: this 'tf' variant behaves closer to Tensorflow / JAX impl where the
  65. bounds [a, b] are applied when sampling the normal distribution with mean=0, std=1.0
  66. and the result is subsequently scaled and shifted by the mean and std args.
  67. Args:
  68. tensor: an n-dimensional `torch.Tensor`
  69. mean: the mean of the normal distribution
  70. std: the standard deviation of the normal distribution
  71. a: the minimum cutoff value
  72. b: the maximum cutoff value
  73. Examples:
  74. >>> w = torch.empty(3, 5)
  75. >>> nn.init.trunc_normal_(w)
  76. """
  77. with torch.no_grad():
  78. _trunc_normal_(tensor, 0, 1.0, a, b)
  79. tensor.mul_(std).add_(mean)
  80. return tensor
  81. def variance_scaling_(tensor, scale=1.0, mode='fan_in', distribution='normal'):
  82. fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor)
  83. if mode == 'fan_in':
  84. denom = fan_in
  85. elif mode == 'fan_out':
  86. denom = fan_out
  87. elif mode == 'fan_avg':
  88. denom = (fan_in + fan_out) / 2
  89. variance = scale / denom
  90. if distribution == "truncated_normal":
  91. # constant is stddev of standard normal truncated to (-2, 2)
  92. trunc_normal_tf_(tensor, std=math.sqrt(variance) / .87962566103423978)
  93. elif distribution == "normal":
  94. with torch.no_grad():
  95. tensor.normal_(std=math.sqrt(variance))
  96. elif distribution == "uniform":
  97. bound = math.sqrt(3 * variance)
  98. with torch.no_grad():
  99. tensor.uniform_(-bound, bound)
  100. else:
  101. raise ValueError(f"invalid distribution {distribution}")
  102. def lecun_normal_(tensor):
  103. variance_scaling_(tensor, mode='fan_in', distribution='truncated_normal')
  104. def init_weight_vit(
  105. module: nn.Module,
  106. name: str,
  107. init_bias: float = 0.02,
  108. head_bias: float = 0.,
  109. classifier_name: str = 'head'
  110. ):
  111. if isinstance(module, (nn.Linear, nn.Conv1d, nn.Conv2d, nn.Conv3d)):
  112. if name.startswith(classifier_name):
  113. nn.init.zeros_(module.weight)
  114. nn.init.constant_(module.bias, head_bias)
  115. else:
  116. nn.init.trunc_normal_(module.weight, std=0.02)
  117. if isinstance(module, nn.Linear) and module.bias is not None:
  118. nn.init.constant_(module.bias, init_bias)
  119. elif hasattr(module, 'init_weights'):
  120. module.init_weights()
  121. def init_weight_jax(
  122. module: nn.Module,
  123. name: str,
  124. head_bias: float = 0.,
  125. classifier_name: str = 'head',
  126. ):
  127. if isinstance(module, nn.Linear):
  128. if name.startswith(classifier_name):
  129. nn.init.zeros_(module.weight)
  130. nn.init.constant_(module.bias, head_bias)
  131. else:
  132. nn.init.xavier_uniform_(module.weight)
  133. if module.bias is not None:
  134. nn.init.normal_(module.bias, std=1e-6) if 'mlp' in name else nn.init.zeros_(module.bias)
  135. elif isinstance(module, nn.Conv2d):
  136. lecun_normal_(module.weight)
  137. if module.bias is not None:
  138. nn.init.zeros_(module.bias)
  139. elif hasattr(module, 'init_weights'):
  140. module.init_weights()