fused_adam.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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. from .multi_tensor_apply import MultiTensorApply
  8. multi_tensor_applier = MultiTensorApply(2048 * 32)
  9. from deepspeed.accelerator import get_accelerator
  10. from deepspeed.ops.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 = get_accelerator().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. if 'step' not in group:
  94. group['step'] = 0
  95. # create lists for multi-tensor apply
  96. g_16, p_16, m_16, v_16 = [], [], [], []
  97. g_32, p_32, m_32, v_32 = [], [], [], []
  98. for p in group['params']:
  99. if p.grad is None:
  100. continue
  101. if p.grad.data.is_sparse:
  102. raise RuntimeError(
  103. 'FusedAdam does not support sparse gradients, please consider SparseAdam instead'
  104. )
  105. state = self.state[p]
  106. # State initialization
  107. if len(state) == 0:
  108. # DeepSpeed ZeRO 3 processes each subgroup a time, so we need to keep tracking step count for each tensor separately.
  109. # While this is not an issue for ZeRO 1 & 2, since they apply a single optimizatin step to the whole param group at the same time.
  110. # In order to keep backward compatibility for the existing checkpoints, we use group['state'] to initialize state['step'] if it exists.
  111. state['step'] = group.get('step', 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. state['step'] += 1
  130. multi_tensor_applier(self.multi_tensor_adam,
  131. self._dummy_overflow_buf,
  132. [g_16,
  133. p_16,
  134. m_16,
  135. v_16],
  136. group['lr'],
  137. beta1,
  138. beta2,
  139. group['eps'],
  140. state['step'],
  141. self.adam_w_mode,
  142. bias_correction,
  143. group['weight_decay'])
  144. if (len(g_32) > 0):
  145. state['step'] += 1
  146. multi_tensor_applier(self.multi_tensor_adam,
  147. self._dummy_overflow_buf,
  148. [g_32,
  149. p_32,
  150. m_32,
  151. v_32],
  152. group['lr'],
  153. beta1,
  154. beta2,
  155. group['eps'],
  156. state['step'],
  157. self.adam_w_mode,
  158. bias_correction,
  159. group['weight_decay'])
  160. return loss