fused_adam.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. '''
  2. Copyright 2020 The Microsoft DeepSpeed Team
  3. Copyright NVIDIA/apex
  4. This file is adapted from fused adam in NVIDIA/apex, commit a109f85
  5. '''
  6. import torch
  7. import importlib
  8. from .multi_tensor_apply import MultiTensorApply
  9. multi_tensor_applier = MultiTensorApply(2048 * 32)
  10. from ..op_builder import FusedAdamBuilder
  11. class FusedAdam(torch.optim.Optimizer):
  12. """Implements Adam algorithm.
  13. Currently GPU-only.
  14. This version of fused Adam implements 2 fusions.
  15. * Fusion of the Adam update's elementwise operations
  16. * A multi-tensor apply launch that batches the elementwise updates applied to all the model's parameters into one or a few kernel launches.
  17. Adam was been proposed in `Adam: A Method for Stochastic Optimization`_.
  18. Arguments:
  19. params (iterable): iterable of parameters to optimize or dicts defining
  20. parameter groups.
  21. lr (float, optional): learning rate. (default: 1e-3)
  22. betas (Tuple[float, float], optional): coefficients used for computing
  23. running averages of gradient and its square. (default: (0.9, 0.999))
  24. eps (float, optional): term added to the denominator to improve
  25. numerical stability. (default: 1e-8)
  26. weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
  27. amsgrad (boolean, optional): whether to use the AMSGrad variant of this
  28. algorithm from the paper `On the Convergence of Adam and Beyond`_
  29. (default: False) NOT SUPPORTED in FusedAdam!
  30. adam_w_mode (boolean, optional): Apply L2 regularization or weight decay
  31. True for decoupled weight decay(also known as AdamW) (default: True)
  32. set_grad_none (bool, optional): whether set grad to None when zero_grad()
  33. method is called. (default: True)
  34. .. _Adam - A Method for Stochastic Optimization:
  35. https://arxiv.org/abs/1412.6980
  36. .. _On the Convergence of Adam and Beyond:
  37. https://openreview.net/forum?id=ryQu7f-RZ
  38. """
  39. def __init__(self,
  40. params,
  41. lr=1e-3,
  42. bias_correction=True,
  43. betas=(0.9,
  44. 0.999),
  45. eps=1e-8,
  46. adam_w_mode=True,
  47. weight_decay=0.,
  48. amsgrad=False,
  49. set_grad_none=True):
  50. if amsgrad:
  51. raise RuntimeError('FusedAdam does not support the AMSGrad variant.')
  52. defaults = dict(lr=lr,
  53. bias_correction=bias_correction,
  54. betas=betas,
  55. eps=eps,
  56. weight_decay=weight_decay)
  57. super(FusedAdam, self).__init__(params, defaults)
  58. self.adam_w_mode = 1 if adam_w_mode else 0
  59. self.set_grad_none = set_grad_none
  60. fused_adam_cuda = FusedAdamBuilder().load()
  61. # Skip buffer
  62. self._dummy_overflow_buf = torch.cuda.IntTensor([0])
  63. self.multi_tensor_adam = fused_adam_cuda.multi_tensor_adam
  64. def zero_grad(self):
  65. if self.set_grad_none:
  66. for group in self.param_groups:
  67. for p in group['params']:
  68. p.grad = None
  69. else:
  70. super(FusedAdam, self).zero_grad()
  71. def step(self,
  72. closure=None,
  73. grads=None,
  74. output_params=None,
  75. scale=None,
  76. grad_norms=None):
  77. """Performs a single optimization step.
  78. Arguments:
  79. closure (callable, optional): A closure that reevaluates the model
  80. and returns the loss.
  81. The remaining arguments are deprecated, and are only retained (for the moment) for error-checking purposes.
  82. """
  83. if any(p is not None for p in [grads, output_params, scale, grad_norms]):
  84. raise RuntimeError(
  85. 'FusedAdam has been updated. Simply initialize it identically to torch.optim.Adam, and call step() with no arguments.'
  86. )
  87. loss = None
  88. if closure is not None:
  89. loss = closure()
  90. for group in self.param_groups:
  91. bias_correction = 1 if group['bias_correction'] else 0
  92. beta1, beta2 = group['betas']
  93. # assume same step across group now to simplify things
  94. # per parameter step can be easily support by making it tensor, or pass list into kernel
  95. if 'step' in group:
  96. group['step'] += 1
  97. else:
  98. group['step'] = 1
  99. # create lists for multi-tensor apply
  100. g_16, p_16, m_16, v_16 = [], [], [], []
  101. g_32, p_32, m_32, v_32 = [], [], [], []
  102. for p in group['params']:
  103. if p.grad is None:
  104. continue
  105. if p.grad.data.is_sparse:
  106. raise RuntimeError(
  107. 'FusedAdam does not support sparse gradients, please consider SparseAdam instead'
  108. )
  109. state = self.state[p]
  110. # State initialization
  111. if len(state) == 0:
  112. # Exponential moving average of gradient values
  113. state['exp_avg'] = torch.zeros_like(p.data)
  114. # Exponential moving average of squared gradient values
  115. state['exp_avg_sq'] = torch.zeros_like(p.data)
  116. if p.dtype == torch.float16:
  117. g_16.append(p.grad.data)
  118. p_16.append(p.data)
  119. m_16.append(state['exp_avg'])
  120. v_16.append(state['exp_avg_sq'])
  121. elif p.dtype == torch.float32:
  122. g_32.append(p.grad.data)
  123. p_32.append(p.data)
  124. m_32.append(state['exp_avg'])
  125. v_32.append(state['exp_avg_sq'])
  126. else:
  127. raise RuntimeError('FusedAdam only support fp16 and fp32.')
  128. if (len(g_16) > 0):
  129. multi_tensor_applier(self.multi_tensor_adam,
  130. self._dummy_overflow_buf,
  131. [g_16,
  132. p_16,
  133. m_16,
  134. v_16],
  135. group['lr'],
  136. beta1,
  137. beta2,
  138. group['eps'],
  139. group['step'],
  140. self.adam_w_mode,
  141. bias_correction,
  142. group['weight_decay'])
  143. if (len(g_32) > 0):
  144. multi_tensor_applier(self.multi_tensor_adam,
  145. self._dummy_overflow_buf,
  146. [g_32,
  147. p_32,
  148. m_32,
  149. v_32],
  150. group['lr'],
  151. beta1,
  152. beta2,
  153. group['eps'],
  154. group['step'],
  155. self.adam_w_mode,
  156. bias_correction,
  157. group['weight_decay'])
  158. return loss