train_dist_unsupervised.py 21.3 KB
Newer Older
1
import os
2
3
4
5
6
7

os.environ["DGLBACKEND"] = "pytorch"
import argparse
import math
import time
from functools import wraps
8
from multiprocessing import Process
9

10
11
12
13
import numpy as np
import sklearn.linear_model as lm
import sklearn.metrics as skm
import torch as th
14
import torch.multiprocessing as mp
15
16
17
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
18
19
20
21
22
23
24
25
import tqdm

import dgl
import dgl.function as fn
import dgl.nn.pytorch as dglnn
from dgl import DGLGraph
from dgl.data import load_data, register_data_args
from dgl.data.utils import load_graphs
26
from dgl.distributed import DistDataLoader
27

28

29
class SAGE(nn.Module):
30
31
32
    def __init__(
        self, in_feats, n_hidden, n_classes, n_layers, activation, dropout
    ):
33
34
35
36
37
        super().__init__()
        self.n_layers = n_layers
        self.n_hidden = n_hidden
        self.n_classes = n_classes
        self.layers = nn.ModuleList()
38
        self.layers.append(dglnn.SAGEConv(in_feats, n_hidden, "mean"))
39
        for i in range(1, n_layers - 1):
40
41
            self.layers.append(dglnn.SAGEConv(n_hidden, n_hidden, "mean"))
        self.layers.append(dglnn.SAGEConv(n_hidden, n_classes, "mean"))
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
        self.dropout = nn.Dropout(dropout)
        self.activation = activation

    def forward(self, blocks, x):
        h = x
        for l, (layer, block) in enumerate(zip(self.layers, blocks)):
            h = layer(block, h)
            if l != len(self.layers) - 1:
                h = self.activation(h)
                h = self.dropout(h)
        return h

    def inference(self, g, x, batch_size, device):
        """
        Inference with the GraphSAGE model on full neighbors (i.e. without neighbor sampling).
        g : the entire graph.
        x : the input of entire node set.

        The inference code is written in a fashion that it could handle any number of nodes and
        layers.
        """
        # During inference with sampling, multi-layer blocks are very inefficient because
        # lots of computations in the first few layers are repeated.
        # Therefore, we compute the representation of all nodes layer by layer.  The nodes
        # on each layer are of course splitted in batches.
        # TODO: can we standardize this?
        for l, layer in enumerate(self.layers):
69
70
71
72
            y = th.zeros(
                g.number_of_nodes(),
                self.n_hidden if l != len(self.layers) - 1 else self.n_classes,
            )
73

74
            sampler = dgl.dataloading.MultiLayerNeighborSampler([None])
75
            dataloader = dgl.dataloading.DistNodeDataLoader(
76
77
78
                g,
                th.arange(g.number_of_nodes()),
                sampler,
79
                batch_size=batch_size,
80
81
                shuffle=True,
                drop_last=False,
82
83
                num_workers=0,
            )
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98

            for input_nodes, output_nodes, blocks in tqdm.tqdm(dataloader):
                block = blocks[0]
                block = block.int().to(device)
                h = x[input_nodes].to(device)
                h = layer(block, h)
                if l != len(self.layers) - 1:
                    h = self.activation(h)
                    h = self.dropout(h)

                y[output_nodes] = h.cpu()

            x = y
        return y

99

100
101
102
103
104
105
class NegativeSampler(object):
    def __init__(self, g, neg_nseeds):
        self.neg_nseeds = neg_nseeds

    def __call__(self, num_samples):
        # select local neg nodes as seeds
106
107
108
109
        return self.neg_nseeds[
            th.randint(self.neg_nseeds.shape[0], (num_samples,))
        ]

110
111

class NeighborSampler(object):
112
113
114
    def __init__(
        self, g, fanouts, neg_nseeds, sample_neighbors, num_negs, remove_edge
    ):
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
        self.g = g
        self.fanouts = fanouts
        self.sample_neighbors = sample_neighbors
        self.neg_sampler = NegativeSampler(g, neg_nseeds)
        self.num_negs = num_negs
        self.remove_edge = remove_edge

    def sample_blocks(self, seed_edges):
        n_edges = len(seed_edges)
        seed_edges = th.LongTensor(np.asarray(seed_edges))
        heads, tails = self.g.find_edges(seed_edges)

        neg_tails = self.neg_sampler(self.num_negs * n_edges)
        neg_heads = heads.view(-1, 1).expand(n_edges, self.num_negs).flatten()

        # Maintain the correspondence between heads, tails and negative tails as two
        # graphs.
        # pos_graph contains the correspondence between each head and its positive tail.
        # neg_graph contains the correspondence between each head and its negative tails.
        # Both pos_graph and neg_graph are first constructed with the same node space as
        # the original graph.  Then they are compacted together with dgl.compact_graphs.
136
137
138
139
140
141
        pos_graph = dgl.graph(
            (heads, tails), num_nodes=self.g.number_of_nodes()
        )
        neg_graph = dgl.graph(
            (neg_heads, neg_tails), num_nodes=self.g.number_of_nodes()
        )
142
143
144
145
146
147
        pos_graph, neg_graph = dgl.compact_graphs([pos_graph, neg_graph])

        seeds = pos_graph.ndata[dgl.NID]
        blocks = []
        for fanout in self.fanouts:
            # For each seed node, sample ``fanout`` neighbors.
148
149
150
            frontier = self.sample_neighbors(
                self.g, seeds, fanout, replace=True
            )
151
152
153
154
155
            if self.remove_edge:
                # Remove all edges between heads and tails, as well as heads and neg_tails.
                _, _, edge_ids = frontier.edge_ids(
                    th.cat([heads, tails, neg_heads, neg_tails]),
                    th.cat([tails, heads, neg_tails, neg_heads]),
156
157
                    return_uv=True,
                )
158
159
160
161
162
163
164
165
166
                frontier = dgl.remove_edges(frontier, edge_ids)
            # Then we compact the frontier into a bipartite graph for message passing.
            block = dgl.to_block(frontier, seeds)

            # Obtain the seed nodes for next layer.
            seeds = block.srcdata[dgl.NID]

            blocks.insert(0, block)

167
        input_nodes = blocks[0].srcdata[dgl.NID]
168
169
170
        blocks[0].srcdata["features"] = load_subtensor(
            self.g, input_nodes, "cpu"
        )
171
172
173
        # Pre-generate CSR format that it can be used in training directly
        return pos_graph, neg_graph, blocks

174

175
176
177
178
179
180
181
182
183
184
185
class PosNeighborSampler(object):
    def __init__(self, g, fanouts, sample_neighbors):
        self.g = g
        self.fanouts = fanouts
        self.sample_neighbors = sample_neighbors

    def sample_blocks(self, seeds):
        seeds = th.LongTensor(np.asarray(seeds))
        blocks = []
        for fanout in self.fanouts:
            # For each seed node, sample ``fanout`` neighbors.
186
187
188
            frontier = self.sample_neighbors(
                self.g, seeds, fanout, replace=True
            )
189
190
191
192
193
194
195
196
            # Then we compact the frontier into a bipartite graph for message passing.
            block = dgl.to_block(frontier, seeds)
            # Obtain the seed nodes for next layer.
            seeds = block.srcdata[dgl.NID]

            blocks.insert(0, block)
        return blocks

197

198
class DistSAGE(SAGE):
199
200
201
202
203
204
    def __init__(
        self, in_feats, n_hidden, n_classes, n_layers, activation, dropout
    ):
        super(DistSAGE, self).__init__(
            in_feats, n_hidden, n_classes, n_layers, activation, dropout
        )
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219

    def inference(self, g, x, batch_size, device):
        """
        Inference with the GraphSAGE model on full neighbors (i.e. without neighbor sampling).
        g : the entire graph.
        x : the input of entire node set.

        The inference code is written in a fashion that it could handle any number of nodes and
        layers.
        """
        # During inference with sampling, multi-layer blocks are very inefficient because
        # lots of computations in the first few layers are repeated.
        # Therefore, we compute the representation of all nodes layer by layer.  The nodes
        # on each layer are of course splitted in batches.
        # TODO: can we standardize this?
220
221
222
223
224
225
226
227
228
229
230
        nodes = dgl.distributed.node_split(
            np.arange(g.number_of_nodes()),
            g.get_partition_book(),
            force_even=True,
        )
        y = dgl.distributed.DistTensor(
            (g.number_of_nodes(), self.n_hidden),
            th.float32,
            "h",
            persistent=True,
        )
231
232
        for l, layer in enumerate(self.layers):
            if l == len(self.layers) - 1:
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
                y = dgl.distributed.DistTensor(
                    (g.number_of_nodes(), self.n_classes),
                    th.float32,
                    "h_last",
                    persistent=True,
                )

            sampler = PosNeighborSampler(
                g, [-1], dgl.distributed.sample_neighbors
            )
            print(
                "|V|={}, eval batch size: {}".format(
                    g.number_of_nodes(), batch_size
                )
            )
248
            # Create PyTorch DataLoader for constructing blocks
249
            dataloader = DistDataLoader(
250
251
252
253
                dataset=nodes,
                batch_size=batch_size,
                collate_fn=sampler.sample_blocks,
                shuffle=False,
254
255
                drop_last=False,
            )
256
257

            for blocks in tqdm.tqdm(dataloader):
258
                block = blocks[0].to(device)
259
260
261
                input_nodes = block.srcdata[dgl.NID]
                output_nodes = block.dstdata[dgl.NID]
                h = x[input_nodes].to(device)
262
                h_dst = h[: block.number_of_dst_nodes()]
263
264
265
266
267
268
269
270
271
272
273
                h = layer(block, (h, h_dst))
                if l != len(self.layers) - 1:
                    h = self.activation(h)
                    h = self.dropout(h)

                y[output_nodes] = h.cpu()

            x = y
            g.barrier()
        return y

274

275
276
277
278
def load_subtensor(g, input_nodes, device):
    """
    Copys features and labels of a set of nodes onto GPU.
    """
279
    batch_inputs = g.ndata["features"][input_nodes].to(device)
280
281
    return batch_inputs

282

283
284
285
class CrossEntropyLoss(nn.Module):
    def forward(self, block_outputs, pos_graph, neg_graph):
        with pos_graph.local_scope():
286
287
288
            pos_graph.ndata["h"] = block_outputs
            pos_graph.apply_edges(fn.u_dot_v("h", "h", "score"))
            pos_score = pos_graph.edata["score"]
289
        with neg_graph.local_scope():
290
291
292
            neg_graph.ndata["h"] = block_outputs
            neg_graph.apply_edges(fn.u_dot_v("h", "h", "score"))
            neg_score = neg_graph.edata["score"]
293
294

        score = th.cat([pos_score, neg_score])
295
296
297
        label = th.cat(
            [th.ones_like(pos_score), th.zeros_like(neg_score)]
        ).long()
298
299
300
        loss = F.binary_cross_entropy_with_logits(score, label.float())
        return loss

301

302
303
304
305
306
307
308
309
310
311
312
313
314
315
def generate_emb(model, g, inputs, batch_size, device):
    """
    Generate embeddings for each node
    g : The entire graph.
    inputs : The features of all the nodes.
    batch_size : Number of nodes to compute at the same time.
    device : The GPU device to evaluate on.
    """
    model.eval()
    with th.no_grad():
        pred = model.inference(g, inputs, batch_size, device)

    return pred

316

317
318
319
def compute_acc(emb, labels, train_nids, val_nids, test_nids):
    """
    Compute the accuracy of prediction given the labels.
320

321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
    We will fist train a LogisticRegression model using the trained embeddings,
    the training set, validation set and test set is provided as the arguments.

    The final result is predicted by the lr model.

    emb: The pretrained embeddings
    labels: The ground truth
    train_nids: The training set node ids
    val_nids: The validation set node ids
    test_nids: The test set node ids
    """

    emb = emb[np.arange(labels.shape[0])].cpu().numpy()
    train_nids = train_nids.cpu().numpy()
    val_nids = val_nids.cpu().numpy()
    test_nids = test_nids.cpu().numpy()
    labels = labels.cpu().numpy()

    emb = (emb - emb.mean(0, keepdims=True)) / emb.std(0, keepdims=True)
340
    lr = lm.LogisticRegression(multi_class="multinomial", max_iter=10000)
341
342
343
344
345
346
347
    lr.fit(emb[train_nids], labels[train_nids])

    pred = lr.predict(emb)
    eval_acc = skm.accuracy_score(labels[val_nids], pred[val_nids])
    test_acc = skm.accuracy_score(labels[test_nids], pred[test_nids])
    return eval_acc, test_acc

348

349
350
def run(args, device, data):
    # Unpack data
351
352
353
354
355
356
357
358
359
360
    (
        train_eids,
        train_nids,
        in_feats,
        g,
        global_train_nid,
        global_valid_nid,
        global_test_nid,
        labels,
    ) = data
361
    # Create sampler
362
363
364
365
366
367
368
369
    sampler = NeighborSampler(
        g,
        [int(fanout) for fanout in args.fan_out.split(",")],
        train_nids,
        dgl.distributed.sample_neighbors,
        args.num_negs,
        args.remove_edge,
    )
370
371

    # Create PyTorch DataLoader for constructing blocks
372
    dataloader = dgl.distributed.DistDataLoader(
373
374
375
376
        dataset=train_eids.numpy(),
        batch_size=args.batch_size,
        collate_fn=sampler.sample_blocks,
        shuffle=True,
377
378
        drop_last=False,
    )
379
380

    # Define model and optimizer
381
382
383
384
385
386
387
388
    model = DistSAGE(
        in_feats,
        args.num_hidden,
        args.num_hidden,
        args.num_layers,
        F.relu,
        args.dropout,
    )
389
390
    model = model.to(device)
    if not args.standalone:
391
392
393
394
        if args.num_gpus == -1:
            model = th.nn.parallel.DistributedDataParallel(model)
        else:
            dev_id = g.rank() % args.num_gpus
395
396
397
            model = th.nn.parallel.DistributedDataParallel(
                model, device_ids=[dev_id], output_device=dev_id
            )
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
    loss_fcn = CrossEntropyLoss()
    loss_fcn = loss_fcn.to(device)
    optimizer = optim.Adam(model.parameters(), lr=args.lr)

    # Training loop
    epoch = 0
    for epoch in range(args.num_epochs):
        sample_time = 0
        copy_time = 0
        forward_time = 0
        backward_time = 0
        update_time = 0
        num_seeds = 0
        num_inputs = 0

        step_time = []
        iter_t = []
        sample_t = []
        feat_copy_t = []
        forward_t = []
        backward_t = []
        update_t = []
        iter_tput = []

        start = time.time()
        # Loop over the dataloader to sample the computation dependency graph as a list of
        # blocks.
        for step, (pos_graph, neg_graph, blocks) in enumerate(dataloader):
            tic_step = time.time()
            sample_t.append(tic_step - start)

429
430
431
            pos_graph = pos_graph.to(device)
            neg_graph = neg_graph.to(device)
            blocks = [block.to(device) for block in blocks]
432
433
434
435
            # The nodes for input lies at the LHS side of the first block.
            # The nodes for output lies at the RHS side of the last block.

            # Load the input features as well as output labels
436
            batch_inputs = blocks[0].srcdata["features"]
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
            copy_time = time.time()
            feat_copy_t.append(copy_time - tic_step)

            # Compute loss and prediction
            batch_pred = model(blocks, batch_inputs)
            loss = loss_fcn(batch_pred, pos_graph, neg_graph)
            forward_end = time.time()
            optimizer.zero_grad()
            loss.backward()
            compute_end = time.time()
            forward_t.append(forward_end - copy_time)
            backward_t.append(compute_end - forward_end)

            # Aggregate gradients in multiple nodes.
            optimizer.step()
            update_t.append(time.time() - compute_end)

            pos_edges = pos_graph.number_of_edges()
            neg_edges = neg_graph.number_of_edges()

            step_t = time.time() - start
            step_time.append(step_t)
            iter_tput.append(pos_edges / step_t)
            num_seeds += pos_edges
            if step % args.log_every == 0:
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
                print(
                    "[{}] Epoch {:05d} | Step {:05d} | Loss {:.4f} | Speed (samples/sec) {:.4f} | time {:.3f} s"
                    "| sample {:.3f} | copy {:.3f} | forward {:.3f} | backward {:.3f} | update {:.3f}".format(
                        g.rank(),
                        epoch,
                        step,
                        loss.item(),
                        np.mean(iter_tput[3:]),
                        np.sum(step_time[-args.log_every :]),
                        np.sum(sample_t[-args.log_every :]),
                        np.sum(feat_copy_t[-args.log_every :]),
                        np.sum(forward_t[-args.log_every :]),
                        np.sum(backward_t[-args.log_every :]),
                        np.sum(update_t[-args.log_every :]),
                    )
                )
478
479
            start = time.time()

480
481
482
483
484
485
486
487
488
489
490
491
492
        print(
            "[{}]Epoch Time(s): {:.4f}, sample: {:.4f}, data copy: {:.4f}, forward: {:.4f}, backward: {:.4f}, update: {:.4f}, #seeds: {}, #inputs: {}".format(
                g.rank(),
                np.sum(step_time),
                np.sum(sample_t),
                np.sum(feat_copy_t),
                np.sum(forward_t),
                np.sum(backward_t),
                np.sum(update_t),
                num_seeds,
                num_inputs,
            )
        )
493
494
495
496
        epoch += 1

    # evaluate the embedding using LogisticRegression
    if args.standalone:
497
498
499
        pred = generate_emb(
            model, g, g.ndata["features"], args.batch_size_eval, device
        )
500
    else:
501
502
503
        pred = generate_emb(
            model.module, g, g.ndata["features"], args.batch_size_eval, device
        )
504
    if g.rank() == 0:
505
506
507
508
        eval_acc, test_acc = compute_acc(
            pred, labels, global_train_nid, global_valid_nid, global_test_nid
        )
        print("eval acc {:.4f}; test acc {:.4f}".format(eval_acc, test_acc))
509
510
511
512
513
514
515
516
517
518

    # sync for eval and test
    if not args.standalone:
        th.distributed.barrier()

    if not args.standalone:
        g._client.barrier()

        # save features into file
        if g.rank() == 0:
519
            th.save(pred, "emb.pt")
520
    else:
521
522
523
        feat = g.ndata["features"]
        th.save(pred, "emb.pt")

524
525

def main(args):
526
    dgl.distributed.initialize(args.ip_config)
527
    if not args.standalone:
528
        th.distributed.init_process_group(backend="gloo")
529
    g = dgl.distributed.DistGraph(args.graph_name, part_config=args.part_config)
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
    print("rank:", g.rank())
    print("number of edges", g.number_of_edges())

    train_eids = dgl.distributed.edge_split(
        th.ones((g.number_of_edges(),), dtype=th.bool),
        g.get_partition_book(),
        force_even=True,
    )
    train_nids = dgl.distributed.node_split(
        th.ones((g.number_of_nodes(),), dtype=th.bool), g.get_partition_book()
    )
    global_train_nid = th.LongTensor(
        np.nonzero(g.ndata["train_mask"][np.arange(g.number_of_nodes())])
    )
    global_valid_nid = th.LongTensor(
        np.nonzero(g.ndata["val_mask"][np.arange(g.number_of_nodes())])
    )
    global_test_nid = th.LongTensor(
        np.nonzero(g.ndata["test_mask"][np.arange(g.number_of_nodes())])
    )
    labels = g.ndata["labels"][np.arange(g.number_of_nodes())]
551
    if args.num_gpus == -1:
552
        device = th.device("cpu")
553
    else:
554
        device = th.device("cuda:" + str(args.local_rank))
555
556

    # Pack data
557
    in_feats = g.ndata["features"].shape[1]
558
559
560
561
562
563
    global_train_nid = global_train_nid.squeeze()
    global_valid_nid = global_valid_nid.squeeze()
    global_test_nid = global_test_nid.squeeze()
    print("number of train {}".format(global_train_nid.shape[0]))
    print("number of valid {}".format(global_valid_nid.shape[0]))
    print("number of test {}".format(global_test_nid.shape[0]))
564
565
566
567
568
569
570
571
572
573
    data = (
        train_eids,
        train_nids,
        in_feats,
        g,
        global_train_nid,
        global_valid_nid,
        global_test_nid,
        labels,
    )
574
575
576
    run(args, device, data)
    print("parent ends")

577
578
579

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="GCN")
580
    register_data_args(parser)
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
    parser.add_argument("--graph_name", type=str, help="graph name")
    parser.add_argument("--id", type=int, help="the partition id")
    parser.add_argument(
        "--ip_config", type=str, help="The file for IP configuration"
    )
    parser.add_argument(
        "--part_config", type=str, help="The path to the partition config file"
    )
    parser.add_argument("--n_classes", type=int, help="the number of classes")
    parser.add_argument(
        "--num_gpus",
        type=int,
        default=-1,
        help="the number of GPU device. Use -1 for CPU training",
    )
    parser.add_argument("--num_epochs", type=int, default=20)
    parser.add_argument("--num_hidden", type=int, default=16)
    parser.add_argument("--num-layers", type=int, default=2)
    parser.add_argument("--fan_out", type=str, default="10,25")
    parser.add_argument("--batch_size", type=int, default=1000)
    parser.add_argument("--batch_size_eval", type=int, default=100000)
    parser.add_argument("--log_every", type=int, default=20)
    parser.add_argument("--eval_every", type=int, default=5)
    parser.add_argument("--lr", type=float, default=0.003)
    parser.add_argument("--dropout", type=float, default=0.5)
    parser.add_argument(
        "--local_rank", type=int, help="get rank of the process"
    )
    parser.add_argument(
        "--standalone", action="store_true", help="run in the standalone mode"
    )
    parser.add_argument("--num_negs", type=int, default=1)
    parser.add_argument(
        "--neg_share",
        default=False,
        action="store_true",
        help="sharing neg nodes for positive nodes",
    )
    parser.add_argument(
        "--remove_edge",
        default=False,
        action="store_true",
        help="whether to remove edges during sampling",
    )
625
626
627
    args = parser.parse_args()
    print(args)
    main(args)