dmlc--dgl
44089c8b4d
* Merge * [Graph][CUDA] Graph on GPU and many refactoring (#1791) * change edge_ids behavior and C++ impl * fix unittests; remove utils.Index in edge_id * pass mx and th tests * pass tf test * add aten::Scatter_ * Add nonzero; impl CSRGetDataAndIndices/CSRSliceMatrix * CSRGetData and CSRGetDataAndIndices passed tests * CSRSliceMatrix basic tests * fix bug in empty slice * CUDA CSRHasDuplicate * has_node; has_edge_between * predecessors, successors * deprecate send/recv; fix send_and_recv * deprecate send/recv; fix send_and_recv * in_edges; out_edges; all_edges; apply_edges * in deg/out deg * subgraph/edge_subgraph * adj * in_subgraph/out_subgraph * sample neighbors * set/get_n/e_repr * wip: working on refactoring all idtypes * pass ndata/edata tests on gpu * fix * stash * workaround nonzero issue * stash * nx conversion * test_hetero_basics except update routines * test_update_routines * test_hetero_basics for pytorch * more fixes * WIP: flatten graph * wip: flatten * test_flatten * test_to_device * fix bug in to_homo * fix bug in CSRSliceMatrix * pass subgraph test * fix send_and_recv * fix filter * test_heterograph * passed all pytorch tests * fix mx unittest * fix pytorch test_nn * fix all unittests for PyTorch * passed all mxnet tests * lint * fix tf nn test * pass all tf tests * lint * lint * change deprecation * try fix compile * lint * update METIDS * fix utest * fix * fix utests * try debug * revert * small fix * fix utests * upd * upd * upd * fix * upd * upd * upd * upd * upd * trigger * +1s * [kernel] Use heterograph index instead of unitgraph index (#1813) * upd * upd * upd * fix * upd * upd * upd * upd * upd * trigger * +1s * [Graph] Mutation for Heterograph (#1818) * mutation add_nodes and add_edges * Add support for remove_edges, remove_nodes, add_selfloop, remove_selfloop * Fix Co-authored-by: Ubuntu <ubuntu@ip-172-31-51-214.ec2.internal> * upd * upd * upd * fix * [Transfom] Mutable transform (#1833) * add nodesy * All three * Fix * lint * Add some test case * Fix * Fix * Fix * Fix * Fix * Fix * fix * triger * Fix * fix Co-authored-by: Ubuntu <ubuntu@ip-172-31-51-214.ec2.internal> * [Graph] Migrate Batch & Readout module to heterograph (#1836) * dgl.batch * unbatch * fix to device * reduce readout; segment reduce * change batch_num_nodes|edges to function * reduce readout/ softmax * broadcast * topk * fix * fix tf and mx * fix some ci * fix batch but unbatch differently * new checkk * upd * upd * upd * idtype behavior; code reorg * idtype behavior; code reorg * wip: test_basics * pass test_basics * WIP: from nx/ to nx * missing files * upd * pass test_basics:test_nx_conversion * Fix test * Fix inplace update * WIP: fixing tests * upd * pass test_transform cpu * pass gpu test_transform * pass test_batched_graph * GPU graph auto cast to int32 * missing file * stash * WIP: rgcn-hetero * Fix two datasety * upd * weird * Fix capsuley * fuck you * fuck matthias * Fix dgmg * fix bug in block degrees; pass rgcn-hetero * rgcn * gat and diffpool fix also fix ppi and tu dataset * Tree LSTM * pointcloud * rrn; wip: sgc * resolve conflicts * upd * sgc and reddit dataset * upd * Fix deepwalk, gindt and gcn * fix datasets and sign * optimization * optimization * upd * upd * Fix GIN * fix bug in add_nodes add_edges; tagcn * adaptive sampling and gcmc * upd * upd * fix geometric * fix * metapath2vec * fix agnn * fix pickling problem of block * fix utests * miss file * linegraph * upd * upd * upd * graphsage * stgcn_wave * fix hgt * on unittests * Fix transformer * Fix HAN * passed pytorch unittests * lint * fix * Fix cluster gcn * cluster-gcn is ready * on fixing block related codes * 2nd order derivative * Revert "2nd order derivative" This reverts commit 523bf6c249bee61b51b1ad1babf42aad4167f206. * passed torch utests again * fix all mxnet unittests * delete some useless tests * pass all tf cpu tests * disable * disable distributed unittest * fix * fix * lint * fix * fix * fix script * fix tutorial * fix apply edges bug * fix 2 basics * fix tutorial Co-authored-by: yzh119 <expye@outlook.com> Co-authored-by: xiang song(charlie.song) <classicxsong@gmail.com> Co-authored-by: Ubuntu <ubuntu@ip-172-31-51-214.ec2.internal> Co-authored-by: Ubuntu <ubuntu@ip-172-31-7-42.us-west-2.compute.internal> Co-authored-by: Ubuntu <ubuntu@ip-172-31-1-5.us-west-2.compute.internal> Co-authored-by: Ubuntu <ubuntu@ip-172-31-68-185.ec2.internal>
162 行
4.9 KiB
Python
162 行
4.9 KiB
Python
import sys
|
|
import numpy as np
|
|
from tqdm import tqdm
|
|
|
|
import torch
|
|
import torch.nn as nn
|
|
import torch.optim as optim
|
|
|
|
from dgl.data.gindt import GINDataset
|
|
from dataloader import GraphDataLoader, collate
|
|
from parser import Parser
|
|
from gin import GIN
|
|
|
|
|
|
def train(args, net, trainloader, optimizer, criterion, epoch):
|
|
net.train()
|
|
|
|
running_loss = 0
|
|
total_iters = len(trainloader)
|
|
# setup the offset to avoid the overlap with mouse cursor
|
|
bar = tqdm(range(total_iters), unit='batch', position=2, file=sys.stdout)
|
|
|
|
for pos, (graphs, labels) in zip(bar, trainloader):
|
|
# batch graphs will be shipped to device in forward part of model
|
|
labels = labels.to(args.device)
|
|
feat = graphs.ndata.pop('attr').to(args.device)
|
|
graphs = graphs.to(args.device)
|
|
outputs = net(graphs, feat)
|
|
|
|
loss = criterion(outputs, labels)
|
|
running_loss += loss.item()
|
|
|
|
# backprop
|
|
optimizer.zero_grad()
|
|
loss.backward()
|
|
optimizer.step()
|
|
|
|
# report
|
|
bar.set_description('epoch-{}'.format(epoch))
|
|
bar.close()
|
|
# the final batch will be aligned
|
|
running_loss = running_loss / total_iters
|
|
|
|
return running_loss
|
|
|
|
|
|
def eval_net(args, net, dataloader, criterion):
|
|
net.eval()
|
|
|
|
total = 0
|
|
total_loss = 0
|
|
total_correct = 0
|
|
|
|
for data in dataloader:
|
|
graphs, labels = data
|
|
feat = graphs.ndata.pop('attr').to(args.device)
|
|
graphs = graphs.to(args.device)
|
|
labels = labels.to(args.device)
|
|
total += len(labels)
|
|
outputs = net(graphs, feat)
|
|
_, predicted = torch.max(outputs.data, 1)
|
|
|
|
total_correct += (predicted == labels.data).sum().item()
|
|
loss = criterion(outputs, labels)
|
|
# crossentropy(reduce=True) for default
|
|
total_loss += loss.item() * len(labels)
|
|
|
|
loss, acc = 1.0*total_loss / total, 1.0*total_correct / total
|
|
|
|
net.train()
|
|
|
|
return loss, acc
|
|
|
|
|
|
def main(args):
|
|
|
|
# set up seeds, args.seed supported
|
|
torch.manual_seed(seed=args.seed)
|
|
np.random.seed(seed=args.seed)
|
|
|
|
is_cuda = not args.disable_cuda and torch.cuda.is_available()
|
|
|
|
if is_cuda:
|
|
args.device = torch.device("cuda:" + str(args.device))
|
|
torch.cuda.manual_seed_all(seed=args.seed)
|
|
else:
|
|
args.device = torch.device("cpu")
|
|
|
|
dataset = GINDataset(args.dataset, not args.learn_eps)
|
|
|
|
trainloader, validloader = GraphDataLoader(
|
|
dataset, batch_size=args.batch_size, device=args.device,
|
|
collate_fn=collate, seed=args.seed, shuffle=True,
|
|
split_name='fold10', fold_idx=args.fold_idx).train_valid_loader()
|
|
# or split_name='rand', split_ratio=0.7
|
|
|
|
model = GIN(
|
|
args.num_layers, args.num_mlp_layers,
|
|
dataset.dim_nfeats, args.hidden_dim, dataset.gclasses,
|
|
args.final_dropout, args.learn_eps,
|
|
args.graph_pooling_type, args.neighbor_pooling_type).to(args.device)
|
|
|
|
criterion = nn.CrossEntropyLoss() # defaul reduce is true
|
|
optimizer = optim.Adam(model.parameters(), lr=args.lr)
|
|
scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=50, gamma=0.5)
|
|
|
|
# it's not cost-effective to hanle the cursor and init 0
|
|
# https://stackoverflow.com/a/23121189
|
|
tbar = tqdm(range(args.epochs), unit="epoch", position=3, ncols=0, file=sys.stdout)
|
|
vbar = tqdm(range(args.epochs), unit="epoch", position=4, ncols=0, file=sys.stdout)
|
|
lrbar = tqdm(range(args.epochs), unit="epoch", position=5, ncols=0, file=sys.stdout)
|
|
|
|
for epoch, _, _ in zip(tbar, vbar, lrbar):
|
|
|
|
train(args, model, trainloader, optimizer, criterion, epoch)
|
|
scheduler.step()
|
|
|
|
train_loss, train_acc = eval_net(
|
|
args, model, trainloader, criterion)
|
|
tbar.set_description(
|
|
'train set - average loss: {:.4f}, accuracy: {:.0f}%'
|
|
.format(train_loss, 100. * train_acc))
|
|
|
|
valid_loss, valid_acc = eval_net(
|
|
args, model, validloader, criterion)
|
|
vbar.set_description(
|
|
'valid set - average loss: {:.4f}, accuracy: {:.0f}%'
|
|
.format(valid_loss, 100. * valid_acc))
|
|
|
|
if not args.filename == "":
|
|
with open(args.filename, 'a') as f:
|
|
f.write('%s %s %s %s' % (
|
|
args.dataset,
|
|
args.learn_eps,
|
|
args.neighbor_pooling_type,
|
|
args.graph_pooling_type
|
|
))
|
|
f.write("\n")
|
|
f.write("%f %f %f %f" % (
|
|
train_loss,
|
|
train_acc,
|
|
valid_loss,
|
|
valid_acc
|
|
))
|
|
f.write("\n")
|
|
|
|
lrbar.set_description(
|
|
"Learning eps with learn_eps={}: {}".format(
|
|
args.learn_eps, [layer.eps.data.item() for layer in model.ginlayers]))
|
|
|
|
tbar.close()
|
|
vbar.close()
|
|
lrbar.close()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
args = Parser(description='GIN').args
|
|
print('show all arguments configuration...')
|
|
print(args)
|
|
|
|
main(args)
|