cyd0806 commited on
Commit
e351fd6
·
verified ·
1 Parent(s): 33305a0

Upload apex-master/tests/L0/run_optimizers/test_lamb.py with huggingface_hub

Browse files
apex-master/tests/L0/run_optimizers/test_lamb.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+ import os
3
+
4
+ import torch
5
+ from torch.optim import Optimizer
6
+ import apex
7
+ from apex.multi_tensor_apply import multi_tensor_applier
8
+ from itertools import product
9
+
10
+ class RefLAMB(Optimizer):
11
+ r"""Implements Lamb algorithm.
12
+
13
+ It has been proposed in `Large Batch Optimization for Deep Learning: Training BERT in 76 minutes`_.
14
+
15
+ Arguments:
16
+ params (iterable): iterable of parameters to optimize or dicts defining
17
+ parameter groups
18
+ lr (float, optional): learning rate (default: 1e-3)
19
+ betas (Tuple[float, float], optional): coefficients used for computing
20
+ running averages of gradient and its square (default: (0.9, 0.999))
21
+ eps (float, optional): term added to the denominator to improve
22
+ numerical stability (default: 1e-6)
23
+ weight_decay (float, optional): weight decay (L2 penalty) (default: 0.01)
24
+
25
+ .. _Large Batch Optimization for Deep Learning: Training BERT in 76 minutes:
26
+ https://arxiv.org/abs/1904.00962
27
+ """
28
+
29
+ def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-6, weight_decay=0.01):
30
+ if not 0.0 <= lr:
31
+ raise ValueError("Invalid learning rate: {}".format(lr))
32
+ if not 0.0 <= eps:
33
+ raise ValueError("Invalid epsilon value: {}".format(eps))
34
+ if not 0.0 <= betas[0] < 1.0:
35
+ raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0]))
36
+ if not 0.0 <= betas[1] < 1.0:
37
+ raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1]))
38
+ defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay)
39
+ super(RefLAMB, self).__init__(params, defaults)
40
+ if multi_tensor_applier.available:
41
+ import amp_C
42
+ self.multi_tensor_l2norm=amp_C.multi_tensor_l2norm
43
+ # Skip buffer
44
+ self._dummy_overflow_buf = torch.tensor([0], dtype=torch.int, device=self.param_groups[0]["params"][0].device)
45
+ self.multi_tensor_lamb = amp_C.multi_tensor_lamb
46
+ else:
47
+ raise RuntimeError('apex.optimizers.FusedLAMB requires cuda extensions')
48
+
49
+ def step(self, closure=None):
50
+ """Performs a single optimization step.
51
+ Arguments:
52
+ closure (callable, optional): A closure that reevaluates the model
53
+ and returns the loss.
54
+ """
55
+ loss = None
56
+ if closure is not None:
57
+ loss = closure()
58
+
59
+ # create separate grad lists for fp32, fp16, and bf16 params
60
+ g_all_32, g_all_16, g_all_bf16 = [], [], []
61
+ for group in self.param_groups:
62
+ for p in group['params']:
63
+ if p.grad is None:
64
+ continue
65
+ if p.dtype == torch.float32:
66
+ g_all_32.append(p.grad.data)
67
+ elif p.dtype == torch.float16:
68
+ g_all_16.append(p.grad.data)
69
+ elif p.dtype == torch.bfloat16:
70
+ g_all_bf16.append(p.grad.data)
71
+ else:
72
+ raise RuntimeError('FusedLAMB only support fp16, fp32, and bf16.')
73
+
74
+ device = self.param_groups[0]["params"][0].device
75
+ g_norm_32, g_norm_16, g_norm_bf16 = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)
76
+ # compute grad norm for two lists
77
+ if len(g_all_32) > 0:
78
+ g_norm_32 = multi_tensor_applier(self.multi_tensor_l2norm,
79
+ self._dummy_overflow_buf,
80
+ [g_all_32], False)[0]
81
+ if len(g_all_16) > 0:
82
+ g_norm_16 = multi_tensor_applier(self.multi_tensor_l2norm,
83
+ self._dummy_overflow_buf,
84
+ [g_all_16], False)[0]
85
+ if len(g_all_bf16) > 0:
86
+ g_norm_bf16 = multi_tensor_applier(self.multi_tensor_l2norm,
87
+ self._dummy_overflow_buf,
88
+ [g_all_bf16], False)[0]
89
+
90
+ # blend two grad norms to get global grad norm
91
+ global_grad_norm = multi_tensor_applier(self.multi_tensor_l2norm,
92
+ self._dummy_overflow_buf,
93
+ [[g_norm_32, g_norm_16, g_norm_bf16]],
94
+ False)[0]
95
+
96
+ max_grad_norm = 1.0
97
+ clipped_ratio = max_grad_norm / max(global_grad_norm, max_grad_norm)
98
+
99
+ for group in self.param_groups:
100
+ for p in group['params']:
101
+ if p.grad is None:
102
+ continue
103
+ p.grad.data *= clipped_ratio
104
+ grad = p.grad.data
105
+ if grad.is_sparse:
106
+ raise RuntimeError('Lamb does not support sparse gradients, consider SparseAdam instad.')
107
+
108
+ state = self.state[p]
109
+
110
+ # State initialization
111
+ if len(state) == 0:
112
+ state['step'] = 0
113
+ # Exponential moving average of gradient values
114
+ state['m'] = torch.zeros_like(p.data)
115
+ # Exponential moving average of squared gradient values
116
+ state['v'] = torch.zeros_like(p.data)
117
+
118
+ m_t, v_t = state['m'], state['v']
119
+ beta1, beta2 = group['betas']
120
+
121
+ state['step'] += 1
122
+
123
+ # m_t = beta1 * m + (1 - beta1) * g_t
124
+ m_t.mul_(beta1).add_(grad, alpha=1-beta1)
125
+ # v_t = beta2 * v + (1 - beta2) * (g_t * g_t)
126
+ if len(g_all_16) > 0:
127
+ v_t.mul_(beta2)
128
+ v_t = v_t.to(torch.float32)
129
+ grad32 = grad.to(torch.float32)
130
+ v_t.addcmul_(grad32, grad32, value=1-beta2)
131
+ else:
132
+ v_t.mul_(beta2).addcmul_(grad, grad, value=1-beta2)
133
+
134
+ # Debiasing
135
+ m_t_hat = m_t / (1.0 - beta1 ** state['step'])
136
+ v_t_hat = v_t / (1.0 - beta2 ** state['step'])
137
+
138
+ update = m_t_hat / v_t_hat.sqrt().add(group['eps'])
139
+
140
+ if group['weight_decay'] != 0:
141
+ update.add_(p.data, alpha=group['weight_decay'])
142
+
143
+ trust_ratio = 1.0
144
+ w_norm = p.data.to(torch.float32).pow(2).sum().sqrt()
145
+ g_norm = update.pow(2).sum().sqrt()
146
+ if w_norm > 0 and g_norm > 0:
147
+ trust_ratio = w_norm / g_norm
148
+
149
+ state['w_norm'] = w_norm
150
+ state['g_norm'] = g_norm
151
+ state['trust_ratio'] = trust_ratio
152
+
153
+ step_size = group['lr']
154
+
155
+ p.data.add_(update, alpha=-step_size*trust_ratio)
156
+
157
+ return loss
158
+
159
+ class TestLamb(unittest.TestCase):
160
+ def setUp(self, max_abs_diff=1e-3, max_rel_diff=1, iters=7):
161
+ self.max_abs_diff = max_abs_diff
162
+ self.max_rel_diff = max_rel_diff
163
+ self.iters = iters
164
+ torch.cuda.manual_seed(9876)
165
+
166
+
167
+ def tearDown(self):
168
+ pass
169
+
170
+ def gen_param_optim(self, tensors, lamb_option):
171
+ ref_param = []
172
+ tst_param = []
173
+ for tensor in tensors:
174
+ ref_param.append(torch.nn.Parameter(tensor.clone()))
175
+ tst_param.append(torch.nn.Parameter(tensor.clone()))
176
+
177
+ ref_optim = self.ref_optim(ref_param, **lamb_option)
178
+ tst_optim = self.tst_optim(tst_param, use_nvlamb=True, **lamb_option)
179
+
180
+ return (ref_param, tst_param, ref_optim, tst_optim)
181
+
182
+ def gen_grad(self, ref_param, tst_param):
183
+ for p_ref, p_tst in zip(ref_param, tst_param):
184
+ p_ref.grad = torch.rand_like(p_ref)
185
+ p_tst.grad = p_ref.grad
186
+
187
+ def gen_mixed_grad(self, ref_param, tst_param, scale=1.0):
188
+ half_grads = []
189
+ for p_ref, _ in zip(ref_param, tst_param):
190
+ half_grads.append(torch.rand_like(p_ref).half())
191
+ p_ref.grad = half_grads[-1].float() / scale
192
+ return half_grads
193
+
194
+ def gen_single_type_test(self, param_type=torch.float, device="cuda"):
195
+ nelem = 18011
196
+ tensor = torch.rand(nelem, dtype=param_type, device=device)
197
+ weight_decay = [0, 0.01]
198
+
199
+ for wd in weight_decay:
200
+ lamb_option = {'lr':5e-4, 'betas':(0.9, 0.999), 'eps':1e-08, 'weight_decay':wd}
201
+ ref_param, tst_param, ref_optim, tst_optim = \
202
+ self.gen_param_optim([tensor], lamb_option)
203
+
204
+ if isinstance(tst_optim, apex.optimizers.FusedMixedPrecisionLamb):
205
+ if param_type != torch.float:
206
+ # joseli: This parameter is usually passed into the constructor,
207
+ # but I do not want to change the testing interface.
208
+ # As long as this parameter is set before the first call to step(),
209
+ # then it should act normally.
210
+ tst_optim.reduced_precision_dtype = param_type
211
+ for i in range(self.iters):
212
+ self.gen_grad(ref_param, tst_param)
213
+ ref_optim.step()
214
+ torch.cuda.synchronize()
215
+ tst_optim.step()
216
+ torch.cuda.synchronize()
217
+ torch.testing.assert_close(tst_param, ref_param)
218
+
219
+ class TestFusedLAMB(TestLamb):
220
+ def __init__(self, *args, **kwargs):
221
+ super(TestLamb, self).__init__(*args, **kwargs)
222
+ self.ref_optim = RefLAMB
223
+ self.tst_optim = apex.optimizers.FusedLAMB
224
+
225
+
226
+ def test_float(self):
227
+ self.gen_single_type_test(param_type=torch.float)
228
+
229
+ @unittest.skip("PyTorch optimizer is not numerically correct for fp16")
230
+ def test_half(self):
231
+ self.gen_single_type_test(param_type=torch.float16)
232
+
233
+ @unittest.skipIf(torch.cuda.device_count()<2, "more than 1 GPU required")
234
+ def test_multi_device(self):
235
+ devices = ("cuda:0", "cuda:1")
236
+ for current_dev, tensor_dev in product(devices, devices):
237
+ with torch.cuda.device(current_dev):
238
+ self.gen_single_type_test(param_type=torch.float, device=tensor_dev)
239
+
240
+ def test_multi_params(self):
241
+ sizes = [[4096, 1024], [4096], [4096, 2048], [32320, 1024], [1]]
242
+ weight_decay = [0, 0.01]
243
+
244
+ for wd in weight_decay:
245
+ lamb_option = {'lr':5e-4, 'betas':(0.9, 0.999), 'eps':1e-08, 'weight_decay':wd}
246
+ tensors = []
247
+ for size in sizes:
248
+ tensors.append(torch.rand(size, dtype=torch.float, device='cuda'))
249
+ ref_param, tst_param, ref_optim, tst_optim = \
250
+ self.gen_param_optim(tensors, lamb_option)
251
+
252
+ for i in range(self.iters):
253
+ self.gen_grad(ref_param, tst_param)
254
+ ref_optim.step()
255
+ tst_optim.step()
256
+ torch.testing.assert_close(tst_param, ref_param)
257
+
258
+ def test_lamb_option(self):
259
+ nelem = 1
260
+ tensor = torch.rand(nelem, dtype=torch.float, device='cuda')
261
+ weight_decay = [0, 0.01]
262
+
263
+ for wd in weight_decay:
264
+ lamb_option = {'lr':0.01, 'betas':(0.6, 0.9), 'eps':3e-06, 'weight_decay':wd}
265
+ ref_param, tst_param, ref_optim, tst_optim = \
266
+ self.gen_param_optim([tensor], lamb_option)
267
+
268
+ for i in range(self.iters):
269
+ self.gen_grad(ref_param, tst_param)
270
+ ref_optim.step()
271
+ tst_optim.step()
272
+ torch.testing.assert_close(tst_param, ref_param)
273
+
274
+ class TestFusedMixedPrecisionLamb(TestLamb):
275
+ def __init__(self, *args, **kwargs):
276
+ super(TestLamb, self).__init__(*args, **kwargs)
277
+ self.ref_optim = RefLAMB
278
+ self.tst_optim = apex.optimizers.FusedMixedPrecisionLamb
279
+
280
+
281
+ def test_float(self):
282
+ self.gen_single_type_test(param_type=torch.float)
283
+
284
+ def test_bfloat16(self):
285
+ self.iters = 4
286
+ self.gen_single_type_test(param_type=torch.bfloat16)
287
+
288
+ def test_half(self):
289
+ self.iters = 1
290
+ self.gen_single_type_test(param_type=torch.float16)
291
+
292
+ @unittest.skipIf(torch.cuda.device_count()<2, "more than 1 GPU required")
293
+ def test_multi_device(self):
294
+ devices = ("cuda:0", "cuda:1")
295
+ for current_dev, tensor_dev in product(devices, devices):
296
+ with torch.cuda.device(current_dev):
297
+ self.gen_single_type_test(param_type=torch.float, device=tensor_dev)
298
+
299
+ def test_multi_params(self):
300
+ sizes = [[4096, 1024], [4096], [4096, 2048], [32320, 1024], [1]]
301
+ weight_decay = [0, 0.01]
302
+
303
+ for wd in weight_decay:
304
+ lamb_option = {'lr':5e-4, 'betas':(0.9, 0.999), 'eps':1e-08, 'weight_decay':wd}
305
+ tensors = []
306
+ for size in sizes:
307
+ tensors.append(torch.rand(size, dtype=torch.float, device='cuda'))
308
+ ref_param, tst_param, ref_optim, tst_optim = \
309
+ self.gen_param_optim(tensors, lamb_option)
310
+
311
+ for i in range(self.iters):
312
+ self.gen_grad(ref_param, tst_param)
313
+ ref_optim.step()
314
+ tst_optim.step()
315
+ torch.testing.assert_close(tst_param, ref_param)
316
+
317
+ def test_lamb_option(self):
318
+ nelem = 1
319
+ tensor = torch.rand(nelem, dtype=torch.float, device='cuda')
320
+ weight_decay = [0, 0.01]
321
+
322
+ for wd in weight_decay:
323
+ lamb_option = {'lr':0.01, 'betas':(0.6, 0.9), 'eps':3e-06, 'weight_decay':wd}
324
+ ref_param, tst_param, ref_optim, tst_optim = \
325
+ self.gen_param_optim([tensor], lamb_option)
326
+
327
+ for i in range(self.iters):
328
+ self.gen_grad(ref_param, tst_param)
329
+ ref_optim.step()
330
+ tst_optim.step()
331
+ torch.testing.assert_close(tst_param, ref_param)
332
+
333
+ if __name__ == '__main__':
334
+ script_path = os.path.dirname(os.path.realpath(__file__))
335
+ unittest.main()