-
Notifications
You must be signed in to change notification settings - Fork 5
/
test_minmax_transfer_pretrain_bio.py
190 lines (142 loc) · 7.16 KB
/
test_minmax_transfer_pretrain_bio.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import argparse
import logging
import random
from pathlib import Path
import numpy as np
import torch
from torch_geometric.data import DataLoader
from torch_geometric.transforms import Compose
from torch_scatter import scatter
from tqdm import tqdm
from datasets import BioDataset
from transfer import BioGNN
from transfer.learning import GInfoMinMax, ViewLearner
from unsupervised.utils import initialize_edge_weight
def setup_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
np.random.seed(seed)
random.seed(seed)
def train(args, model, view_learner, device, dataset, model_optimizer, view_optimizer):
dataset = dataset.shuffle()
dataloader = DataLoader(dataset, batch_size=args.batch_size, num_workers=8, shuffle=False)
model.train()
model_loss_all = 0
view_loss_all = 0
reg_all = 0
for step, batch in enumerate(dataloader):
batch = batch.to(device)
# train view to maximize contrastive loss
view_learner.train()
view_learner.zero_grad()
model.eval()
x = model(batch.batch, batch.x, batch.edge_index, batch.edge_attr, None)
edge_logits = view_learner(batch.batch, batch.x, batch.edge_index, batch.edge_attr)
temperature = 1.0
bias = 0.0 + 0.0001 # If bias is 0, we run into problems
eps = (bias - (1 - bias)) * torch.rand(edge_logits.size()) + (1 - bias)
gate_inputs = torch.log(eps) - torch.log(1 - eps)
gate_inputs = gate_inputs.to(device)
gate_inputs = (gate_inputs + edge_logits) / temperature
batch_aug_edge_weight = torch.sigmoid(gate_inputs).squeeze()
x_aug = model(batch.batch, batch.x, batch.edge_index, batch.edge_attr, batch_aug_edge_weight)
# regularization
row, col = batch.edge_index
edge_batch = batch.batch[row]
edge_drop_out_prob = 1 - batch_aug_edge_weight
uni, edge_batch_num = edge_batch.unique(return_counts=True)
sum_pe = scatter(edge_drop_out_prob, edge_batch, reduce="sum")
reg = []
for b_id in range(args.batch_size):
if b_id in uni:
num_edges = edge_batch_num[uni.tolist().index(b_id)]
reg.append(sum_pe[b_id] / num_edges)
else:
# means no edges in that graph. So don't include.
pass
num_graph_with_edges = len(reg)
reg = torch.stack(reg)
reg = reg.mean()
view_loss = model.calc_loss(x, x_aug, temperature=0.2) - (args.reg_lambda * reg)
view_loss_all += view_loss.item() * batch.num_graphs
reg_all += reg.item()
# gradient ascent formulation
(-view_loss).backward()
view_optimizer.step()
model.train()
view_learner.eval()
# train (model) to minimize contrastive loss
model.zero_grad()
x = model(batch.batch, batch.x, batch.edge_index, batch.edge_attr, None)
edge_logits = view_learner(batch.batch, batch.x, batch.edge_index, batch.edge_attr)
temperature = 1.0
bias = 0.0 + 0.0001 # If bias is 0, we run into problems
eps = (bias - (1 - bias)) * torch.rand(edge_logits.size()) + (1 - bias)
gate_inputs = torch.log(eps) - torch.log(1 - eps)
gate_inputs = gate_inputs.to(device)
gate_inputs = (gate_inputs + edge_logits) / temperature
batch_aug_edge_weight = torch.sigmoid(gate_inputs).squeeze().detach()
x_aug = model(batch.batch, batch.x, batch.edge_index, batch.edge_attr, batch_aug_edge_weight)
model_loss = model.calc_loss(x, x_aug, temperature=0.2)
model_loss_all += model_loss.item() * batch.num_graphs
# standard gradient descent formulation
model_loss.backward()
model_optimizer.step()
fin_model_loss = model_loss_all / len(dataloader)
fin_view_loss = view_loss_all / len(dataloader)
fin_reg = reg_all / len(dataloader)
return fin_model_loss, fin_view_loss, fin_reg
def run(args):
Path("./models_minmax/bio").mkdir(parents=True, exist_ok=True)
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S')
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
logging.info("Using Device: %s" % device)
logging.info("Seed: %d" % args.seed)
logging.info(args)
setup_seed(args.seed)
my_transforms = Compose([initialize_edge_weight])
dataset = BioDataset("original_datasets/transfer/bio/unsupervised", data_type="unsupervised", transform=my_transforms)
model = GInfoMinMax(
BioGNN(num_layer=args.num_gc_layers, emb_dim=args.emb_dim, JK="last", drop_ratio=args.drop_ratio, gnn_type="gin"),
proj_hidden_dim=args.emb_dim).to(device)
model_optimizer = torch.optim.Adam(model.parameters(), lr=args.model_lr)
view_learner = ViewLearner(
BioGNN(num_layer=args.num_gc_layers, emb_dim=args.emb_dim, JK="last", drop_ratio=args.drop_ratio, gnn_type="gin"),
mlp_edge_model_dim=args.mlp_edge_model_dim).to(device)
view_optimizer = torch.optim.Adam(view_learner.parameters(), lr=args.view_lr)
for epoch in tqdm(range(1, args.epochs)):
logging.info('====epoch {}'.format(epoch))
model_loss, view_loss, reg = train(args, model, view_learner, device, dataset, model_optimizer, view_optimizer)
logging.info(
'Epoch {}, Model Loss {}, View Loss {}, Reg {}'.format(epoch, model_loss, view_loss, reg))
if epoch % 1 == 0:
torch.save(model.gnn.state_dict(), "./models_minmax/bio/pretrain_minmax_seed_"+str(args.seed)+"_reg_"+str(args.reg_lambda)+"_epoch_"+ str(epoch)+".pth")
def arg_parse():
parser = argparse.ArgumentParser(description='Transfer Learning AD-GCL Pretrain on PPI-306K')
parser.add_argument('--dataset', type=str, default='unsupervised',
help='Dataset')
parser.add_argument('--model_lr', type=float, default=0.001,
help='Model Learning rate.')
parser.add_argument('--view_lr', type=float, default=0.001,
help='View Learning rate.')
parser.add_argument('--num_gc_layers', type=int, default=5,
help='Number of GNN layers before pooling')
parser.add_argument('--pooling_type', type=str, default='standard',
help='GNN Pooling Type Standard/Layerwise')
parser.add_argument('--emb_dim', type=int, default=300,
help='embedding dimension')
parser.add_argument('--mlp_edge_model_dim', type=int, default=64,
help='embedding dimension')
parser.add_argument('--batch_size', type=int, default=256,
help='batch size')
parser.add_argument('--drop_ratio', type=float, default=0.0,
help='Dropout Ratio / Probability')
parser.add_argument('--epochs', type=int, default=100,
help='Train Epochs')
parser.add_argument('--reg_lambda', type=float, default=5.0, help='View Learner Edge Perturb Regularization Strength')
parser.add_argument('--seed', type=int, default=0)
return parser.parse_args()
if __name__ == '__main__':
args = arg_parse()
run(args)