test_optim.py 14.4 KB
Newer Older
1
import time
2
import torch.multiprocessing as mp
3
4
5
import unittest, os
import pytest

6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import torch as th
import backend as F

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

@unittest.skipIf(os.name == 'nt', reason='Do not support windows yet')
def test_sparse_adam():
    num_embs = 10
    emb_dim = 4
    device=F.ctx()
    dgl_emb = NodeEmbedding(num_embs, emb_dim, 'test')
    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)
22
    th.nn.init.uniform_(dgl_emb.weight, 0, 1.0)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

    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,))
    dgl_value = dgl_emb(idx, device).to(th.device('cpu'))
    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()
42
    assert F.allclose(dgl_emb.weight, torch_emb.weight)
43
44
45
46
47

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

48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
@unittest.skipIf(os.name == 'nt', reason='Do not support windows yet')
def test_sparse_adam_zero_step():
    num_embs = 10
    emb_dim = 4
    device=F.ctx()
    dgl_emb = NodeEmbedding(num_embs, emb_dim, 'test')
    torch_emb = th.nn.Embedding(num_embs, emb_dim, sparse=True)
    dgl_emb_zero = NodeEmbedding(num_embs, emb_dim, 'test2')
    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(
        list(torch_emb.parameters()) + list(torch_emb_zero.parameters()), lr=0.01)

    # first step
    idx = th.randint(0, num_embs, size=(4,))
    dgl_value = dgl_emb(idx, device).to(th.device('cpu'))
    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)

def initializer(emb):
    th.manual_seed(0)
    emb.uniform_(-1.0, 1.0)
    return emb

90
91
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):
92
93
94
    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')
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141

    if device.type == 'cuda':
        th.cuda.set_device(device)

    th.distributed.init_process_group(backend=backend,
                                      init_method=dist_init_method,
                                      world_size=world_size,
                                      rank=rank)

    init_weight = th.empty((num_embs, emb_dim))
    th.manual_seed(0)
    th.nn.init.uniform_(init_weight, -1.0, 1.0)
    dgl_emb = NodeEmbedding(num_embs, emb_dim, 'test', init_func=initializer, device=tensor_dev)
    dgl_emb.all_set_embedding(init_weight)

    if has_zero_grad:
        dgl_emb_zero = NodeEmbedding(num_embs, emb_dim, 'zero', init_func=initializer, device=tensor_dev)
        dgl_adam = SparseAdam(params=[dgl_emb, dgl_emb_zero], lr=0.01)
    else:
        dgl_adam = SparseAdam(params=[dgl_emb], lr=0.01)

    start = (num_embs // world_size) * rank
    end = (num_embs // world_size) * (rank + 1)
    th.manual_seed(rank)
    idx = th.randint(start, end, size=(4,)).to(tensor_dev)
    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()

def start_torch_adam_worker(rank, world_size, weight, has_zero_grad=False,
                            num_embs=128, emb_dim=10):
    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'
142
143
144
145
146
147
148
149
150
151
152
153

    th.distributed.init_process_group(backend=backend,
                                      init_method=dist_init_method,
                                      world_size=world_size,
                                      rank=rank)

    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)
154
        torch_emb_zero = torch_emb_zero.to(tensor_dev)
155
156
157
158
159
160
161
162
163
164
165
        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(
            list(torch_emb.module.parameters()) + list(torch_emb_zero.module.parameters()),
            lr=0.01)
    else:
        torch_adam = th.optim.SparseAdam(list(torch_emb.module.parameters()), lr=0.01)

    start = (num_embs // world_size) * rank
    end = (num_embs // world_size) * (rank + 1)
166
    th.manual_seed(rank)
167
168
    idx = th.randint(start, end, size=(4,))
    labels = th.ones((4,)).long()
169
    torch_value = torch_emb(idx)
170
171
172
173
    torch_loss = th.nn.functional.cross_entropy(torch_value, labels)
    torch_adam.zero_grad()
    torch_loss.backward()
    torch_adam.step()
174
175
    th.distributed.barrier()

176
    if rank == 0:
177
        weight[:] = torch_emb.module.weight.cpu()[:]
178
179
180
    th.distributed.barrier()

@unittest.skipIf(os.name == 'nt', reason='Do not support windows yet')
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
@unittest.skipIf(F.ctx().type == 'gpu', reason='cpu only test')
@pytest.mark.parametrize("num_workers", [2, 4])
def test_multiprocess_cpu_sparse_adam(num_workers):
    backend = 'gloo'
    worker_list = []
    num_embs=128
    emb_dim=10
    dgl_weight = th.empty((num_embs, emb_dim))
    ctx = mp.get_context('spawn')
    for i in range(num_workers):
        device = F.ctx()
        p = ctx.Process(target=start_sparse_adam_worker,
                        args=(i, device, num_workers, dgl_weight, th.device('cpu'), True, backend))
        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):
        p = ctx.Process(target=start_torch_adam_worker,
                        args=(i, num_workers, torch_weight, False))
        p.start()
        worker_list.append(p)
    for p in worker_list:
        p.join()

    assert F.allclose(dgl_weight, torch_weight)

@unittest.skipIf(os.name == 'nt', reason='Do not support windows yet')
@unittest.skipIf(F.ctx().type == 'cpu', reason='gpu only test')
213
@pytest.mark.parametrize("num_workers", [2, 4, 8])
214
215
@pytest.mark.parametrize("backend", ['nccl', 'gloo'])
def test_multiprocess_sparse_adam(num_workers, backend):
216
217
218
    if F.ctx().type == 'cuda' and th.cuda.device_count() < num_workers:
        pytest.skip("Not enough GPUs to run test.")

219
    worker_list = []
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
    num_embs=128
    emb_dim=10
    dgl_weight = th.empty((num_embs, emb_dim))
    ctx = mp.get_context('spawn')
    for i in range(num_workers):
        device = F.ctx()
        if device.type == 'cuda':
            # make sure each process has a unique GPU
            device = th.device(i)
        p = ctx.Process(target=start_sparse_adam_worker,
                        args=(i, device, num_workers, dgl_weight, th.device('cpu'), True, backend))
        p.start()
        worker_list.append(p)
    for p in worker_list:
        p.join()
235

236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
    worker_list = []
    torch_weight = th.empty((num_embs, emb_dim))
    for i in range(num_workers):
        p = ctx.Process(target=start_torch_adam_worker,
                        args=(i, num_workers, torch_weight, False))
        p.start()
        worker_list.append(p)
    for p in worker_list:
        p.join()

    assert F.allclose(dgl_weight, torch_weight)

@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')
@pytest.mark.parametrize("num_workers", [2, 4, 8])
def test_multiprocess_sparse_adam_cuda_tensor(num_workers):
    if F.ctx().type == 'cpu':
        pytest.skip("Do not test CPU")
    if F.ctx().type == 'cuda' and th.cuda.device_count() < num_workers:
        pytest.skip("Not enough GPUs to run test.")

    backend = 'nccl'
    worker_list = []
    num_embs=128
    emb_dim=10
    dgl_weight = th.empty((num_embs, emb_dim))
262
263
    ctx = mp.get_context('spawn')
    for i in range(num_workers):
264
        device = th.device(i)
265
        p = ctx.Process(target=start_sparse_adam_worker,
266
                        args=(i, device, num_workers, dgl_weight, device, False, backend))
267
268
        p.start()
        worker_list.append(p)
269
270
    for p in worker_list:
        p.join()
271

272
273
274
275
276
277
278
    worker_list = []
    torch_weight = th.empty((num_embs, emb_dim))
    for i in range(num_workers):
        p = ctx.Process(target=start_torch_adam_worker,
                        args=(i, num_workers, torch_weight, False))
        p.start()
        worker_list.append(p)
279
280
281
    for p in worker_list:
        p.join()

282
283
    assert F.allclose(dgl_weight, torch_weight)

284
@unittest.skipIf(os.name == 'nt', reason='Do not support windows yet')
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
@unittest.skipIf(F.ctx().type == 'gpu', reason='cpu only test')
@pytest.mark.parametrize("num_workers", [2, 4])
def test_multiprocess_sparse_adam_cpu_zero_step(num_workers):
    backend = 'gloo'

    worker_list = []
    num_embs=128
    emb_dim=10
    dgl_weight = th.empty((num_embs, emb_dim))
    ctx = mp.get_context('spawn')
    for i in range(num_workers):
        device = F.ctx()
        p = ctx.Process(target=start_sparse_adam_worker,
                        args=(i, device, num_workers, dgl_weight, th.device('cpu'), True, backend))
        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):
        p = ctx.Process(target=start_torch_adam_worker,
                        args=(i, num_workers, torch_weight, False))
        p.start()
        worker_list.append(p)
    for p in worker_list:
        p.join()

    assert F.allclose(dgl_weight, torch_weight)

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

324
    worker_list = []
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
    num_embs=128
    emb_dim=10
    dgl_weight = th.empty((num_embs, emb_dim))
    ctx = mp.get_context('spawn')
    for i in range(num_workers):
        device = F.ctx()
        if device.type == 'cuda':
            # make sure each process has a unique GPU
            device = th.device(i)
        p = ctx.Process(target=start_sparse_adam_worker,
                        args=(i, device, num_workers, dgl_weight, th.device('cpu'), True, backend))
        p.start()
        worker_list.append(p)
    for p in worker_list:
        p.join()
340

341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
    worker_list = []
    torch_weight = th.empty((num_embs, emb_dim))
    for i in range(num_workers):
        p = ctx.Process(target=start_torch_adam_worker,
                        args=(i, num_workers, torch_weight, False))
        p.start()
        worker_list.append(p)
    for p in worker_list:
        p.join()

    assert F.allclose(dgl_weight, torch_weight)

@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')
@pytest.mark.parametrize("num_workers", [2, 4, 8])
def test_multiprocess_sparse_adam_zero_step_cuda_tensor(num_workers):
    if F.ctx().type == 'cuda' and th.cuda.device_count() < num_workers:
        pytest.skip("Not enough GPUs to run test.")

    backend = 'nccl'
    worker_list = []
    num_embs=128
    emb_dim=10
    dgl_weight = th.empty((num_embs, emb_dim))
365
366
    ctx = mp.get_context('spawn')
    for i in range(num_workers):
367
        device = th.device(i)
368
        p = ctx.Process(target=start_sparse_adam_worker,
369
                        args=(i, device, num_workers, dgl_weight, device, True, backend))
370
371
        p.start()
        worker_list.append(p)
372
373
    for p in worker_list:
        p.join()
374

375
376
377
378
379
380
381
    worker_list = []
    torch_weight = th.empty((num_embs, emb_dim))
    for i in range(num_workers):
        p = ctx.Process(target=start_torch_adam_worker,
                        args=(i, num_workers, torch_weight, False))
        p.start()
        worker_list.append(p)
382
383
384
    for p in worker_list:
        p.join()

385
386
    assert F.allclose(dgl_weight, torch_weight)

387
388
if __name__ == '__main__':
    test_sparse_adam()
389
390
    test_sparse_adam_zero_step()

391
392
393
394
395
396
397
398
399
400
401
402
403
404
    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)

    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')

    test_multiprocess_sparse_adam_zero_step(2, backend='gloo')
    test_multiprocess_sparse_adam_zero_step(4, backend='nccl')
405

406
407
    test_multiprocess_sparse_adam_cuda_tensor(2)
    test_multiprocess_sparse_adam_zero_step_cuda_tensor(4)