weight_init.py 6.5 KB

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