test_optim.py 18.6 KB
Newer Older
1
import os
2
import time
3
import unittest
4

5
import backend as F
6
7
8
import pytest
import torch as th
import torch.multiprocessing as mp
9
10

from dgl.nn import NodeEmbedding
11
12
from dgl.optim import SparseAdagrad, SparseAdam

13

14
15
@unittest.skipIf(os.name == "nt", reason="Do not support windows yet")
@pytest.mark.parametrize("emb_dim", [1, 4, 101, 1024])
16
def test_sparse_adam(emb_dim):
17
    num_embs = 10
18
19
    device = F.ctx()
    dgl_emb = NodeEmbedding(num_embs, emb_dim, "test")
20
21
22
23
    torch_emb = th.nn.Embedding(num_embs, emb_dim, sparse=True)
    th.manual_seed(0)
    th.nn.init.uniform_(torch_emb.weight, 0, 1.0)
    th.manual_seed(0)
24
    th.nn.init.uniform_(dgl_emb.weight, 0, 1.0)
25
26
27
28
29
30

    dgl_adam = SparseAdam(params=[dgl_emb], lr=0.01)
    torch_adam = th.optim.SparseAdam(list(torch_emb.parameters()), lr=0.01)

    # first step
    idx = th.randint(0, num_embs, size=(4,))
31
    dgl_value = dgl_emb(idx, device).to(th.device("cpu"))
32
    torch_value = torch_emb(idx)
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
    labels = th.zeros((4,)).long()
    print("dgl_value = {}".format(dgl_value))
    print("labels = {}".format(labels))

    dgl_adam.zero_grad()
    torch_adam.zero_grad()
    dgl_loss = th.nn.functional.cross_entropy(dgl_value, labels)
    torch_loss = th.nn.functional.cross_entropy(torch_value, labels)
    dgl_loss.backward()
    torch_loss.backward()

    dgl_adam.step()
    torch_adam.step()
    assert F.allclose(dgl_emb.weight, torch_emb.weight)

    # Can not test second step
    # Pytorch sparseAdam maintains a global step
    # DGL sparseAdam use a per embedding step

52
53
54
55

@unittest.skipIf(os.name == "nt", reason="Do not support windows yet")
@pytest.mark.parametrize("use_uva", [False, True, None])
@pytest.mark.parametrize("emb_dim", [1, 4, 101, 1024])
56
def test_sparse_adam_uva(use_uva, emb_dim):
57
    if F.ctx().type == "cpu" and use_uva == True:
58
59
60
61
        # we want to only test values of False and None when not using GPU
        pytest.skip("UVA cannot be used without GPUs.")

    num_embs = 10
62
63
    device = F.ctx()
    dgl_emb = NodeEmbedding(num_embs, emb_dim, "test_uva{}".format(use_uva))
64
65
66
67
68
69
70
71
72
73
74
    torch_emb = th.nn.Embedding(num_embs, emb_dim, sparse=True)
    th.manual_seed(0)
    th.nn.init.uniform_(torch_emb.weight, 0, 1.0)
    th.manual_seed(0)
    th.nn.init.uniform_(dgl_emb.weight, 0, 1.0)

    dgl_adam = SparseAdam(params=[dgl_emb], lr=0.01, use_uva=use_uva)
    torch_adam = th.optim.SparseAdam(list(torch_emb.parameters()), lr=0.01)

    # first step
    idx = th.randint(0, num_embs, size=(4,))
75
    dgl_value = dgl_emb(idx, device).to(th.device("cpu"))
76
77
    torch_value = torch_emb(idx)
    labels = th.zeros((4,)).long()
78
79
80
81
82
83
84
85
86
87

    dgl_adam.zero_grad()
    torch_adam.zero_grad()
    dgl_loss = th.nn.functional.cross_entropy(dgl_value, labels)
    torch_loss = th.nn.functional.cross_entropy(torch_value, labels)
    dgl_loss.backward()
    torch_loss.backward()

    dgl_adam.step()
    torch_adam.step()
88
    assert F.allclose(dgl_emb.weight, torch_emb.weight)
89
90
91
92
93

    # Can not test second step
    # Pytorch sparseAdam maintains a global step
    # DGL sparseAdam use a per embedding step

94
95
96
97

@unittest.skipIf(os.name == "nt", reason="Do not support windows yet")
@pytest.mark.parametrize("dtype", [th.float32, th.float16])
@pytest.mark.parametrize("emb_dim", [1, 4, 101, 1024])
98
99
def test_sparse_adam_dtype(dtype, emb_dim):
    num_embs = 10
100
101
    device = F.ctx()
    dgl_emb = NodeEmbedding(num_embs, emb_dim, "test_dtype{}".format(dtype))
102
103
104
105
106
107
108
109
110
111
112
    torch_emb = th.nn.Embedding(num_embs, emb_dim, sparse=True)
    th.manual_seed(0)
    th.nn.init.uniform_(torch_emb.weight, 0, 1.0)
    th.manual_seed(0)
    th.nn.init.uniform_(dgl_emb.weight, 0, 1.0)

    dgl_adam = SparseAdam(params=[dgl_emb], lr=0.01, dtype=dtype)
    torch_adam = th.optim.SparseAdam(list(torch_emb.parameters()), lr=0.01)

    # first step
    idx = th.randint(0, num_embs, size=(4,))
113
    dgl_value = dgl_emb(idx, device).to(th.device("cpu"))
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
    torch_value = torch_emb(idx)
    labels = th.zeros((4,)).long()

    dgl_adam.zero_grad()
    torch_adam.zero_grad()
    dgl_loss = th.nn.functional.cross_entropy(dgl_value, labels)
    torch_loss = th.nn.functional.cross_entropy(torch_value, labels)
    dgl_loss.backward()
    torch_loss.backward()

    dgl_adam.step()
    torch_adam.step()
    assert F.allclose(dgl_emb.weight, torch_emb.weight)

    # Can not test second step
    # Pytorch sparseAdam maintains a global step
    # DGL sparseAdam use a per embedding step


133
@unittest.skipIf(os.name == "nt", reason="Do not support windows yet")
134
135
136
def test_sparse_adam_zero_step():
    num_embs = 10
    emb_dim = 4
137
138
    device = F.ctx()
    dgl_emb = NodeEmbedding(num_embs, emb_dim, "test")
139
    torch_emb = th.nn.Embedding(num_embs, emb_dim, sparse=True)
140
    dgl_emb_zero = NodeEmbedding(num_embs, emb_dim, "test2")
141
142
143
144
145
146
147
148
149
150
    torch_emb_zero = th.nn.Embedding(num_embs, emb_dim, sparse=True)
    th.manual_seed(0)
    th.nn.init.uniform_(torch_emb.weight, 0, 1.0)
    th.nn.init.uniform_(torch_emb_zero.weight, 0, 1.0)
    th.manual_seed(0)
    th.nn.init.uniform_(dgl_emb.weight, 0, 1.0)
    th.nn.init.uniform_(dgl_emb_zero.weight, 0, 1.0)

    dgl_adam = SparseAdam(params=[dgl_emb, dgl_emb_zero], lr=0.01)
    torch_adam = th.optim.SparseAdam(
151
152
153
        list(torch_emb.parameters()) + list(torch_emb_zero.parameters()),
        lr=0.01,
    )
154
155
156

    # first step
    idx = th.randint(0, num_embs, size=(4,))
157
    dgl_value = dgl_emb(idx, device).to(th.device("cpu"))
158
159
160
161
162
163
164
165
166
167
168
169
170
171
    torch_value = torch_emb(idx)
    labels = th.ones((4,)).long()

    dgl_adam.zero_grad()
    torch_adam.zero_grad()
    dgl_loss = th.nn.functional.cross_entropy(dgl_value, labels)
    torch_loss = th.nn.functional.cross_entropy(torch_value, labels)
    dgl_loss.backward()
    torch_loss.backward()

    dgl_adam.step()
    torch_adam.step()
    assert F.allclose(dgl_emb.weight, torch_emb.weight)

172

173
174
175
176
177
def initializer(emb):
    th.manual_seed(0)
    emb.uniform_(-1.0, 1.0)
    return emb

178

179
180
181
182
183
184
185
186
187
188
def start_sparse_adam_worker(
    rank,
    device,
    world_size,
    weight,
    tensor_dev="cpu",
    has_zero_grad=False,
    backend="gloo",
    num_embs=128,
    emb_dim=10,
189
    zero_comm=True,
190
191
192
193
194
195
196
):
    print("start sparse worker for adam {}".format(rank))
    dist_init_method = "tcp://{master_ip}:{master_port}".format(
        master_ip="127.0.0.1", master_port="12345"
    )

    if device.type == "cuda":
197
198
        th.cuda.set_device(device)

199
200
201
202
203
204
    th.distributed.init_process_group(
        backend=backend,
        init_method=dist_init_method,
        world_size=world_size,
        rank=rank,
    )
205
206
207
208

    init_weight = th.empty((num_embs, emb_dim))
    th.manual_seed(0)
    th.nn.init.uniform_(init_weight, -1.0, 1.0)
209
210
211
    dgl_emb = NodeEmbedding(
        num_embs, emb_dim, "test", init_func=initializer, device=tensor_dev
    )
212
213
214
    dgl_emb.all_set_embedding(init_weight)

    if has_zero_grad:
215
216
217
        dgl_emb_zero = NodeEmbedding(
            num_embs, emb_dim, "zero", init_func=initializer, device=tensor_dev
        )
218
219
220
221
222
        dgl_adam = SparseAdam(params=[dgl_emb, dgl_emb_zero], lr=0.01)
    else:
        dgl_adam = SparseAdam(params=[dgl_emb], lr=0.01)

    th.manual_seed(rank)
223
224
225
226
227
228
    if zero_comm:
        start = (num_embs // world_size) * rank
        end = (num_embs // world_size) * (rank + 1)
        idx = th.randint(start, end, size=(4,)).to(tensor_dev)
    else:
        idx = th.randint(0, num_embs, size=(4,)).to(tensor_dev)
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
    dgl_value = dgl_emb(idx, device)
    labels = th.ones((4,)).long().to(device)
    dgl_loss = th.nn.functional.cross_entropy(dgl_value, labels)
    dgl_adam.zero_grad()
    dgl_loss.backward()
    dgl_adam.step()
    th.distributed.barrier()
    dgl_weight = dgl_emb.all_get_embedding().detach()
    after_step = dgl_emb(idx, device).cpu()

    if rank == 0:
        dgl_value = dgl_value.detach().cpu()
        assert F.allclose(dgl_value, after_step) is False
        weight[:] = dgl_weight[:]
    th.distributed.barrier()

245

246
def start_torch_adam_worker(
247
248
249
250
251
252
253
    rank,
    world_size,
    weight,
    has_zero_grad=False,
    num_embs=128,
    emb_dim=10,
    zero_comm=True,
254
255
256
257
258
259
260
261
262
263
264
265
266
):
    print("start sparse worker for adam {}".format(rank))
    dist_init_method = "tcp://{master_ip}:{master_port}".format(
        master_ip="127.0.0.1", master_port="12345"
    )
    backend = "gloo"

    th.distributed.init_process_group(
        backend=backend,
        init_method=dist_init_method,
        world_size=world_size,
        rank=rank,
    )
267
268
269
270
271
272
273

    torch_emb = th.nn.Embedding(num_embs, emb_dim, sparse=True)
    th.manual_seed(0)
    th.nn.init.uniform_(torch_emb.weight, -1.0, 1.0)
    torch_emb = th.nn.parallel.DistributedDataParallel(torch_emb)
    if has_zero_grad:
        torch_emb_zero = th.nn.Embedding(num_embs, emb_dim, sparse=True)
274
        torch_emb_zero = torch_emb_zero.to(tensor_dev)
275
276
277
278
        th.manual_seed(0)
        th.nn.init.uniform_(torch_emb_zero.weight, -1.0, 1.0)
        torch_emb_zero = th.nn.parallel.DistributedDataParallel(torch_emb_zero)
        torch_adam = th.optim.SparseAdam(
279
280
281
282
            list(torch_emb.module.parameters())
            + list(torch_emb_zero.module.parameters()),
            lr=0.01,
        )
283
    else:
284
285
286
        torch_adam = th.optim.SparseAdam(
            list(torch_emb.module.parameters()), lr=0.01
        )
287

288
    th.manual_seed(rank)
289
290
291
292
293
294
    if zero_comm:
        start = (num_embs // world_size) * rank
        end = (num_embs // world_size) * (rank + 1)
        idx = th.randint(start, end, size=(4,))
    else:
        idx = th.randint(0, num_embs, size=(4,))
295
    labels = th.ones((4,)).long()
296
    torch_value = torch_emb(idx)
297
298
299
300
    torch_loss = th.nn.functional.cross_entropy(torch_value, labels)
    torch_adam.zero_grad()
    torch_loss.backward()
    torch_adam.step()
301
302
    th.distributed.barrier()

303
    if rank == 0:
304
        weight[:] = torch_emb.module.weight.cpu()[:]
305
306
    th.distributed.barrier()

307
308
309

@unittest.skipIf(os.name == "nt", reason="Do not support windows yet")
@unittest.skipIf(F.ctx().type != "cpu", reason="cpu only test")
310
311
@pytest.mark.parametrize("num_workers", [2, 4])
def test_multiprocess_cpu_sparse_adam(num_workers):
312
    backend = "gloo"
313
    worker_list = []
314
315
    num_embs = 128
    emb_dim = 10
316
    dgl_weight = th.empty((num_embs, emb_dim))
317
    ctx = mp.get_context("spawn")
318
319
    for i in range(num_workers):
        device = F.ctx()
320
321
322
323
324
325
326
327
328
329
330
331
        p = ctx.Process(
            target=start_sparse_adam_worker,
            args=(
                i,
                device,
                num_workers,
                dgl_weight,
                th.device("cpu"),
                True,
                backend,
            ),
        )
332
333
334
335
336
337
338
339
        p.start()
        worker_list.append(p)
    for p in worker_list:
        p.join()

    worker_list = []
    torch_weight = th.empty((num_embs, emb_dim))
    for i in range(num_workers):
340
341
342
343
        p = ctx.Process(
            target=start_torch_adam_worker,
            args=(i, num_workers, torch_weight, False),
        )
344
345
346
347
348
349
350
        p.start()
        worker_list.append(p)
    for p in worker_list:
        p.join()

    assert F.allclose(dgl_weight, torch_weight)

351
352
353

@unittest.skipIf(os.name == "nt", reason="Do not support windows yet")
@unittest.skipIf(F.ctx().type == "cpu", reason="gpu only test")
354
@pytest.mark.parametrize("num_workers", [2, 4, 8])
355
@pytest.mark.parametrize("backend", ["nccl", "gloo"])
356
357
@pytest.mark.parametrize("zero_comm", [True, False])
def test_multiprocess_sparse_adam(num_workers, backend, zero_comm):
358
    if F.ctx().type == "cuda" and th.cuda.device_count() < num_workers:
359
360
        pytest.skip("Not enough GPUs to run test.")

361
    worker_list = []
362
363
    num_embs = 128
    emb_dim = 10
364
    dgl_weight = th.empty((num_embs, emb_dim))
365
    ctx = mp.get_context("spawn")
366
367
    for i in range(num_workers):
        device = F.ctx()
368
        if device.type == "cuda":
369
370
            # make sure each process has a unique GPU
            device = th.device(i)
371
372
373
374
375
376
377
378
379
380
        p = ctx.Process(
            target=start_sparse_adam_worker,
            args=(
                i,
                device,
                num_workers,
                dgl_weight,
                th.device("cpu"),
                True,
                backend,
381
382
383
                num_embs,
                emb_dim,
                zero_comm,
384
385
            ),
        )
386
387
388
389
        p.start()
        worker_list.append(p)
    for p in worker_list:
        p.join()
390

391
392
393
    worker_list = []
    torch_weight = th.empty((num_embs, emb_dim))
    for i in range(num_workers):
394
395
        p = ctx.Process(
            target=start_torch_adam_worker,
396
397
398
399
400
401
402
403
404
            args=(
                i,
                num_workers,
                torch_weight,
                False,
                num_embs,
                emb_dim,
                zero_comm,
            ),
405
        )
406
407
408
409
410
411
412
        p.start()
        worker_list.append(p)
    for p in worker_list:
        p.join()

    assert F.allclose(dgl_weight, torch_weight)

413
414
415
416
417

@unittest.skipIf(os.name == "nt", reason="Do not support windows yet")
@unittest.skipIf(
    F.ctx().type == "cpu", reason="cuda tensor is not supported for cpu"
)
418
419
@pytest.mark.parametrize("num_workers", [2, 4, 8])
def test_multiprocess_sparse_adam_cuda_tensor(num_workers):
420
    if F.ctx().type == "cpu":
421
        pytest.skip("Do not test CPU")
422
    if F.ctx().type == "cuda" and th.cuda.device_count() < num_workers:
423
424
        pytest.skip("Not enough GPUs to run test.")

425
    backend = "nccl"
426
    worker_list = []
427
428
    num_embs = 128
    emb_dim = 10
429
    dgl_weight = th.empty((num_embs, emb_dim))
430
    ctx = mp.get_context("spawn")
431
    for i in range(num_workers):
432
        device = th.device(i)
433
434
435
436
        p = ctx.Process(
            target=start_sparse_adam_worker,
            args=(i, device, num_workers, dgl_weight, device, False, backend),
        )
437
438
        p.start()
        worker_list.append(p)
439
440
    for p in worker_list:
        p.join()
441

442
443
444
    worker_list = []
    torch_weight = th.empty((num_embs, emb_dim))
    for i in range(num_workers):
445
446
447
448
        p = ctx.Process(
            target=start_torch_adam_worker,
            args=(i, num_workers, torch_weight, False),
        )
449
450
        p.start()
        worker_list.append(p)
451
452
453
    for p in worker_list:
        p.join()

454
455
    assert F.allclose(dgl_weight, torch_weight)

456
457
458

@unittest.skipIf(os.name == "nt", reason="Do not support windows yet")
@unittest.skipIf(F.ctx().type != "cpu", reason="cpu only test")
459
460
@pytest.mark.parametrize("num_workers", [2, 4])
def test_multiprocess_sparse_adam_cpu_zero_step(num_workers):
461
    backend = "gloo"
462
463

    worker_list = []
464
465
    num_embs = 128
    emb_dim = 10
466
    dgl_weight = th.empty((num_embs, emb_dim))
467
    ctx = mp.get_context("spawn")
468
469
    for i in range(num_workers):
        device = F.ctx()
470
471
472
473
474
475
476
477
478
479
480
481
        p = ctx.Process(
            target=start_sparse_adam_worker,
            args=(
                i,
                device,
                num_workers,
                dgl_weight,
                th.device("cpu"),
                True,
                backend,
            ),
        )
482
483
484
485
486
487
488
489
        p.start()
        worker_list.append(p)
    for p in worker_list:
        p.join()

    worker_list = []
    torch_weight = th.empty((num_embs, emb_dim))
    for i in range(num_workers):
490
491
492
493
        p = ctx.Process(
            target=start_torch_adam_worker,
            args=(i, num_workers, torch_weight, False),
        )
494
495
496
497
498
499
500
        p.start()
        worker_list.append(p)
    for p in worker_list:
        p.join()

    assert F.allclose(dgl_weight, torch_weight)

501
502
503

@unittest.skipIf(os.name == "nt", reason="Do not support windows yet")
@unittest.skipIf(F.ctx().type == "cpu", reason="gpu only test")
504
@pytest.mark.parametrize("num_workers", [2, 4, 8])
505
@pytest.mark.parametrize("backend", ["nccl", "gloo"])
506
def test_multiprocess_sparse_adam_zero_step(num_workers, backend):
507
    if F.ctx().type == "cuda" and th.cuda.device_count() < num_workers:
508
509
        pytest.skip("Not enough GPUs to run test.")

510
    worker_list = []
511
512
    num_embs = 128
    emb_dim = 10
513
    dgl_weight = th.empty((num_embs, emb_dim))
514
    ctx = mp.get_context("spawn")
515
516
    for i in range(num_workers):
        device = F.ctx()
517
        if device.type == "cuda":
518
519
            # make sure each process has a unique GPU
            device = th.device(i)
520
521
522
523
524
525
526
527
528
529
530
531
        p = ctx.Process(
            target=start_sparse_adam_worker,
            args=(
                i,
                device,
                num_workers,
                dgl_weight,
                th.device("cpu"),
                True,
                backend,
            ),
        )
532
533
534
535
        p.start()
        worker_list.append(p)
    for p in worker_list:
        p.join()
536

537
538
539
    worker_list = []
    torch_weight = th.empty((num_embs, emb_dim))
    for i in range(num_workers):
540
541
542
543
        p = ctx.Process(
            target=start_torch_adam_worker,
            args=(i, num_workers, torch_weight, False),
        )
544
545
546
547
548
549
550
        p.start()
        worker_list.append(p)
    for p in worker_list:
        p.join()

    assert F.allclose(dgl_weight, torch_weight)

551
552
553
554
555

@unittest.skipIf(os.name == "nt", reason="Do not support windows yet")
@unittest.skipIf(
    F.ctx().type == "cpu", reason="cuda tensor is not supported for cpu"
)
556
557
@pytest.mark.parametrize("num_workers", [2, 4, 8])
def test_multiprocess_sparse_adam_zero_step_cuda_tensor(num_workers):
558
    if F.ctx().type == "cuda" and th.cuda.device_count() < num_workers:
559
560
        pytest.skip("Not enough GPUs to run test.")

561
    backend = "nccl"
562
    worker_list = []
563
564
    num_embs = 128
    emb_dim = 10
565
    dgl_weight = th.empty((num_embs, emb_dim))
566
    ctx = mp.get_context("spawn")
567
    for i in range(num_workers):
568
        device = th.device(i)
569
570
571
572
        p = ctx.Process(
            target=start_sparse_adam_worker,
            args=(i, device, num_workers, dgl_weight, device, True, backend),
        )
573
574
        p.start()
        worker_list.append(p)
575
576
    for p in worker_list:
        p.join()
577

578
579
580
    worker_list = []
    torch_weight = th.empty((num_embs, emb_dim))
    for i in range(num_workers):
581
582
583
584
        p = ctx.Process(
            target=start_torch_adam_worker,
            args=(i, num_workers, torch_weight, False),
        )
585
586
        p.start()
        worker_list.append(p)
587
588
589
    for p in worker_list:
        p.join()

590
591
    assert F.allclose(dgl_weight, torch_weight)

592
593

if __name__ == "__main__":
594
595
596
597
    test_sparse_adam(1)
    test_sparse_adam(4)
    test_sparse_adam(101)
    test_sparse_adam(1024)
598
599
    test_sparse_adam_zero_step()

600
601
602
603
604
    test_multiprocess_cpu_sparse_adam(2)
    test_multiprocess_cpu_sparse_adam(4)
    test_multiprocess_cpu_sparse_adam(8)
    test_multiprocess_sparse_adam_cpu_zero_step(2)

605
606
607
608
609
610
    test_multiprocess_sparse_adam(2, backend="gloo")
    test_multiprocess_sparse_adam(4, backend="gloo")
    test_multiprocess_sparse_adam(8, backend="gloo")
    test_multiprocess_sparse_adam(2, backend="nccl")
    test_multiprocess_sparse_adam(4, backend="nccl")
    test_multiprocess_sparse_adam(8, backend="nccl")
611

612
613
    test_multiprocess_sparse_adam_zero_step(2, backend="gloo")
    test_multiprocess_sparse_adam_zero_step(4, backend="nccl")
614

615
616
    test_multiprocess_sparse_adam_cuda_tensor(2)
    test_multiprocess_sparse_adam_zero_step_cuda_tensor(4)