train_sampling_multi_gpu.py 11.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
import dgl
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.multiprocessing as mp
import dgl.nn.pytorch as dglnn
import time
Jinjing Zhou's avatar
Jinjing Zhou committed
10
import math
11
12
13
14
import argparse
from torch.nn.parallel import DistributedDataParallel
import tqdm

15
from utils import thread_wrapped_func
16
from load_graph import load_reddit, inductive_split
17

18
19
20
21
22
23
24
25
26
27
28
29
30
class SAGE(nn.Module):
    def __init__(self,
                 in_feats,
                 n_hidden,
                 n_classes,
                 n_layers,
                 activation,
                 dropout):
        super().__init__()
        self.n_layers = n_layers
        self.n_hidden = n_hidden
        self.n_classes = n_classes
        self.layers = nn.ModuleList()
31
        self.layers.append(dglnn.SAGEConv(in_feats, n_hidden, 'mean'))
32
        for i in range(1, n_layers - 1):
33
34
35
36
            self.layers.append(dglnn.SAGEConv(n_hidden, n_hidden, 'mean'))
        self.layers.append(dglnn.SAGEConv(n_hidden, n_classes, 'mean'))
        self.dropout = nn.Dropout(dropout)
        self.activation = activation
37
38
39

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

47
    def inference(self, g, x, device):
48
49
50
51
52
53
54
55
56
57
58
59
60
61
        """
        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):
62
            y = th.zeros(g.num_nodes(), self.n_hidden if l != len(self.layers) - 1 else self.n_classes)
63

64
65
            sampler = dgl.dataloading.MultiLayerFullNeighborSampler(1)
            dataloader = dgl.dataloading.NodeDataLoader(
66
                g,
67
                th.arange(g.num_nodes()),
68
69
70
71
72
73
74
75
                sampler,
                batch_size=args.batch_size,
                shuffle=True,
                drop_last=False,
                num_workers=args.num_workers)

            for input_nodes, output_nodes, blocks in tqdm.tqdm(dataloader):
                block = blocks[0]
76

77
                block = block.int().to(device)
78
                h = x[input_nodes].to(device)
79
                h = layer(block, h)
80
81
82
                if l != len(self.layers) - 1:
                    h = self.activation(h)
                    h = self.dropout(h)
83

84
                y[output_nodes] = h.cpu()
85
86
87
88
89
90
91
92
93
94

            x = y
        return y

def compute_acc(pred, labels):
    """
    Compute the accuracy of prediction given the labels.
    """
    return (th.argmax(pred, dim=1) == labels).float().sum() / len(pred)

95
def evaluate(model, g, nfeat, labels, val_nid, device):
96
    """
97
    Evaluate the model on the validation set specified by ``val_nid``.
98
99
100
    g : The entire graph.
    inputs : The features of all the nodes.
    labels : The labels of all the nodes.
101
    val_nid : A node ID tensor indicating which nodes do we actually compute the accuracy for.
102
103
104
105
    device : The GPU device to evaluate on.
    """
    model.eval()
    with th.no_grad():
106
        pred = model.inference(g, nfeat, device)
107
    model.train()
108
    return compute_acc(pred[val_nid], labels[val_nid])
109

110
def load_subtensor(nfeat, labels, seeds, input_nodes, dev_id):
111
    """
112
    Extracts features and labels for a subset of nodes.
113
    """
114
    batch_inputs = nfeat[input_nodes].to(dev_id)
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
    batch_labels = labels[seeds].to(dev_id)
    return batch_inputs, batch_labels

#### Entry point

def run(proc_id, n_gpus, args, devices, data):
    # Start up distributed training, if enabled.
    dev_id = devices[proc_id]
    if n_gpus > 1:
        dist_init_method = 'tcp://{master_ip}:{master_port}'.format(
            master_ip='127.0.0.1', master_port='12345')
        world_size = n_gpus
        th.distributed.init_process_group(backend="nccl",
                                          init_method=dist_init_method,
                                          world_size=world_size,
130
                                          rank=proc_id)
131
132
133
    th.cuda.set_device(dev_id)

    # Unpack data
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
    n_classes, train_g, val_g, test_g = data

    if args.inductive:
        train_nfeat = train_g.ndata.pop('features')
        val_nfeat = val_g.ndata.pop('features')
        test_nfeat = test_g.ndata.pop('features')
        train_labels = train_g.ndata.pop('labels')
        val_labels = val_g.ndata.pop('labels')
        test_labels = test_g.ndata.pop('labels')
    else:
        train_nfeat = val_nfeat = test_nfeat = g.ndata.pop('features')
        train_labels = val_labels = test_labels = g.ndata.pop('labels')

    if not args.data_cpu:
        train_nfeat = train_nfeat.to(dev_id)
        train_labels = train_labels.to(dev_id)

    in_feats = train_nfeat.shape[1]

153
154
    train_mask = train_g.ndata['train_mask']
    val_mask = val_g.ndata['val_mask']
155
    test_mask = ~(test_g.ndata['train_mask'] | test_g.ndata['val_mask'])
156
157
158
    train_nid = train_mask.nonzero().squeeze()
    val_nid = val_mask.nonzero().squeeze()
    test_nid = test_mask.nonzero().squeeze()
159
160

    # Split train_nid
161
    train_nid = th.split(train_nid, math.ceil(len(train_nid) / n_gpus))[proc_id]
162

163
    # Create PyTorch DataLoader for constructing blocks
164
    sampler = dgl.dataloading.MultiLayerNeighborSampler(
165
        [int(fanout) for fanout in args.fan_out.split(',')])
166
    dataloader = dgl.dataloading.NodeDataLoader(
167
        train_g,
168
169
        train_nid,
        sampler,
170
171
172
        batch_size=args.batch_size,
        shuffle=True,
        drop_last=False,
173
        num_workers=args.num_workers)
174
175

    # Define model and optimizer
176
    model = SAGE(in_feats, args.num_hidden, n_classes, args.num_layers, F.relu, args.dropout)
177
178
179
180
181
182
183
184
185
186
187
    model = model.to(dev_id)
    if n_gpus > 1:
        model = DistributedDataParallel(model, device_ids=[dev_id], output_device=dev_id)
    loss_fcn = nn.CrossEntropyLoss()
    optimizer = optim.Adam(model.parameters(), lr=args.lr)

    # Training loop
    avg = 0
    iter_tput = []
    for epoch in range(args.num_epochs):
        tic = time.time()
188
189
190

        # Loop over the dataloader to sample the computation dependency graph as a list of
        # blocks.
191
        for step, (input_nodes, seeds, blocks) in enumerate(dataloader):
192
193
194
195
            if proc_id == 0:
                tic_step = time.time()

            # Load the input features as well as output labels
196
197
            batch_inputs, batch_labels = load_subtensor(train_nfeat, train_labels,
                                                        seeds, input_nodes, dev_id)
198
            blocks = [block.int().to(dev_id) for block in blocks]
199
200
201
202
203
204
205
206
207
208
209
            # Compute loss and prediction
            batch_pred = model(blocks, batch_inputs)
            loss = loss_fcn(batch_pred, batch_labels)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

            if proc_id == 0:
                iter_tput.append(len(seeds) * n_gpus / (time.time() - tic_step))
            if step % args.log_every == 0 and proc_id == 0:
                acc = compute_acc(batch_pred, batch_labels)
maqy1995's avatar
maqy1995 committed
210
                print('Epoch {:05d} | Step {:05d} | Loss {:.4f} | Train Acc {:.4f} | Speed (samples/sec) {:.4f} | GPU {:.1f} MB'.format(
211
                    epoch, step, loss.item(), acc.item(), np.mean(iter_tput[3:]), th.cuda.max_memory_allocated() / 1000000))
212
213
214
215
216
217
218
219
220
221

        if n_gpus > 1:
            th.distributed.barrier()

        toc = time.time()
        if proc_id == 0:
            print('Epoch Time(s): {:.4f}'.format(toc - tic))
            if epoch >= 5:
                avg += toc - tic
            if epoch % args.eval_every == 0 and epoch != 0:
222
                if n_gpus == 1:
223
                    eval_acc = evaluate(
224
                        model, val_g, val_nfeat, val_labels, val_nid, devices[0])
225
                    test_acc = evaluate(
226
                        model, test_g, test_nfeat, test_labels, test_nid, devices[0])
227
                else:
228
                    eval_acc = evaluate(
229
                        model.module, val_g, val_nfeat, val_labels, val_nid, devices[0])
230
                    test_acc = evaluate(
231
                        model.module, test_g, test_nfeat, test_labels, test_nid, devices[0])
232
                print('Eval Acc {:.4f}'.format(eval_acc))
233
                print('Test Acc: {:.4f}'.format(test_acc))
234

235

236
237
238
239
240
241
242
    if n_gpus > 1:
        th.distributed.barrier()
    if proc_id == 0:
        print('Avg epoch time: {}'.format(avg / (epoch - 4)))

if __name__ == '__main__':
    argparser = argparse.ArgumentParser("multi-gpu training")
243
    argparser.add_argument('--gpu', type=str, default='0',
244
                           help="Comma separated list of GPU device IDs.")
245
246
247
    argparser.add_argument('--num-epochs', type=int, default=20)
    argparser.add_argument('--num-hidden', type=int, default=16)
    argparser.add_argument('--num-layers', type=int, default=2)
248
    argparser.add_argument('--fan-out', type=str, default='10,25')
249
250
251
252
    argparser.add_argument('--batch-size', type=int, default=1000)
    argparser.add_argument('--log-every', type=int, default=20)
    argparser.add_argument('--eval-every', type=int, default=5)
    argparser.add_argument('--lr', type=float, default=0.003)
253
254
    argparser.add_argument('--dropout', type=float, default=0.5)
    argparser.add_argument('--num-workers', type=int, default=0,
255
                           help="Number of sampling processes. Use 0 for no extra process.")
256
    argparser.add_argument('--inductive', action='store_true',
257
258
259
260
261
262
                           help="Inductive learning setting")
    argparser.add_argument('--data-cpu', action='store_true',
                           help="By default the script puts all node features and labels "
                                "on GPU when using it to save time for data copy. This may "
                                "be undesired if they cannot fit in GPU memory at once. "
                                "This flag disables that.")
263
264
265
266
267
    args = argparser.parse_args()
    
    devices = list(map(int, args.gpu.split(',')))
    n_gpus = len(devices)

268
    g, n_classes = load_reddit()
269
    # Construct graph
270
271
272
273
274
275
276
    g = dgl.as_heterograph(g)

    if args.inductive:
        train_g, val_g, test_g = inductive_split(g)
    else:
        train_g = val_g = test_g = g

277
278
    # Create csr/coo/csc formats before launching training processes with multi-gpu.
    # This avoids creating certain formats in each sub-process, which saves momory and CPU.
279
280
281
    train_g.create_formats_()
    val_g.create_formats_()
    test_g.create_formats_()
282
    # Pack data
283
    data = n_classes, train_g, val_g, test_g
284
285
286
287
288
289

    if n_gpus == 1:
        run(0, n_gpus, args, devices, data)
    else:
        procs = []
        for proc_id in range(n_gpus):
290
291
            p = mp.Process(target=thread_wrapped_func(run),
                           args=(proc_id, n_gpus, args, devices, data))
292
293
294
295
            p.start()
            procs.append(p)
        for p in procs:
            p.join()