test_fp16.py 28.7 KB
Newer Older
1
2
3
4
5
6
import torch
import deepspeed
import argparse
import pytest
import json
import os
7
from deepspeed.ops.adam import FusedAdam
8
from common import distributed_test
9
from simple_model import SimpleModel, SimpleOptimizer, random_dataloader, args_from_dict, create_deepspeed_args
Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
10
from deepspeed.ops.op_builder import CPUAdamBuilder
11

12
13
14
15
16
17
try:
    from apex import amp
    _amp_available = True
except ImportError:
    _amp_available = False
amp_available = pytest.mark.skip(_amp_available, reason="apex/amp is not installed")
18

19

20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def test_lamb_fp32_grad_clip(tmpdir):
    config_dict = {
        "train_batch_size": 2,
        "steps_per_print": 1,
        "optimizer": {
            "type": "Lamb",
            "params": {
                "lr": 0.00015
            }
        },
        "gradient_clipping": 1.0
    }
    args = args_from_dict(tmpdir, config_dict)
    hidden_dim = 10

35
    model = SimpleModel(hidden_dim)
36
37
38

    @distributed_test(world_size=[1, 2])
    def _test_lamb_fp32_grad_clip(args, model, hidden_dim):
39
40
41
        model, _, _, _ = deepspeed.initialize(args=args,
                                              model=model,
                                              model_parameters=model.parameters())
42
43
44
        data_loader = random_dataloader(model=model,
                                        total_samples=50,
                                        hidden_dim=hidden_dim,
Jeff Rasley's avatar
Jeff Rasley committed
45
46
                                        device=model.device,
                                        dtype=torch.float)
47
        for n, batch in enumerate(data_loader):
Jeff Rasley's avatar
Jeff Rasley committed
48
            loss = model(batch[0], batch[1])
49
50
51
52
53
54
            model.backward(loss)
            model.step()

    _test_lamb_fp32_grad_clip(args=args, model=model, hidden_dim=hidden_dim)


55
56
57
58
59
60
61
def test_lamb_fp16_basic(tmpdir):
    config_dict = {
        "train_batch_size": 2,
        "steps_per_print": 1,
        "optimizer": {
            "type": "Lamb",
            "params": {
62
                "lr": 0.00015
63
64
            }
        },
65
        "gradient_clipping": 1.0,
66
67
68
69
        "fp16": {
            "enabled": True
        }
    }
70
    args = args_from_dict(tmpdir, config_dict)
71
72
    hidden_dim = 10

73
    model = SimpleModel(hidden_dim)
74
75
76

    @distributed_test(world_size=[1, 2])
    def _test_lamb_fp16_basic(args, model, hidden_dim):
77
78
79
        model, _, _, _ = deepspeed.initialize(args=args,
                                              model=model,
                                              model_parameters=model.parameters())
80
81
82
83
        data_loader = random_dataloader(model=model,
                                        total_samples=50,
                                        hidden_dim=hidden_dim,
                                        device=model.device)
84
85
86
87
88
89
90
91
92
93
        for n, batch in enumerate(data_loader):
            loss = model(batch[0], batch[1])
            model.backward(loss)
            model.step()

    _test_lamb_fp16_basic(args=args, model=model, hidden_dim=hidden_dim)


def test_lamb_fp16_empty_grad(tmpdir):
    config_dict = {
Jeff Rasley's avatar
Jeff Rasley committed
94
        "train_batch_size": 2,
95
96
97
98
        "steps_per_print": 1,
        "optimizer": {
            "type": "Lamb",
            "params": {
99
                "lr": 0.00015
100
101
            }
        },
102
        "gradient_clipping": 1.0,
103
104
105
106
        "fp16": {
            "enabled": True
        }
    }
107
    args = args_from_dict(tmpdir, config_dict)
108
109
    hidden_dim = 10

110
    model = SimpleModel(hidden_dim, empty_grad=True)
111

Jeff Rasley's avatar
Jeff Rasley committed
112
    @distributed_test(world_size=[2])
113
    def _test_lamb_fp16_empty_grad(args, model, hidden_dim):
114
115
116
        model, _, _, _ = deepspeed.initialize(args=args,
                                              model=model,
                                              model_parameters=model.parameters())
117
118
119
120
        data_loader = random_dataloader(model=model,
                                        total_samples=50,
                                        hidden_dim=hidden_dim,
                                        device=model.device)
121
122
123
124
125
126
127
128
        for n, batch in enumerate(data_loader):
            loss = model(batch[0], batch[1])
            model.backward(loss)
            model.step()

    _test_lamb_fp16_empty_grad(args=args, model=model, hidden_dim=hidden_dim)


Jeff Rasley's avatar
Jeff Rasley committed
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def test_adam_fp32_empty_grad(tmpdir):
    config_dict = {
        "train_batch_size": 2,
        "steps_per_print": 1,
        "optimizer": {
            "type": "Adam",
            "params": {
                "lr": 0.00015
            }
        },
        "gradient_clipping": 1.0,
        "fp16": {
            "enabled": False
        }
    }
    args = args_from_dict(tmpdir, config_dict)
    hidden_dim = 10

147
    model = SimpleModel(hidden_dim, empty_grad=True)
Jeff Rasley's avatar
Jeff Rasley committed
148
149
150

    @distributed_test(world_size=[2])
    def _test_adam_fp32_empty_grad(args, model, hidden_dim):
151
152
153
        model, _, _, _ = deepspeed.initialize(args=args,
                                              model=model,
                                              model_parameters=model.parameters())
Jeff Rasley's avatar
Jeff Rasley committed
154
155
156
157
158
159
160
161
162
163
164
165
166
        data_loader = random_dataloader(model=model,
                                        total_samples=50,
                                        hidden_dim=hidden_dim,
                                        device=model.device,
                                        dtype=torch.float)
        for n, batch in enumerate(data_loader):
            loss = model(batch[0], batch[1])
            model.backward(loss)
            model.step()

    _test_adam_fp32_empty_grad(args=args, model=model, hidden_dim=hidden_dim)


167
168
169
170
171
172
173
174
def test_adamw_fp16_basic(tmpdir):
    config_dict = {
        "train_batch_size": 1,
        "steps_per_print": 1,
        "fp16": {
            "enabled": True
        }
    }
175
    args = args_from_dict(tmpdir, config_dict)
176
177
    hidden_dim = 10

178
    model = SimpleModel(hidden_dim)
179
180
181
182

    @distributed_test(world_size=[1])
    def _test_adamw_fp16_basic(args, model, hidden_dim):
        optimizer = torch.optim.AdamW(params=model.parameters())
183
184
185
        model, _, _, _ = deepspeed.initialize(args=args,
                                              model=model,
                                              optimizer=optimizer)
186
187
188
189
        data_loader = random_dataloader(model=model,
                                        total_samples=50,
                                        hidden_dim=hidden_dim,
                                        device=model.device)
190
191
192
193
194
195
196
197
        for n, batch in enumerate(data_loader):
            loss = model(batch[0], batch[1])
            model.backward(loss)
            model.step()

    _test_adamw_fp16_basic(args=args, model=model, hidden_dim=hidden_dim)


198
199
200
201
202
203
204
205
206
207
208
def test_dict_config_adamw_fp16_basic():
    config_dict = {
        "train_batch_size": 1,
        "steps_per_print": 1,
        "fp16": {
            "enabled": True
        }
    }
    args = create_deepspeed_args()
    hidden_dim = 10

209
    model = SimpleModel(hidden_dim)
210
211
212
213

    @distributed_test(world_size=[1])
    def _test_adamw_fp16_basic(args, model, hidden_dim, config_dict):
        optimizer = torch.optim.AdamW(params=model.parameters())
214
215
216
217
        model, _, _, _ = deepspeed.initialize(args=args,
                                              model=model,
                                              optimizer=optimizer,
                                              config_params=config_dict)
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
        data_loader = random_dataloader(model=model,
                                        total_samples=50,
                                        hidden_dim=hidden_dim,
                                        device=model.device)
        for n, batch in enumerate(data_loader):
            loss = model(batch[0], batch[1])
            model.backward(loss)
            model.step()

    _test_adamw_fp16_basic(args=args,
                           model=model,
                           hidden_dim=hidden_dim,
                           config_dict=config_dict)


233
234
235
236
237
238
239
240
def test_adamw_fp16_empty_grad(tmpdir):
    config_dict = {
        "train_batch_size": 1,
        "steps_per_print": 1,
        "fp16": {
            "enabled": True
        }
    }
241
    args = args_from_dict(tmpdir, config_dict)
242
243
    hidden_dim = 10

Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
244
    model = SimpleModel(hidden_dim, empty_grad=True)
245
246
247
248

    @distributed_test(world_size=[1])
    def _test_adamw_fp16_empty_grad(args, model, hidden_dim):
        optimizer = torch.optim.AdamW(params=model.parameters())
249
250
251
        model, _, _, _ = deepspeed.initialize(args=args,
                                              model=model,
                                              optimizer=optimizer)
252
253
254
255
        data_loader = random_dataloader(model=model,
                                        total_samples=50,
                                        hidden_dim=hidden_dim,
                                        device=model.device)
256
257
258
259
260
261
        for n, batch in enumerate(data_loader):
            loss = model(batch[0], batch[1])
            model.backward(loss)
            model.step()

    _test_adamw_fp16_empty_grad(args=args, model=model, hidden_dim=hidden_dim)
262
263


Jeff Rasley's avatar
Jeff Rasley committed
264
@pytest.mark.parametrize('zero_stage, use_cpu_offload',
Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
265
266
267
268
269
270
271
272
273
274
                         [(1,
                           False),
                          (2,
                           False),
                          (2,
                           True),
                          (3,
                           False),
                          (3,
                           True)])
Jeff Rasley's avatar
Jeff Rasley committed
275
def test_adam_fp16_zero_onecycle_compatibility(tmpdir, zero_stage, use_cpu_offload):
Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
276
277
278
    if use_cpu_offload and not deepspeed.ops.__compatible_ops__[CPUAdamBuilder.NAME]:
        pytest.skip("cpu-adam is not compatible")

279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
    config_dict = {
        "train_batch_size": 1,
        "steps_per_print": 1,
        "optimizer": {
            "type": "Adam",
            "params": {
                "lr": 0.00015
            }
        },
        "scheduler": {
            "type": "OneCycle",
            "params": {
                "cycle_first_step_size": 16000,
                "cycle_first_stair_count": 8000,
                "decay_step_size": 16000,
                "cycle_min_lr": 1e-06,
                "cycle_max_lr": 3e-05,
                "decay_lr_rate": 1e-07,
                "cycle_min_mom": 0.85,
                "cycle_max_mom": 0.99,
                "decay_mom_rate": 0.0
            }
        },
        "fp16": {
            "enabled": True
        },
Jeff Rasley's avatar
Jeff Rasley committed
305
        "zero_optimization": {
Jeff Rasley's avatar
Jeff Rasley committed
306
307
            "stage": zero_stage,
            "cpu_offload": use_cpu_offload
Jeff Rasley's avatar
Jeff Rasley committed
308
        }
309
    }
Jeff Rasley's avatar
Jeff Rasley committed
310

311
312
313
314
    args = args_from_dict(tmpdir, config_dict)
    hidden_dim = 10

    @distributed_test(world_size=[1])
Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
315
316
317
318
319
320
    def _test_adam_fp16_zero_onecycle_compatibility(args, zero_stage, hidden_dim):
        model = SimpleModel(hidden_dim)

        model, _, _,_ = deepspeed.initialize(args=args,
                                             model=model,
                                             model_parameters=model.parameters())
321
322
323
324
325
326
327
328
329
        data_loader = random_dataloader(model=model,
                                        total_samples=50,
                                        hidden_dim=hidden_dim,
                                        device=model.device)
        for n, batch in enumerate(data_loader):
            loss = model(batch[0], batch[1])
            model.backward(loss)
            model.step()

Jeff Rasley's avatar
Jeff Rasley committed
330
    _test_adam_fp16_zero_onecycle_compatibility(args=args,
Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
331
                                                zero_stage=zero_stage,
Jeff Rasley's avatar
Jeff Rasley committed
332
                                                hidden_dim=hidden_dim)
333
334


Jeff Rasley's avatar
Jeff Rasley committed
335
@pytest.mark.parametrize('zero_stage, use_cpu_offload',
Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
336
337
338
339
340
341
342
343
344
345
                         [(1,
                           False),
                          (2,
                           False),
                          (2,
                           True),
                          (3,
                           False),
                          (3,
                           True)])
Jeff Rasley's avatar
Jeff Rasley committed
346
def test_zero_static_scale(tmpdir, zero_stage, use_cpu_offload):
Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
347
348
349
    if use_cpu_offload and not deepspeed.ops.__compatible_ops__[CPUAdamBuilder.NAME]:
        pytest.skip("cpu-adam is not compatible")

350
    config_dict = {
Jeff Rasley's avatar
Jeff Rasley committed
351
        "train_batch_size": 4,
352
353
354
355
356
357
358
359
        "steps_per_print": 1,
        "optimizer": {
            "type": "Adam",
            "params": {
                "lr": 0.00015
            }
        },
        "fp16": {
Jeff Rasley's avatar
Jeff Rasley committed
360
361
            "enabled": True,
            "loss_scale": 138.
362
        },
Jeff Rasley's avatar
Jeff Rasley committed
363
        "zero_optimization": {
Jeff Rasley's avatar
Jeff Rasley committed
364
365
            "stage": zero_stage,
            "cpu_offload": use_cpu_offload
Jeff Rasley's avatar
Jeff Rasley committed
366
        }
367
368
369
    }
    args = args_from_dict(tmpdir, config_dict)

Jeff Rasley's avatar
Jeff Rasley committed
370
    @distributed_test(world_size=2)
371
372
373
    def _test_zero_static_scale(args, zero_stage, hidden_dim):
        #making hidden size not divisible by DP for covering this scenario
        hidden_dim = hidden_dim
374
        model = SimpleModel(hidden_dim)
Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
375

376
        model, optim, _, _ = deepspeed.initialize(args=args,
Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
377
378
                                            model=model,
                                            model_parameters=model.parameters())
379

Jeff Rasley's avatar
Jeff Rasley committed
380
381
382
383
384
        # Ensure the static scaler is configured.
        assert optim.dynamic_loss_scale == False
        assert optim.loss_scaler.loss_scale == 138.

        # Now make sure things work..
385
        data_loader = random_dataloader(model=model,
Jeff Rasley's avatar
Jeff Rasley committed
386
                                        total_samples=10,
387
388
389
390
391
392
393
                                        hidden_dim=hidden_dim,
                                        device=model.device)
        for n, batch in enumerate(data_loader):
            loss = model(batch[0], batch[1])
            model.backward(loss)
            model.step()

394
395
396
397
    #test when hidden_dim is not aligned with world size
    _test_zero_static_scale(args=args, zero_stage=zero_stage, hidden_dim=9)
    #test when hidden_dim is aligned with world size
    _test_zero_static_scale(args=args, zero_stage=zero_stage, hidden_dim=10)
398
399


Jeff Rasley's avatar
Jeff Rasley committed
400
def test_zero_static_scale_deprecated_format(tmpdir):
401
402
403
404
405
406
407
408
409
410
411
412
413
    config_dict = {
        "train_batch_size": 4,
        "steps_per_print": 1,
        "optimizer": {
            "type": "Adam",
            "params": {
                "lr": 0.00015
            }
        },
        "fp16": {
            "enabled": True,
            "loss_scale": 138.
        },
Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
414
415
416
        "zero_optimization": {
            "stage": 1
        }
417
418
419
420
421
422
    }
    args = args_from_dict(tmpdir, config_dict)

    @distributed_test(world_size=2)
    def _test_zero_static_scale(args):
        hidden_dim = 10
423
        model = SimpleModel(hidden_dim)
424
425
426
        model, optim, _, _ = deepspeed.initialize(args=args,
                                                  model=model,
                                                  model_parameters=model.parameters())
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442

        # Ensure the static scaler is configured.
        assert optim.dynamic_loss_scale == False
        assert optim.loss_scaler.loss_scale == 138.

        # Now make sure things work..
        data_loader = random_dataloader(model=model,
                                        total_samples=10,
                                        hidden_dim=hidden_dim,
                                        device=model.device)
        for n, batch in enumerate(data_loader):
            loss = model(batch[0], batch[1])
            model.backward(loss)
            model.step()

    _test_zero_static_scale(args)
443
444


Jeff Rasley's avatar
Jeff Rasley committed
445
@pytest.mark.parametrize('zero_stage, use_cpu_offload',
Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
446
447
448
449
450
451
452
453
454
455
                         [(1,
                           False),
                          (2,
                           False),
                          (2,
                           True),
                          (3,
                           False),
                          (3,
                           True)])
Jeff Rasley's avatar
Jeff Rasley committed
456
def test_zero_allow_untested_optimizer(tmpdir, zero_stage, use_cpu_offload):
Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
457
458
459
    if use_cpu_offload and not deepspeed.ops.__compatible_ops__[CPUAdamBuilder.NAME]:
        pytest.skip("cpu-adam is not compatible")

460
461
462
463
464
465
    config_dict = {
        "train_batch_size": 4,
        "steps_per_print": 1,
        "fp16": {
            "enabled": True,
        },
Jeff Rasley's avatar
Jeff Rasley committed
466
        "zero_optimization": {
Jeff Rasley's avatar
Jeff Rasley committed
467
468
            "stage": zero_stage,
            "cpu_offload": use_cpu_offload
Jeff Rasley's avatar
Jeff Rasley committed
469
        },
470
471
472
473
474
        "zero_allow_untested_optimizer": False
    }
    args = args_from_dict(tmpdir, config_dict)

    @distributed_test(world_size=[1])
Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
475
    def _test_zero_allow_untested_optimizer(args, zero_stage):
476
        hidden_dim = 10
477
        model = SimpleModel(hidden_dim)
478
479
        optimizer = SimpleOptimizer(model.parameters())
        with pytest.raises(AssertionError):
480
481
482
483
            model, optim, _, _ = deepspeed.initialize(args=args,
                                                      model=model,
                                                      optimizer=optimizer,
                                                      model_parameters=model.parameters())
484

Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
485
    _test_zero_allow_untested_optimizer(args, zero_stage)
486
487


Jeff Rasley's avatar
Jeff Rasley committed
488
@pytest.mark.parametrize('zero_stage, use_cpu_offload',
Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
489
490
491
492
493
494
495
496
497
498
                         [(1,
                           False),
                          (2,
                           False),
                          (2,
                           True),
                          (3,
                           False),
                          (3,
                           True)])
Jeff Rasley's avatar
Jeff Rasley committed
499
def test_zero_empty_partition(tmpdir, zero_stage, use_cpu_offload):
Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
500
501
502
503
504
505
    if use_cpu_offload and not deepspeed.ops.__compatible_ops__[CPUAdamBuilder.NAME]:
        pytest.skip("cpu-adam is not compatible")

    if zero_stage == 3:
        pytest.skip("skip for now")

506
507
508
509
510
511
512
513
514
515
516
517
518
519
    config_dict = {
        "train_micro_batch_size_per_gpu": 1,
        "gradient_accumulation_steps": 1,
        "fp16": {
            "enabled": True,
            "initial_scale_power": 8
        },
        "optimizer": {
            "type": "Adam",
            "params": {
                "lr": 0.00015
            }
        },
        "zero_optimization": {
Jeff Rasley's avatar
Jeff Rasley committed
520
            "stage": zero_stage,
Jeff Rasley's avatar
Jeff Rasley committed
521
522
523
            "cpu_offload": use_cpu_offload,
            "reduce_bucket_size": 100,
            "allgather_bucket_size": 100
524
525
526
527
528
        }
    }
    args = args_from_dict(tmpdir, config_dict)

    @distributed_test(world_size=[3])
Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
529
    def _test_zero_empty_partition(args, zero_stage):
530
531
        hidden_dim = 1
        model = SimpleModel(hidden_dim)
Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
532

533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
        # Ensure model has 2 parameters, to cause empty partition with DP=3
        assert len(list(model.parameters())) == 2
        model, _, _, _ = deepspeed.initialize(args=args,
                                              model=model,
                                              model_parameters=model.parameters())

        # Now make sure things work..
        data_loader = random_dataloader(model=model,
                                        total_samples=1,
                                        hidden_dim=hidden_dim,
                                        device=model.device)
        for n, batch in enumerate(data_loader):
            loss = model(batch[0], batch[1])
            model.backward(loss)
            model.step()

Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
549
    _test_zero_empty_partition(args=args, zero_stage=zero_stage)
550
551


552
@amp_available
553
554
555
556
557
def test_adam_amp_basic(tmpdir):
    config_dict = {"train_batch_size": 1, "steps_per_print": 1, "amp": {"enabled": True}}
    args = args_from_dict(tmpdir, config_dict)
    hidden_dim = 10

558
    model = SimpleModel(hidden_dim)
559
560
561
562

    @distributed_test(world_size=[1])
    def _test_adam_amp_basic(args, model, hidden_dim):
        optimizer = torch.optim.Adam(params=model.parameters())
563
564
565
        model, _, _, _ = deepspeed.initialize(args=args,
                                              model=model,
                                              optimizer=optimizer)
566
567
568
569
570
571
572
573
574
575
576
577
        data_loader = random_dataloader(model=model,
                                        total_samples=50,
                                        hidden_dim=hidden_dim,
                                        device=model.device)
        for n, batch in enumerate(data_loader):
            loss = model(batch[0], batch[1])
            model.backward(loss)
            model.step()

    _test_adam_amp_basic(args=args, model=model, hidden_dim=hidden_dim)


578
@amp_available
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
def test_lamb_amp_basic(tmpdir):
    config_dict = {
        "train_batch_size": 2,
        "steps_per_print": 1,
        "optimizer": {
            "type": "Lamb",
            "params": {
                "lr": 0.00015
            }
        },
        "gradient_clipping": 1.0,
        "amp": {
            "enabled": True,
        }
    }
    args = args_from_dict(tmpdir, config_dict)
    hidden_dim = 10

597
    model = SimpleModel(hidden_dim)
598
599
600

    @distributed_test(world_size=[1, 2])
    def _test_lamb_amp_basic(args, model, hidden_dim):
601
602
603
        model, _, _, _ = deepspeed.initialize(args=args,
                                              model=model,
                                              model_parameters=model.parameters())
604
605
606
607
608
609
610
611
612
613
614
615
        data_loader = random_dataloader(model=model,
                                        total_samples=50,
                                        hidden_dim=hidden_dim,
                                        device=model.device)
        for n, batch in enumerate(data_loader):
            loss = model(batch[0], batch[1])
            model.backward(loss)
            model.step()

    _test_lamb_amp_basic(args=args, model=model, hidden_dim=hidden_dim)


616
@amp_available
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
def test_adam_amp_o2(tmpdir):
    config_dict = {
        "train_batch_size": 2,
        "steps_per_print": 1,
        "optimizer": {
            "type": "Adam",
            "params": {
                "lr": 0.00015
            }
        },
        "gradient_clipping": 1.0,
        "amp": {
            "enabled": True,
            "opt_level": "O2"
        }
    }
    args = args_from_dict(tmpdir, config_dict)
    hidden_dim = 10

636
    model = SimpleModel(hidden_dim)
637
638
639

    @distributed_test(world_size=[1, 2])
    def _test_adam_amp_o2(args, model, hidden_dim):
640
641
642
        model, _, _, _ = deepspeed.initialize(args=args,
                                              model=model,
                                              model_parameters=model.parameters())
643
644
645
646
647
648
649
650
651
652
        data_loader = random_dataloader(model=model,
                                        total_samples=50,
                                        hidden_dim=hidden_dim,
                                        device=model.device)
        for n, batch in enumerate(data_loader):
            loss = model(batch[0], batch[1])
            model.backward(loss)
            model.step()

    _test_adam_amp_o2(args=args, model=model, hidden_dim=hidden_dim)
Jeff Rasley's avatar
Jeff Rasley committed
653
654


655
@amp_available
Jeff Rasley's avatar
Jeff Rasley committed
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
def test_adam_amp_o2_empty_grad(tmpdir):
    config_dict = {
        "train_batch_size": 2,
        "steps_per_print": 1,
        "optimizer": {
            "type": "Adam",
            "params": {
                "lr": 0.00015
            }
        },
        "gradient_clipping": 1.0,
        "amp": {
            "enabled": True,
            "opt_level": "O2"
        }
    }
    args = args_from_dict(tmpdir, config_dict)
    hidden_dim = 10

675
    model = SimpleModel(hidden_dim)
Jeff Rasley's avatar
Jeff Rasley committed
676
677
678

    @distributed_test(world_size=[2])
    def _test_adam_amp_o2_empty_grad(args, model, hidden_dim):
679
680
681
        model, _, _, _ = deepspeed.initialize(args=args,
                                              model=model,
                                              model_parameters=model.parameters())
Jeff Rasley's avatar
Jeff Rasley committed
682
683
684
685
686
687
688
689
690
691
        data_loader = random_dataloader(model=model,
                                        total_samples=50,
                                        hidden_dim=hidden_dim,
                                        device=model.device)
        for n, batch in enumerate(data_loader):
            loss = model(batch[0], batch[1])
            model.backward(loss)
            model.step()

    _test_adam_amp_o2_empty_grad(args=args, model=model, hidden_dim=hidden_dim)
Jeff Rasley's avatar
Jeff Rasley committed
692
693
694
695


@pytest.mark.parametrize('zero_stage, optimizer_constructor',
                         [(1,
696
                           FusedAdam),
Jeff Rasley's avatar
Jeff Rasley committed
697
698
699
                          (2,
                           torch.optim.Adam),
                          (2,
Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
700
701
702
703
                           FusedAdam),
                          (3,
                           torch.optim.Adam),
                          (3,
704
                           FusedAdam)])
Jeff Rasley's avatar
Jeff Rasley committed
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
def test_zero_supported_client_optimizer(tmpdir, zero_stage, optimizer_constructor):
    config_dict = {
        "train_batch_size": 2,
        "steps_per_print": 1,
        "fp16": {
            "enabled": True
        },
        "zero_optimization": {
            "stage": zero_stage
        }
    }
    args = args_from_dict(tmpdir, config_dict)
    hidden_dim = 10

    @distributed_test(world_size=[1])
Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
720
721
722
    def _test_zero_supported_client_optimizer(args, zero_stage, optimizer_constructor):
        model = SimpleModel(hidden_dim)

Jeff Rasley's avatar
Jeff Rasley committed
723
724
        client_optimizer = optimizer_constructor(params=model.parameters())
        model, _, _, _ = deepspeed.initialize(args=args,
725
726
                                              model=model,
                                              optimizer=client_optimizer)
Jeff Rasley's avatar
Jeff Rasley committed
727
728

    _test_zero_supported_client_optimizer(args=args,
Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
729
                                          zero_stage=zero_stage,
Jeff Rasley's avatar
Jeff Rasley committed
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
                                          optimizer_constructor=optimizer_constructor)


def test_zero2_reduce_scatter_off(tmpdir):
    config_dict = {
        "train_batch_size": 2,
        "steps_per_print": 1,
        "optimizer": {
            "type": "Adam",
            "params": {
                "lr": 0.00015
            }
        },
        "gradient_clipping": 1.0,
        "zero_optimization": {
            "stage": 2,
            "contiguous_gradients": True,
            "allgather_bucket_size": 2000000000,
            "reduce_bucket_size": 200000000,
            "overlap_comm": False,
            "reduce_scatter": False
        },
        "fp16": {
            "enabled": True
        }
    }
    args = args_from_dict(tmpdir, config_dict)
    hidden_dim = 10

759
    model = SimpleModel(hidden_dim)
Jeff Rasley's avatar
Jeff Rasley committed
760
761
762

    @distributed_test(world_size=[2])
    def _helper(args, model, hidden_dim):
763
764
765
        model, _, _, _ = deepspeed.initialize(args=args,
                                              model=model,
                                              model_parameters=model.parameters())
Jeff Rasley's avatar
Jeff Rasley committed
766
767
768
769
770
771
772
773
774
775
        data_loader = random_dataloader(model=model,
                                        total_samples=50,
                                        hidden_dim=hidden_dim,
                                        device=model.device)
        for n, batch in enumerate(data_loader):
            loss = model(batch[0], batch[1])
            model.backward(loss)
            model.step()

    _helper(args=args, model=model, hidden_dim=hidden_dim)
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805


@pytest.mark.parametrize('adam_type, torch_impl',
                         [('Adam',
                           True),
                          ('Adam',
                           False),
                          ('AdamW',
                           True),
                          ('AdamW',
                           False)])
def test_fp16_adam_types(tmpdir, adam_type, torch_impl):
    config_dict = {
        "train_batch_size": 1,
        "steps_per_print": 1,
        "fp16": {
            "enabled": True,
            "initial_scale_power": 10
        },
        "optimizer": {
            "type": adam_type,
            "torch_adam": torch_impl,
            "params": {
                "lr": 0.00015
            }
        }
    }
    args = args_from_dict(tmpdir, config_dict)
    hidden_dim = 10

806
    model = SimpleModel(hidden_dim)
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825

    @distributed_test(world_size=[1])
    def _test_fp16_adam_types(args, model, hidden_dim):

        model, _, _, _ = deepspeed.initialize(args=args,
                                              model=model,
                                              model_parameters=model.parameters())

        data_loader = random_dataloader(model=model,
                                        total_samples=10,
                                        hidden_dim=hidden_dim,
                                        device=model.device)

        for _, batch in enumerate(data_loader):
            loss = model(batch[0], batch[1])
            model.backward(loss)
            model.step()

    _test_fp16_adam_types(args=args, model=model, hidden_dim=hidden_dim)
Samyam Rajbhandari's avatar
Samyam Rajbhandari committed
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867


def test_zero3_lazyscatter(tmpdir):
    config_dict = {
        "train_batch_size": 1,
        "steps_per_print": 1,
        "fp16": {
            "enabled": True,
            "initial_scale_power": 10
        },
        "optimizer": {
            "type": "AdamW",
            "params": {
                "lr": 0.00015
            }
        },
        "zero_optimization": {
            "stage": 3
        }
    }
    args = args_from_dict(tmpdir, config_dict)
    hidden_dim = 10

    @distributed_test(world_size=[1])
    def _go(args):
        model = SimpleModel(hidden_dim)

        model, _, _, _ = deepspeed.initialize(args=args,
                                              model=model,
                                              model_parameters=model.parameters())

        data_loader = random_dataloader(model=model,
                                        total_samples=10,
                                        hidden_dim=hidden_dim,
                                        device=model.device)

        for _, batch in enumerate(data_loader):
            loss = model(batch[0], batch[1])
            model.backward(loss)
            model.step()

    _go(args=args)