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

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

Browse files
apex-master/tests/L0/run_optimizers/test_fused_optimizer.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import product
2
+ import random
3
+ import unittest
4
+
5
+ import torch
6
+
7
+ import apex
8
+
9
+
10
+ class TestFusedOptimizer(unittest.TestCase):
11
+ def setUp(self, max_abs_diff=1e-3, max_rel_diff=1, iters=7):
12
+ self.max_abs_diff = max_abs_diff
13
+ self.max_rel_diff = max_rel_diff
14
+ self.iters = iters
15
+ torch.manual_seed(9876)
16
+
17
+ def tearDown(self):
18
+ pass
19
+
20
+ def gen_param_optim(self, tensors, options, tst_options=None):
21
+
22
+ # Adding this to make backward compatible with existing tests. Just in
23
+ # case "tst_options" are not provided, it gets a copy of options
24
+ # which contains the parameters for the reference optimizer
25
+ if tst_options == None:
26
+ tst_options = options
27
+
28
+ ref_param = []
29
+ tst_param = []
30
+ for tensor in tensors:
31
+ ref_param.append(torch.nn.Parameter(tensor.clone()))
32
+ tst_param.append(torch.nn.Parameter(tensor.clone()))
33
+
34
+ ref_optim = self.ref_optim(ref_param, **options)
35
+ tst_optim = self.fused_optim(tst_param, **tst_options)
36
+
37
+ return (ref_param, tst_param, ref_optim, tst_optim)
38
+
39
+ def gen_grad(self, ref_param, tst_param):
40
+ for p_ref, p_tst in zip(ref_param, tst_param):
41
+ p_ref.grad = torch.rand_like(p_ref)
42
+ p_tst.grad = p_ref.grad
43
+
44
+ def gen_mixed_grad(self, ref_param, tst_param, scale=1.0):
45
+ half_grads = []
46
+ for p_ref, p_tst in zip(ref_param, tst_param):
47
+ half_grads.append(torch.rand_like(p_ref).half())
48
+ p_ref.grad = half_grads[-1].float() / scale
49
+ return half_grads
50
+
51
+ def get_max_diff(self, ref_param, tst_param):
52
+ max_abs_diff = max_rel_diff = 0
53
+ for p_ref, p_tst in zip(ref_param, tst_param):
54
+ max_abs_diff_p = (p_ref - p_tst).abs().max().item()
55
+ max_rel_diff_p = ((p_ref - p_tst) / p_ref).abs().max().item()
56
+
57
+ if max_abs_diff_p > max_abs_diff: max_abs_diff = max_abs_diff_p
58
+ if max_rel_diff_p > max_rel_diff: max_rel_diff = max_rel_diff_p
59
+
60
+ return max_abs_diff, max_rel_diff
61
+
62
+ def gen_single_type_test(self, param_type=torch.float, device='cuda', *, skip_assert: bool = False):
63
+ nelem = 278011
64
+
65
+ # Some ref and test optimizers may require different set of options.
66
+ # This is a quick workaround to add that functionality while making
67
+ # minimum changes in existing code.
68
+ # If there is no "tst_options" field provided, safe to initialize
69
+ # the test optimizer with the parameters of reference optimizer.
70
+ if not hasattr(self, 'tst_options'):
71
+ self.tst_options = self.options
72
+
73
+ tensor = torch.rand(nelem, dtype=param_type, device=device)
74
+
75
+ ref_param, tst_param, ref_optim, tst_optim = \
76
+ self.gen_param_optim([tensor], self.options, self.tst_options)
77
+
78
+ for i in range(self.iters):
79
+ self.gen_grad(ref_param, tst_param)
80
+ ref_optim.step()
81
+ tst_optim.step()
82
+ if skip_assert:
83
+ return
84
+ max_abs_diff, max_rel_diff = self.get_max_diff(ref_param, tst_param)
85
+ self.assertLessEqual(max_abs_diff, self.max_abs_diff)
86
+ self.assertLessEqual(max_rel_diff, self.max_rel_diff)
87
+
88
+
89
+ class TestFusedAdam(TestFusedOptimizer):
90
+
91
+ def setUp(self):
92
+ super().setUp()
93
+ self.options = {'lr':5e-4, 'betas':(0.9, 0.999), 'eps':1e-08,
94
+ 'weight_decay': 0, 'amsgrad': False}
95
+ self.ref_optim = torch.optim.Adam
96
+ self.fused_optim = apex.optimizers.FusedAdam
97
+
98
+ def test_float(self):
99
+ self.gen_single_type_test(param_type=torch.float)
100
+
101
+ # NOTE(mkozuki): Current threshold values look too small for BFloat16.
102
+ # TODO(mkozuki): Refactor `TestFusedOptimizer`
103
+ def test_half(self):
104
+ self.gen_single_type_test(param_type=torch.float16, skip_assert=True)
105
+
106
+ def test_bfloat16(self):
107
+ self.gen_single_type_test(param_type=torch.bfloat16, skip_assert=True)
108
+
109
+ @unittest.skipIf(torch.cuda.device_count()<2, "more than 1 GPU required")
110
+ def test_multi_device(self):
111
+ devices = ("cuda:0", "cuda:1")
112
+ for current_dev, tensor_dev in product(devices, devices):
113
+ with torch.cuda.device(current_dev):
114
+ self.gen_single_type_test(param_type=torch.float, device=tensor_dev)
115
+
116
+ @unittest.skip('Disable until 8/1/2019 adam/adamw upstream picked')
117
+ def test_multi_params(self):
118
+ sizes = [[4096, 1024], [4096], [4096, 2048], [32320, 1024], [1]]
119
+
120
+ tensors = []
121
+ for size in sizes:
122
+ tensors.append(torch.rand(size, dtype=torch.float, device='cuda'))
123
+ ref_param, tst_param, ref_optim, tst_optim = \
124
+ self.gen_param_optim(tensors, self.options)
125
+
126
+ for i in range(self.iters):
127
+ self.gen_grad(ref_param, tst_param)
128
+ ref_optim.step()
129
+ tst_optim.step()
130
+ max_abs_diff, max_rel_diff = self.get_max_diff(ref_param, tst_param)
131
+ self.assertLessEqual(max_abs_diff, self.max_abs_diff)
132
+ self.assertLessEqual(max_rel_diff, self.max_rel_diff)
133
+
134
+ @unittest.skip('No longer support fuse scaling')
135
+ def test_scale(self):
136
+ nelem = 278011
137
+ tensor = torch.rand(nelem, dtype=torch.float, device='cuda')
138
+ ref_param, tst_param, ref_optim, tst_optim = \
139
+ self.gen_param_optim([tensor], self.options)
140
+
141
+ for i in range(self.iters):
142
+ scale = random.random() * 1000
143
+ half_grads = self.gen_mixed_grad(ref_param, tst_param, scale)
144
+ ref_optim.step()
145
+ tst_optim.step(grads=half_grads, scale=scale)
146
+ max_abs_diff, max_rel_diff = self.get_max_diff(ref_param, tst_param)
147
+
148
+ self.assertLessEqual(max_abs_diff, self.max_abs_diff)
149
+ self.assertLessEqual(max_rel_diff, self.max_rel_diff)
150
+
151
+ @unittest.skip('No longer support output fp16 param')
152
+ def test_fp16_output(self):
153
+ nelem = 278011
154
+
155
+ tensor = torch.rand(nelem, dtype=torch.float, device='cuda')
156
+ ref_param, tst_param, ref_optim, tst_optim = \
157
+ self.gen_param_optim([tensor], self.options)
158
+
159
+ fp16_param = torch.nn.Parameter(tensor.clone().half())
160
+
161
+ for i in range(self.iters):
162
+ half_grads = self.gen_mixed_grad(ref_param, tst_param)
163
+ ref_optim.step()
164
+ tst_optim.step(grads=half_grads, output_params=[fp16_param])
165
+
166
+ max_abs_diff, max_rel_diff = self.get_max_diff(ref_param, tst_param)
167
+ self.assertLessEqual(max_abs_diff, self.max_abs_diff)
168
+ self.assertLessEqual(max_rel_diff, self.max_rel_diff)
169
+
170
+ max_abs_diff, max_rel_diff = self.get_max_diff(tst_param, \
171
+ [fp16_param.float()])
172
+ self.assertLessEqual(max_abs_diff, self.max_abs_diff)
173
+ self.assertLessEqual(max_rel_diff, self.max_rel_diff)
174
+
175
+ def test_adam_option(self):
176
+ nelem = 1
177
+ adam_option = {'lr':0.01, 'betas':(0.6, 0.9), 'eps':3e-06,
178
+ 'weight_decay':0, 'amsgrad':False}
179
+
180
+ tensor = torch.rand(nelem, dtype=torch.float, device='cuda')
181
+ ref_param, tst_param, ref_optim, tst_optim = \
182
+ self.gen_param_optim([tensor], adam_option)
183
+
184
+ for i in range(self.iters):
185
+ self.gen_grad(ref_param, tst_param)
186
+ ref_optim.step()
187
+ tst_optim.step()
188
+ max_abs_diff, max_rel_diff = self.get_max_diff(ref_param, tst_param)
189
+
190
+ self.assertLessEqual(max_abs_diff, self.max_abs_diff)
191
+ self.assertLessEqual(max_rel_diff, self.max_rel_diff)
192
+
193
+ def test_frozen_model(self):
194
+ nelem = 1
195
+ adam_option = {'lr':0.01, 'betas':(0.6, 0.9), 'eps':3e-06,
196
+ 'weight_decay':0, 'amsgrad':False}
197
+
198
+ tensor = torch.rand(nelem, dtype=torch.float, device='cuda')
199
+ ref_param, tst_param, ref_optim, tst_optim = \
200
+ self.gen_param_optim([tensor], adam_option)
201
+
202
+ #Add an empty param group which may occur for pipeline parallel p-tuning
203
+ tst_optim.add_param_group({"params": []})
204
+
205
+ for i in range(self.iters):
206
+ self.gen_grad(ref_param, tst_param)
207
+ ref_optim.step()
208
+ tst_optim.step()
209
+ max_abs_diff, max_rel_diff = self.get_max_diff(ref_param, tst_param)
210
+
211
+ self.assertLessEqual(max_abs_diff, self.max_abs_diff)
212
+ self.assertLessEqual(max_rel_diff, self.max_rel_diff)
213
+
214
+
215
+ class TestFusedAdagrad(TestFusedOptimizer):
216
+ def __init__(self, *args, **kwargs):
217
+ super(TestFusedAdagrad, self).__init__(*args, **kwargs)
218
+ self.options = {"lr": 5e-4, "eps": 1e-08, "weight_decay": 1.0e-5}
219
+ self.ref_optim = torch.optim.Adagrad
220
+ self.fused_optim = apex.optimizers.FusedAdagrad
221
+
222
+ def test_float(self):
223
+ self.gen_single_type_test(param_type=torch.float)
224
+
225
+ @unittest.skip("PyTorch optimizer is not numerically correct for fp16")
226
+ def test_half(self):
227
+ self.gen_single_type_test(param_type=torch.float16)
228
+
229
+ @unittest.skipIf(torch.cuda.device_count()<2, "more than 1 GPU required")
230
+ def test_multi_device(self):
231
+ devices = ("cuda:0", "cuda:1")
232
+ for current_dev, tensor_dev in product(devices, devices):
233
+ with torch.cuda.device(current_dev):
234
+ self.gen_single_type_test(param_type=torch.float, device=tensor_dev)
235
+
236
+
237
+ def test_multi_params(self):
238
+ sizes = [[4096, 1024], [4096], [4096, 2048], [32320, 1024], [1]]
239
+ adagrad_option = {"lr": 5e-4, "eps": 1e-08, "weight_decay": 0}
240
+
241
+ tensors = []
242
+ for size in sizes:
243
+ tensors.append(torch.rand(size, dtype=torch.float, device="cuda"))
244
+ ref_param, tst_param, ref_optim, tst_optim = self.gen_param_optim(
245
+ tensors, adagrad_option
246
+ )
247
+
248
+ for _ in range(self.iters):
249
+ self.gen_grad(ref_param, tst_param)
250
+ ref_optim.step()
251
+ tst_optim.step()
252
+ max_abs_diff, max_rel_diff = self.get_max_diff(ref_param, tst_param)
253
+ self.assertLessEqual(max_abs_diff, self.max_abs_diff)
254
+ self.assertLessEqual(max_rel_diff, self.max_rel_diff)
255
+
256
+ @unittest.skipIf(torch.cuda.device_count()<2, "more than 1 GPU required")
257
+ def test_multi_params_different_devices_throws(self):
258
+ sizes = [[4096, 1024], [4096], [4096, 2048], [32320, 1024], [1]]
259
+ adagrad_option = {"lr": 5e-4, "eps": 1e-08, "weight_decay": 0}
260
+
261
+ tensors = []
262
+ for i, size in enumerate(sizes):
263
+ tensors.append(torch.rand(size, dtype=torch.float, device="cuda:"+str(i % 2)))
264
+ ref_param, tst_param, ref_optim, tst_optim = self.gen_param_optim(
265
+ tensors, adagrad_option
266
+ )
267
+ self.gen_grad(ref_param, tst_param)
268
+ with self.assertRaisesRegex(RuntimeError, "not on the same device"):
269
+ tst_optim.step()
270
+
271
+ def test_adagrad_option(self):
272
+ nelem = 1
273
+ adagrad_option = {"lr": 0.01, "eps": 3e-06, "weight_decay": 0}
274
+
275
+ tensor = torch.rand(nelem, dtype=torch.float, device="cuda")
276
+ ref_param, tst_param, ref_optim, tst_optim = self.gen_param_optim(
277
+ [tensor], adagrad_option
278
+ )
279
+
280
+ for _ in range(self.iters):
281
+ self.gen_grad(ref_param, tst_param)
282
+ ref_optim.step()
283
+ tst_optim.step()
284
+ max_abs_diff, max_rel_diff = self.get_max_diff(ref_param, tst_param)
285
+
286
+ self.assertLessEqual(max_abs_diff, self.max_abs_diff)
287
+ self.assertLessEqual(max_rel_diff, self.max_rel_diff)
288
+
289
+
290
+ class TestFusedSGD(TestFusedOptimizer):
291
+ def __init__(self, *args, **kwargs):
292
+ super(TestFusedSGD, self).__init__(*args, **kwargs)
293
+ self.options = {"lr": .25, "momentum": .125}
294
+ self.ref_optim = torch.optim.SGD
295
+ self.fused_optim = apex.optimizers.FusedSGD
296
+
297
+ def test_float(self):
298
+ self.gen_single_type_test(param_type=torch.float)
299
+
300
+ def test_half(self):
301
+ self.gen_single_type_test(param_type=torch.float16)
302
+
303
+ @unittest.skipIf(torch.cuda.device_count()<2, "more than 1 GPU required")
304
+ def test_multi_device(self):
305
+ devices = ("cuda:0", "cuda:1")
306
+ for current_dev, tensor_dev in product(devices, devices):
307
+ with torch.cuda.device(current_dev):
308
+ self.gen_single_type_test(param_type=torch.float, device=tensor_dev)
309
+
310
+ if __name__ == '__main__':
311
+ unittest.main()