2021-10-28 16:21:23 +00:00
|
|
|
# modified from https://github.com/NVIDIA/apex/blob/master/apex/optimizers/fused_adam.py
|
|
|
|
import torch
|
|
|
|
|
|
|
|
from colossalai.registry import OPTIMIZERS
|
Develop/experiments (#59)
* Add gradient accumulation, fix lr scheduler
* fix FP16 optimizer and adapted torch amp with tensor parallel (#18)
* fixed bugs in compatibility between torch amp and tensor parallel and performed some minor fixes
* fixed trainer
* Revert "fixed trainer"
This reverts commit 2e0b0b76990e8d4e337add483d878c0f61cf5097.
* improved consistency between trainer, engine and schedule (#23)
Co-authored-by: 1SAA <c2h214748@gmail.com>
* Split conv2d, class token, positional embedding in 2d, Fix random number in ddp
Fix convergence in cifar10, Imagenet1000
* Integrate 1d tensor parallel in Colossal-AI (#39)
* fixed 1D and 2D convergence (#38)
* optimized 2D operations
* fixed 1D ViT convergence problem
* Feature/ddp (#49)
* remove redundancy func in setup (#19) (#20)
* use env to control the language of doc (#24) (#25)
* Support TP-compatible Torch AMP and Update trainer API (#27)
* Add gradient accumulation, fix lr scheduler
* fix FP16 optimizer and adapted torch amp with tensor parallel (#18)
* fixed bugs in compatibility between torch amp and tensor parallel and performed some minor fixes
* fixed trainer
* Revert "fixed trainer"
This reverts commit 2e0b0b76990e8d4e337add483d878c0f61cf5097.
* improved consistency between trainer, engine and schedule (#23)
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: ver217 <lhx0217@gmail.com>
* add an example of ViT-B/16 and remove w_norm clipping in LAMB (#29)
* add explanation for ViT example (#35) (#36)
* support torch ddp
* fix loss accumulation
* add log for ddp
* change seed
* modify timing hook
Co-authored-by: Frank Lee <somerlee.9@gmail.com>
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: binmakeswell <binmakeswell@gmail.com>
* Feature/pipeline (#40)
* remove redundancy func in setup (#19) (#20)
* use env to control the language of doc (#24) (#25)
* Support TP-compatible Torch AMP and Update trainer API (#27)
* Add gradient accumulation, fix lr scheduler
* fix FP16 optimizer and adapted torch amp with tensor parallel (#18)
* fixed bugs in compatibility between torch amp and tensor parallel and performed some minor fixes
* fixed trainer
* Revert "fixed trainer"
This reverts commit 2e0b0b76990e8d4e337add483d878c0f61cf5097.
* improved consistency between trainer, engine and schedule (#23)
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: ver217 <lhx0217@gmail.com>
* add an example of ViT-B/16 and remove w_norm clipping in LAMB (#29)
* add explanation for ViT example (#35) (#36)
* optimize communication of pipeline parallel
* fix grad clip for pipeline
Co-authored-by: Frank Lee <somerlee.9@gmail.com>
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: binmakeswell <binmakeswell@gmail.com>
* optimized 3d layer to fix slow computation ; tested imagenet performance with 3d; reworked lr_scheduler config definition; fixed launch args; fixed some printing issues; simplified apis of 3d layers (#51)
* Update 2.5d layer code to get a similar accuracy on imagenet-1k dataset
* update api for better usability (#58)
update api for better usability
Co-authored-by: 1SAA <c2h214748@gmail.com>
Co-authored-by: ver217 <lhx0217@gmail.com>
Co-authored-by: puck_WCR <46049915+WANG-CR@users.noreply.github.com>
Co-authored-by: binmakeswell <binmakeswell@gmail.com>
Co-authored-by: アマデウス <kurisusnowdeng@users.noreply.github.com>
Co-authored-by: BoxiangW <45734921+BoxiangW@users.noreply.github.com>
2021-12-09 07:08:29 +00:00
|
|
|
from colossalai.utils import multi_tensor_applier
|
2021-10-28 16:21:23 +00:00
|
|
|
|
|
|
|
|
|
|
|
@OPTIMIZERS.register_module
|
|
|
|
class FusedAdam(torch.optim.Optimizer):
|
|
|
|
"""Implements Adam algorithm.
|
|
|
|
|
|
|
|
Currently GPU-only. Requires ColossalAI to be installed via
|
2022-03-25 06:15:53 +00:00
|
|
|
``pip install .``.
|
2021-10-28 16:21:23 +00:00
|
|
|
|
|
|
|
This version of fused Adam implements 2 fusions.
|
|
|
|
|
|
|
|
* Fusion of the Adam update's elementwise operations
|
|
|
|
* A multi-tensor apply launch that batches the elementwise updates applied to all the model's parameters into one or a few kernel launches.
|
|
|
|
|
|
|
|
:class:`colossalai.nn.optimizer.FusedAdam` may be used as a drop-in replacement for ``torch.optim.AdamW``,
|
2022-03-25 06:15:53 +00:00
|
|
|
or ``torch.optim.Adam`` with ``adamw_mode=False``
|
2021-10-28 16:21:23 +00:00
|
|
|
|
|
|
|
:class:`colossalai.nn.optimizer.FusedAdam` may be used with or without Amp.
|
|
|
|
|
|
|
|
Adam was been proposed in `Adam: A Method for Stochastic Optimization`_.
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
params (iterable): iterable of parameters to optimize or dicts defining
|
|
|
|
parameter groups.
|
|
|
|
lr (float, optional): learning rate. (default: 1e-3)
|
|
|
|
betas (Tuple[float, float], optional): coefficients used for computing
|
|
|
|
running averages of gradient and its square. (default: (0.9, 0.999))
|
|
|
|
eps (float, optional): term added to the denominator to improve
|
|
|
|
numerical stability. (default: 1e-8)
|
|
|
|
weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
|
|
|
|
amsgrad (boolean, optional): whether to use the AMSGrad variant of this
|
|
|
|
algorithm from the paper `On the Convergence of Adam and Beyond`_
|
|
|
|
(default: False) NOT SUPPORTED in FusedAdam!
|
2022-03-25 06:15:53 +00:00
|
|
|
adamw_mode (boolean, optional): Apply L2 regularization or weight decay
|
2021-10-28 16:21:23 +00:00
|
|
|
True for decoupled weight decay(also known as AdamW) (default: True)
|
|
|
|
set_grad_none (bool, optional): whether set grad to None when zero_grad()
|
|
|
|
method is called. (default: True)
|
|
|
|
|
2022-04-01 08:27:03 +00:00
|
|
|
.. _Adam\: A Method for Stochastic Optimization:
|
2021-10-28 16:21:23 +00:00
|
|
|
https://arxiv.org/abs/1412.6980
|
|
|
|
.. _On the Convergence of Adam and Beyond:
|
|
|
|
https://openreview.net/forum?id=ryQu7f-RZ
|
|
|
|
"""
|
|
|
|
|
2022-03-21 05:35:04 +00:00
|
|
|
def __init__(self,
|
|
|
|
params,
|
|
|
|
lr=1e-3,
|
|
|
|
bias_correction=True,
|
|
|
|
betas=(0.9, 0.999),
|
|
|
|
eps=1e-8,
|
2022-03-25 06:15:53 +00:00
|
|
|
adamw_mode=True,
|
2022-03-21 05:35:04 +00:00
|
|
|
weight_decay=0.,
|
|
|
|
amsgrad=False,
|
|
|
|
set_grad_none=True):
|
2021-10-28 16:21:23 +00:00
|
|
|
|
|
|
|
if amsgrad:
|
2022-03-21 05:35:04 +00:00
|
|
|
raise RuntimeError('FusedAdam does not support the AMSGrad variant.')
|
|
|
|
defaults = dict(lr=lr, bias_correction=bias_correction, betas=betas, eps=eps, weight_decay=weight_decay)
|
2021-10-28 16:21:23 +00:00
|
|
|
super(FusedAdam, self).__init__(params, defaults)
|
2022-03-25 06:15:53 +00:00
|
|
|
self.adamw_mode = 1 if adamw_mode else 0
|
2021-10-28 16:21:23 +00:00
|
|
|
self.set_grad_none = set_grad_none
|
|
|
|
if multi_tensor_applier.available:
|
|
|
|
import colossal_C
|
|
|
|
# Skip buffer
|
|
|
|
self._dummy_overflow_buf = torch.cuda.IntTensor([0])
|
|
|
|
self.multi_tensor_adam = colossal_C.multi_tensor_adam
|
|
|
|
else:
|
2022-01-13 08:47:17 +00:00
|
|
|
raise RuntimeError('FusedAdam requires cuda extensions')
|
2021-10-28 16:21:23 +00:00
|
|
|
|
2022-03-30 10:14:59 +00:00
|
|
|
def zero_grad(self, set_to_none=False):
|
|
|
|
if set_to_none:
|
2021-10-28 16:21:23 +00:00
|
|
|
for group in self.param_groups:
|
|
|
|
for p in group['params']:
|
|
|
|
p.grad = None
|
|
|
|
else:
|
|
|
|
super(FusedAdam, self).zero_grad()
|
|
|
|
|
|
|
|
def step(self, closure=None, grads=None, output_params=None, scale=None, grad_norms=None):
|
|
|
|
"""Performs a single optimization step.
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
closure (callable, optional): A closure that reevaluates the model
|
|
|
|
and returns the loss.
|
|
|
|
|
|
|
|
The remaining arguments are deprecated, and are only retained (for the moment) for error-checking purposes.
|
|
|
|
"""
|
|
|
|
if any(p is not None for p in [grads, output_params, scale, grad_norms]):
|
|
|
|
raise RuntimeError(
|
2022-03-21 05:35:04 +00:00
|
|
|
'FusedAdam has been updated. Simply initialize it identically to torch.optim.Adam, and call step() with no arguments.'
|
|
|
|
)
|
2021-10-28 16:21:23 +00:00
|
|
|
loss = None
|
|
|
|
if closure is not None:
|
|
|
|
loss = closure()
|
|
|
|
|
|
|
|
for group in self.param_groups:
|
|
|
|
bias_correction = 1 if group['bias_correction'] else 0
|
|
|
|
beta1, beta2 = group['betas']
|
|
|
|
|
|
|
|
# assume same step across group now to simplify things
|
|
|
|
# per parameter step can be easily support by making it tensor, or pass list into kernel
|
|
|
|
if 'step' in group:
|
|
|
|
group['step'] += 1
|
|
|
|
else:
|
|
|
|
group['step'] = 1
|
|
|
|
|
|
|
|
# create lists for multi-tensor apply
|
2022-03-25 06:15:53 +00:00
|
|
|
g_l, p_l, m_l, v_l = [], [], [], []
|
2021-10-28 16:21:23 +00:00
|
|
|
|
|
|
|
for p in group['params']:
|
|
|
|
if p.grad is None:
|
|
|
|
continue
|
|
|
|
if p.grad.data.is_sparse:
|
|
|
|
raise RuntimeError(
|
|
|
|
'FusedAdam does not support sparse gradients, please consider SparseAdam instead')
|
|
|
|
|
|
|
|
state = self.state[p]
|
|
|
|
# State initialization
|
|
|
|
if len(state) == 0:
|
|
|
|
# Exponential moving average of gradient values
|
2022-07-29 11:33:24 +00:00
|
|
|
state['exp_avg'] = torch.zeros_like(p)
|
2021-10-28 16:21:23 +00:00
|
|
|
# Exponential moving average of squared gradient values
|
2022-07-29 11:33:24 +00:00
|
|
|
state['exp_avg_sq'] = torch.zeros_like(p)
|
2021-10-28 16:21:23 +00:00
|
|
|
|
2022-03-25 06:15:53 +00:00
|
|
|
if p.dtype not in [torch.float16, torch.float32]:
|
2021-10-28 16:21:23 +00:00
|
|
|
raise RuntimeError('FusedAdam only support fp16 and fp32.')
|
2022-04-01 08:27:03 +00:00
|
|
|
|
2022-03-25 06:15:53 +00:00
|
|
|
g_l.append(p.grad.data)
|
|
|
|
p_l.append(p.data)
|
|
|
|
m_l.append(state['exp_avg'])
|
|
|
|
v_l.append(state['exp_avg_sq'])
|
|
|
|
|
2022-04-01 08:27:03 +00:00
|
|
|
multi_tensor_applier(self.multi_tensor_adam, self._dummy_overflow_buf, [g_l, p_l, m_l, v_l], group['lr'],
|
|
|
|
beta1, beta2, group['eps'], group['step'], self.adamw_mode, bias_correction,
|
|
|
|
group['weight_decay'])
|
2021-10-28 16:21:23 +00:00
|
|
|
|
|
|
|
return loss
|