Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

bgrl.py 8.4 KB

You have to be logged in to leave a comment. Sign In
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
  1. from copy import deepcopy
  2. from typing import Dict, List, Union
  3. import numpy as np
  4. from pl_bolts.optimizers.lr_scheduler import LinearWarmupCosineAnnealingLR
  5. import torch
  6. from torch import nn
  7. from torch.nn import functional as F
  8. from torch_geometric.data import Data
  9. from torch_geometric.data import NeighborSampler
  10. from torch_geometric.data.sampler import EdgeIndex
  11. from torch_geometric import nn as tgnn
  12. from tqdm import tqdm
  13. from gssl.augment import GraphAugmentor
  14. from gssl.batched.encoders import get_inference_loader
  15. from gssl.tasks import evaluate_node_classification_acc
  16. class TwoLayerGCN(nn.Module):
  17. def __init__(self, in_dim: int, hidden_dim: int, out_dim: int):
  18. super().__init__()
  19. self._conv1 = tgnn.GCNConv(in_dim, hidden_dim)
  20. self._conv2 = tgnn.GCNConv(hidden_dim, out_dim)
  21. self._bn1 = nn.BatchNorm1d(hidden_dim, momentum=0.01) # same as `weight_decay = 0.99`
  22. self._bn2 = nn.BatchNorm1d(out_dim, momentum=0.01)
  23. self._act1 = nn.PReLU()
  24. self._act2 = nn.PReLU()
  25. def forward(self, x, edge_index):
  26. x = self._conv1(x, edge_index)
  27. x = self._bn1(x)
  28. x = self._act1(x)
  29. x = self._conv2(x, edge_index)
  30. x = self._bn2(x)
  31. x = self._act2(x)
  32. return x
  33. class BGRL(nn.Module):
  34. def __init__(
  35. self,
  36. encoder: nn.Module,
  37. augmentor: GraphAugmentor,
  38. out_dim: int,
  39. pred_dim: int,
  40. ):
  41. super().__init__()
  42. self._online_encoder = encoder
  43. self._target_encoder = None
  44. self._augmentor = augmentor
  45. self._predictor = torch.nn.Sequential(
  46. nn.Linear(out_dim, pred_dim),
  47. nn.BatchNorm1d(pred_dim, momentum=0.01),
  48. nn.PReLU(),
  49. nn.Linear(pred_dim, out_dim),
  50. nn.BatchNorm1d(out_dim, momentum=0.01),
  51. nn.PReLU(),
  52. )
  53. def get_target_encoder(self):
  54. if self._target_encoder is None:
  55. self._target_encoder = deepcopy(self._online_encoder)
  56. for p in self._target_encoder.parameters():
  57. p.requires_grad = False
  58. return self._target_encoder
  59. def update_target_encoder(self, momentum: float):
  60. for p, new_p in zip(
  61. self.get_target_encoder().parameters(),
  62. self._online_encoder.parameters(),
  63. ):
  64. next_p = momentum * p.data + (1 - momentum) * new_p.data
  65. p.data = next_p
  66. def forward(self, data: Data):
  67. (x1, edge_index1), (x2, edge_index2) = self._augmentor(data=data)
  68. h1 = self._online_encoder(x1, edge_index1)
  69. h2 = self._online_encoder(x2, edge_index2)
  70. h1_pred = self._predictor(h1)
  71. h2_pred = self._predictor(h2)
  72. with torch.no_grad():
  73. h1_target = self.get_target_encoder()(x1, edge_index1)
  74. h2_target = self.get_target_encoder()(x2, edge_index2)
  75. return h1, h2, h1_pred, h2_pred, h1_target, h2_target
  76. def predict(self, data: Data):
  77. with torch.no_grad():
  78. return self._online_encoder(data.x, data.edge_index).cpu()
  79. class BatchedBGRL(BGRL):
  80. def __init__(
  81. self,
  82. encoder: nn.Module,
  83. augmentor: GraphAugmentor,
  84. out_dim: int,
  85. pred_dim: int,
  86. inference_batch_size: int,
  87. ):
  88. super().__init__(
  89. encoder=encoder,
  90. augmentor=augmentor,
  91. out_dim=out_dim,
  92. pred_dim=pred_dim,
  93. )
  94. self._inference_batch_size = inference_batch_size
  95. def forward(self, x: torch.Tensor, adjs: List[EdgeIndex]):
  96. (x1, edge_indexes1), (x2, edge_indexes2) = self._augmentor.augment_batch(
  97. x=x, adjs=adjs
  98. )
  99. sizes = [adj.size[1] for adj in adjs]
  100. h1 = self._online_encoder(x=x1, edge_indexes=edge_indexes1, sizes=sizes)
  101. h2 = self._online_encoder(x=x2, edge_indexes=edge_indexes2, sizes=sizes)
  102. h1_pred = self._predictor(h1)
  103. h2_pred = self._predictor(h2)
  104. with torch.no_grad():
  105. h1_target = self.get_target_encoder()(x=x1, edge_indexes=edge_indexes1, sizes=sizes)
  106. h2_target = self.get_target_encoder()(x=x2, edge_indexes=edge_indexes2, sizes=sizes)
  107. return h1, h2, h1_pred, h2_pred, h1_target, h2_target
  108. def predict(self, data: Data):
  109. with torch.no_grad():
  110. h = self._online_encoder.inference(
  111. x_all=data.x,
  112. edge_index_all=data.edge_index,
  113. inference_batch_size=self._inference_batch_size,
  114. device=torch.device(
  115. "cuda" if torch.cuda.is_available() else "cpu"
  116. ),
  117. ).cpu()
  118. return h
  119. class BatchedGAT4BGRL(nn.Module):
  120. def __init__(
  121. self,
  122. in_dim: int,
  123. out_dim: int,
  124. hidden: int = 256,
  125. heads: int = 4,
  126. ):
  127. super().__init__()
  128. self.convs = nn.ModuleList([
  129. tgnn.GATConv(in_dim, hidden, heads=heads, concat=True),
  130. tgnn.GATConv(heads * hidden, hidden, heads=heads, concat=True),
  131. tgnn.GATConv(heads * hidden, out_dim, heads=heads, concat=False),
  132. ])
  133. self.skips = nn.ModuleList([
  134. nn.Linear(in_dim, heads * hidden),
  135. nn.Linear(heads * hidden, heads * hidden),
  136. nn.Linear(heads * hidden, out_dim),
  137. ])
  138. self.bns = nn.ModuleList([
  139. nn.BatchNorm1d(heads * hidden, momentum=0.01),
  140. nn.BatchNorm1d(heads * hidden, momentum=0.01),
  141. nn.BatchNorm1d(out_dim, momentum=0.01),
  142. ])
  143. def forward(self, x, edge_indexes, sizes):
  144. for i, (edge_index, size) in enumerate(zip(edge_indexes, sizes)):
  145. x_target = x[:size]
  146. x = self.convs[i]((x, x_target), edge_index)
  147. x = x + self.skips[i](x_target)
  148. x = self.bns[i](x)
  149. x = F.elu(x)
  150. return x
  151. def inference(self, x_all, edge_index_all, inference_batch_size, device):
  152. pbar = tqdm(total=x_all.size(0) * self.num_layers, leave=False)
  153. pbar.set_description("Evaluation")
  154. inference_loader = get_inference_loader(
  155. edge_index=edge_index_all,
  156. batch_size=inference_batch_size,
  157. num_nodes=x_all.shape[0],
  158. )
  159. for i in range(len(self.convs)):
  160. pbar.set_description(f"Evaluation [{i+1}/{len(self.convs)}]")
  161. xs = []
  162. for batch_size, n_id, adj in inference_loader:
  163. edge_index, _, size = adj.to(device)
  164. x = x_all[n_id].to(device)
  165. x_target = x[:size[1]]
  166. x = self.convs[i]((x, x_target), edge_index)
  167. x = x + self.skips[i](x_target)
  168. x = self.bns[i](x)
  169. x = F.elu(x)
  170. xs.append(x.cpu())
  171. pbar.update(batch_size)
  172. x_all = torch.cat(xs, dim=0)
  173. pbar.close()
  174. return x_all
  175. @property
  176. def num_layers(self):
  177. return len(self.convs)
  178. def compute_tau(
  179. epoch: int,
  180. total_epochs: int,
  181. tau_base: float = 0.99,
  182. ) -> float:
  183. return (
  184. 1.0 - (
  185. ((1.0 - tau_base) / 2.0)
  186. * (np.cos((epoch * np.pi) / total_epochs) + 1.0)
  187. )
  188. )
  189. def test(
  190. model: Union[BGRL, BatchedBGRL],
  191. data: Data,
  192. masks: Dict[str, torch.Tensor],
  193. use_pytorch_eval_model: bool,
  194. device: torch.device,
  195. ):
  196. model.eval()
  197. z = model.predict(data=data.to(device))
  198. accs = evaluate_node_classification_acc(
  199. z=z, data=data, masks=masks, use_pytorch=use_pytorch_eval_model,
  200. )
  201. return z, accs
  202. def train_batched(
  203. model: BatchedBGRL,
  204. contrast_model: torch.nn.Module,
  205. optimizer: torch.optim.AdamW,
  206. scheduler: LinearWarmupCosineAnnealingLR,
  207. data: Data,
  208. loader: NeighborSampler,
  209. device: torch.device,
  210. tau: float,
  211. ):
  212. model.train()
  213. contrast_model.train()
  214. total_loss = 0
  215. for _, n_id, adjs in tqdm(iterable=loader, desc="Batches", leave=False):
  216. adjs = [adj.to(device) for adj in adjs]
  217. optimizer.zero_grad()
  218. _, _, h1_pred, h2_pred, h1_target, h2_target = model(
  219. x=data.x[n_id].to(device), adjs=adjs,
  220. )
  221. loss = contrast_model(
  222. h1_pred=h1_pred, h2_pred=h2_pred,
  223. h1_target=h1_target.detach(), h2_target=h2_target.detach(),
  224. )
  225. loss.backward()
  226. total_loss += loss.item()
  227. optimizer.step()
  228. model.update_target_encoder(tau)
  229. scheduler.step()
  230. avg_loss = total_loss / len(loader)
  231. return avg_loss
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...