-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmodels.py
More file actions
631 lines (500 loc) · 24.4 KB
/
models.py
File metadata and controls
631 lines (500 loc) · 24.4 KB
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
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
429
430
431
432
433
434
435
436
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
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
625
626
627
628
629
630
631
import torch
import torch.nn.functional as F
from torch.nn import Linear, Sequential, BatchNorm1d, ReLU, Dropout
'''
'''
import copy
import math
import torch
import torch.nn as nn
from timm.models.layers import DropPath, trunc_normal_
from pos_encoding import get_2d_sincos_pos_embed
import torch.nn.functional as F
from einops.layers.torch import Rearrange
def _no_grad_trunc_normal_(tensor, mean, std, a, b):
# Cut & paste from PyTorch official master until it's in a few official releases - RW
# Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
def norm_cdf(x):
# Computes standard normal cumulative distribution function
return (1. + math.erf(x / math.sqrt(2.))) / 2.
with torch.no_grad():
# Values are generated by using a truncated uniform distribution and
# then using the inverse CDF for the normal distribution.
# Get upper and lower cdf values
l = norm_cdf((a - mean) / std)
u = norm_cdf((b - mean) / std)
# Uniformly fill tensor with values from [l, u], then translate to
# [2l-1, 2u-1].
tensor.uniform_(2 * l - 1, 2 * u - 1)
# Use inverse cdf transform for normal distribution to get truncated
# standard normal
tensor.erfinv_()
# Transform to proper mean, std
tensor.mul_(std * math.sqrt(2.))
tensor.add_(mean)
# Clamp to ensure it's in the proper range
tensor.clamp_(min=a, max=b)
return tensor
def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):
# type: (Tensor, float, float, float, float) -> Tensor
return _no_grad_trunc_normal_(tensor, mean, std, a, b)
## Transformers
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class Attention_with_padding(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = qk_scale or head_dim ** -0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x, n_valid_tokens):
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
attn = (q @ k.transpose(-2, -1)) * self.scale
# Create the attention mask
attention_mask = torch.arange(N).unsqueeze(0).expand(B, N).to(x.device) < n_valid_tokens.unsqueeze(1)
attention_mask = attention_mask.unsqueeze(1).unsqueeze(2) # (B, 1, 1, N)
# Apply the attention mask
attn = attn.masked_fill(~attention_mask, float('-inf'))
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
class Block(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):
super().__init__()
self.norm1 = norm_layer(dim)
# NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
self.attn = Attention_with_padding(
dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
def forward(self, x, n_valid_tokens):
x = x + self.drop_path(self.attn(self.norm1(x), n_valid_tokens))
x = x + self.drop_path(self.mlp(self.norm2(x)))
return x
class Encoder_Block(nn.Module):
def __init__(self, embed_dim=384, depth=12, num_heads=6, mlp_ratio=4., qkv_bias=False, qk_scale=None,
drop_rate=0., attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm):
super().__init__()
self.blocks = nn.ModuleList([
Block(
dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
drop=drop_rate, attn_drop=attn_drop_rate,
drop_path = drop_path_rate[i] if isinstance(drop_path_rate, list) else drop_path_rate,
norm_layer=norm_layer)
for i in range(depth)])
def forward(self, x, n_valid_tokens, pos_embed):
for i, block in enumerate(self.blocks):
x = block(x+pos_embed, n_valid_tokens) + (x + pos_embed)
return x
class Transformer(nn.Module):
def __init__(
self,
embed_dim=384,
depth=12,
num_heads=6,
grid_size=50,
patch_size=5,
mlp_ratio=4.0,
qkv_bias=False,
qk_scale=None,
cls_token=False,
token='nonlinear',
pos_type='sincos',
drop_rate=0.0,
attn_drop_rate=0.0,
drop_path_rate=0.0,
norm_layer=nn.LayerNorm,
init_std=0.02,
classification_head=False,
num_classes=5
):
super().__init__()
self.init_std = init_std
# self.mask_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
self.grid_size = grid_size
self.patch_size = patch_size
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim), requires_grad=True) if cls_token else None
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)]
self.encoder_blocks = Encoder_Block(embed_dim=embed_dim, depth=depth, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop_rate=drop_rate, attn_drop_rate=attn_drop_rate, drop_path_rate=dpr, norm_layer=norm_layer)
self.norm = nn.LayerNorm(embed_dim)
self.embed_dim = embed_dim
self.token = token
if token == 'conv':
self.tokenizer = nn.Conv2d(in_channels=4, out_channels=embed_dim, kernel_size=patch_size, stride=patch_size, padding=0)
elif token == 'linear':
patch_dim = 4*patch_size**2
self.tokenizer = nn.Sequential(
Rearrange('b c (h p1) (w p2) -> b (h w) (p1 p2 c)', p1=patch_size, p2=patch_size, c=4),
nn.LayerNorm(patch_dim),
nn.Linear(patch_dim, embed_dim),
nn.LayerNorm(embed_dim),
)
elif token == 'nonlinear':
patch_dim = 4*patch_size**2
self.tokenizer = nn.Sequential(
Rearrange('b c (h p1) (w p2) -> b (h w) (p1 p2 c)', p1=patch_size, p2=patch_size, c=4),
nn.LayerNorm(patch_dim),
nn.Linear(patch_dim, embed_dim//2),
nn.LayerNorm(embed_dim//2),
nn.GELU(),
nn.Linear(embed_dim//2, embed_dim),
nn.LayerNorm(embed_dim),
)
self.classification_head = classification_head
self.decoder = nn.Sequential(
nn.Linear(embed_dim, embed_dim),
nn.GELU(),
nn.Dropout(0.2),
nn.Linear(embed_dim, num_classes)
# nn.Linear(embed_dim, num_classes),
)
self.patch_num = grid_size // patch_size
self.pos_type = pos_type
if pos_type == 'sincos':
self.pos_embed = nn.Parameter(torch.zeros((self.patch_num)**2 + cls_token, embed_dim), requires_grad=False)
pos_embed = get_2d_sincos_pos_embed(embed_dim, self.patch_num , self.patch_num, cls_token=cls_token)
self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float())
elif pos_type == 'learnable':
self.pos_embed = nn.Sequential(
nn.Linear(2, embed_dim//2),
nn.GELU(),
nn.Linear(embed_dim//2, embed_dim)
)
# initialize the learnable token
# trunc_normal_(self.mask_token, std=init_std)
self.apply(self._init_weights)
self.fix_init_weight()
def apply_transform_to_batch(batch, transform):
n, c, h, w = batch.shape
transformed_batch = torch.zeros_like(batch)
for i in range(n):
transformed_batch[i] = transform(batch[i])
return transformed_batch
def fix_init_weight(self):
def rescale(param, layer_id):
param.div_(math.sqrt(2.0 * layer_id))
for layer_id, layer in enumerate(self.encoder_blocks.blocks):
rescale(layer.attn.proj.weight.data, layer_id + 1)
rescale(layer.mlp.fc2.weight.data, layer_id + 1)
def _init_weights(self, m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=self.init_std)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
elif isinstance(m, nn.Conv1d):
trunc_normal_(m.weight, std=self.init_std)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
def find_empty_tokens(self, quantized_rdgms, kernel_size, stride):
kernel = torch.ones((1, 1, kernel_size, kernel_size), dtype=torch.float32, device=quantized_rdgms.device)
convolved = F.conv2d(quantized_rdgms, kernel, stride=stride, padding=0) # (bs, 1, 10, 10)
convolved = convolved.squeeze(1) # (bs, 10, 10)
mask = (convolved == 0) # True if empty token
return mask
def slice_and_pad(self, x, mask):
# Find the maximum number of True values in any mask[i]
m = torch.max(mask.sum(dim=1)).item()
# Initialize the output tensor with zeros
bs = x.size(0)
dim = x.size(-1)
result = torch.zeros((bs, m, dim), dtype=x.dtype, device=x.device)
n_valid_tokens = torch.zeros(bs, dtype=torch.int64, device=x.device, requires_grad=False)
for i in range(bs):
true_indices = torch.nonzero(mask[i], as_tuple=True)[0]
sliced_x = x[i, true_indices]
result[i, :len(true_indices)] = sliced_x
n_valid_tokens[i] = len(true_indices)
return result, n_valid_tokens
def forward(self, data):
'''
data: torch_geometric.data.batch object, added with 'ppd' attribute
ppd : (bs, 4, grid_size, grid_size)
'''
ppd = data.ppd
ppd = ppd.reshape(-1, 4, self.grid_size, self.grid_size)
bs = ppd.size(0)
if self.token == 'conv':
x = self.tokenizer(ppd).reshape(bs, -1, self.embed_dim) # (bs, patch_num^2, embed_dim)
elif self.token == 'linear' or self.token == 'nonlinear':
x = self.tokenizer(ppd)
if self.pos_type == 'sincos':
pos_embed = self.pos_embed.unsqueeze(0).expand(bs, -1, self.embed_dim) # (bs, 1 + patch_num^2, embed_dim)
elif self.pos_type == 'learnable':
pos_embed = self.pos_embed(ppd.sum(dim=1).unsqueeze(1).float())
mask = self.find_empty_tokens(ppd.sum(dim=1).unsqueeze(1), self.patch_size, self.patch_size).reshape(bs, -1) # (bs, patch_num^2)
cls_token = self.cls_token.expand(bs, -1, -1)
x = torch.cat((cls_token, x), dim=1)
cls_mask = torch.zeros(bs, 1, dtype=torch.bool, device=x.device)
mask = torch.cat((cls_mask, mask), dim=1)
x, n_valid_tokens = self.slice_and_pad(x, ~mask)
n_valid_tokens += 1
pos_embed, _ = self.slice_and_pad(pos_embed, ~mask)
x = self.encoder_blocks(x, n_valid_tokens, pos_embed)
# Apply normalization if specified
if self.norm is not None:
x = self.norm(x)
x_cls = x[:, 0]
if self.classification_head:
# return self.decoder(x_cls + x[:,1:].max(dim=1)[0])
return self.decoder(x_cls)
else:
return x_cls
def quantization(rdgms, grid_size=50):
'''
Read rotated persistence diagrams, and outputs a matrix of size (grid_size, grid_size).
Rotated diagrams are quantized into grids, where the maximum values of x and y are given by 'x_ranges' and 'y_ranges'.
Each entry of the matrix contains the number of points in the diagram that correspond to each grid.
Outputs the matrix.
rdgms : (bs, n_pts, 2)
output : (bs, grid_size, grid_size)
'''
bs, n_pts, _ = rdgms.shape
ppd = torch.zeros((bs, grid_size, grid_size), dtype=torch.float32)
births = rdgms[:, :, 0]
pers = rdgms[:, :, 1]
# Filter out points with persistence 0
valid_mask = (pers != 0)
births = births * valid_mask
pers = pers * valid_mask
max_birth = births.max(dim=1, keepdim=True)[0]
max_per = pers.max(dim=1, keepdim=True)[0]
x_range = torch.where(max_birth == 0, torch.ones_like(max_birth), 1.1 * max_birth)
y_range = 1.1 * max_per
x_step = x_range / grid_size
y_step = y_range / grid_size
x_indices = ((births / x_step).floor())
y_indices = ((pers / y_step).floor())
x_indices = torch.clamp(x_indices, 0, grid_size - 1)
y_indices = torch.clamp(y_indices, 0, grid_size - 1)
for i in range(bs):
idx_comb = (y_indices[i] * grid_size + x_indices[i]).to(torch.int64)
idx_comb = idx_comb[valid_mask[i]]
counts = torch.bincount(idx_comb, minlength=grid_size * grid_size).float()
ppd[i] = counts.view(grid_size, grid_size)
return ppd
class Transformer_orbit(nn.Module):
def __init__(
self,
embed_dim=192,
depth=5,
num_heads=8,
grid_size=50,
patch_size=5,
mlp_ratio=4.0,
qkv_bias=False,
qk_scale=None,
cls_token=False,
pos_type='learnable',
drop_rate=0.0,
attn_drop_rate=0.0,
drop_path_rate=0.0,
norm_layer=nn.LayerNorm,
init_std=0.02,
n_classes=5
):
super().__init__()
self.init_std = init_std
# self.mask_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
self.grid_size = grid_size
self.patch_size = patch_size
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim), requires_grad=True) if cls_token else None
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)]
self.encoder_blocks = Encoder_Block(embed_dim=embed_dim, depth=depth, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop_rate=drop_rate, attn_drop_rate=attn_drop_rate, drop_path_rate=dpr, norm_layer=norm_layer)
self.norm = nn.LayerNorm(embed_dim)
self.embed_dim = embed_dim
self.tokenizer0 = nn.Conv1d(in_channels=1, out_channels=embed_dim, kernel_size=patch_size, stride=patch_size, padding=0)
self.tokenizer1 = nn.Conv2d(in_channels=1, out_channels=embed_dim, kernel_size=patch_size, stride=patch_size, padding=0)
self.decoder = nn.Sequential(
nn.Linear(embed_dim, n_classes),
)
self.patch_num = grid_size // patch_size
self.pos_type = pos_type
if pos_type == 'learnable':
self.pos_embed0 = nn.Sequential(
nn.Linear(1, embed_dim//2),
nn.GELU(),
nn.Linear(embed_dim//2, embed_dim)
)
self.pos_embed1 = nn.Sequential(
nn.Linear(2, embed_dim//2),
nn.GELU(),
nn.Linear(embed_dim//2, embed_dim)
)
elif pos_type == 'sincos':
self.pos_embed = nn.Parameter(torch.zeros((self.patch_num)**2 + self.patch_num + cls_token, embed_dim), requires_grad=False)
pos_embed = get_2d_sincos_pos_embed(embed_dim, self.patch_num + 1, self.patch_num, cls_token=cls_token)
self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float())
# initialize the learnable token
# trunc_normal_(self.mask_token, std=init_std)
self.apply(self._init_weights)
self.fix_init_weight()
def fix_init_weight(self):
def rescale(param, layer_id):
param.div_(math.sqrt(2.0 * layer_id))
for layer_id, layer in enumerate(self.encoder_blocks.blocks):
rescale(layer.attn.proj.weight.data, layer_id + 1)
rescale(layer.mlp.fc2.weight.data, layer_id + 1)
def _init_weights(self, m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=self.init_std)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
elif isinstance(m, nn.Conv1d):
trunc_normal_(m.weight, std=self.init_std)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
def find_empty_tokens(self, quantized_rdgms, kernel_size, stride):
if quantized_rdgms.dim() == 4:
kernel = torch.ones((1, 1, kernel_size, kernel_size), dtype=torch.float32, device=quantized_rdgms.device)
convolved = F.conv2d(quantized_rdgms, kernel, stride=stride, padding=0) # (bs, 1, 10, 10)
elif quantized_rdgms.dim() == 3:
kernel = torch.ones((1, 1, kernel_size), dtype=torch.float32, device=quantized_rdgms.device)
convolved = F.conv1d(quantized_rdgms, kernel, stride=stride, padding=0)
convolved = convolved.squeeze(1)
mask = (convolved == 0)
return mask
def slice_and_pad(self, x, mask):
# Find the maximum number of True values in any mask[i]
m = torch.max(mask.sum(dim=1)).item()
# Initialize the output tensor with zeros
bs = x.size(0)
dim = x.size(-1)
result = torch.zeros((bs, m, dim), dtype=x.dtype, device=x.device)
n_valid_tokens = torch.zeros(bs, dtype=torch.int64, device=x.device, requires_grad=False)
for i in range(bs):
true_indices = torch.nonzero(mask[i], as_tuple=True)[0]
sliced_x = x[i, true_indices]
result[i, :len(true_indices)] = sliced_x
n_valid_tokens[i] = len(true_indices)
return result, n_valid_tokens
def forward(self, rdgms0, rdgms1):
'''
rdgms : (bs, n_pts, 2)
'''
bs,_,_ = rdgms1.shape
quantized_rdgms0 = quantization(rdgms0, grid_size=self.grid_size) # (bs, 1, grid_size, grid_size): quantized diagrams
quantized_rdgms0 = quantized_rdgms0.unsqueeze(1) # (bs, 1, grid_size, grid_size)
quantized_rdgms0 = quantized_rdgms0[:,:,:,0].to('cuda') # (bs, 1, grid_size)
x0 = self.tokenizer0(quantized_rdgms0).permute(0,2,1) # (bs, embed_dim, grid_size) -> (bs, patch_num, embed_dim)
quantized_rdgms1 = quantization(rdgms1, grid_size=self.grid_size) # (bs, 1, grid_size, grid_size): quantized diagrams
quantized_rdgms1 = quantized_rdgms1.unsqueeze(1).to('cuda') # (bs, 1, grid_size, grid_size)
mask1 = self.find_empty_tokens(quantized_rdgms1, self.patch_size, self.patch_size) # (bs, 10, 10)
x1 = self.tokenizer1(quantized_rdgms1).permute(0,2,3,1) # (bs, embed_dim, grid_size, grid_size) -> (bs, patch_num, patch_num, embed_dim)
pos_embed = self.pos_embed.unsqueeze(0).expand(x1.size(0), -1, self.embed_dim) # (bs, 1 + patch_num^2 + patch_num, embed_dim)
x1 = x1.reshape(bs, -1, self.embed_dim) # (bs, patch_num^2, embed_dim)
mask1 = mask1.reshape(bs, -1)
x1, n_valid_tokens1 = self.slice_and_pad(x1, ~mask1)
cls_mask = torch.zeros(bs, 1, dtype=torch.bool, device=x1.device)
rdgms0_mask = torch.zeros(bs, self.patch_num, dtype=torch.bool, device=x1.device)
mask = torch.cat([cls_mask, rdgms0_mask, mask1], dim=1)
# mask = torch.cat([cls_mask, mask0, mask1], dim=1)
pos_embed, _ = self.slice_and_pad(pos_embed, ~mask)
# Concat x0 and x1
cls_token = self.cls_token.expand(bs, 1, -1)
x = torch.concat([cls_token, x0, x1], dim=1)
n_valid_tokens1_new = self.patch_num + n_valid_tokens1 + 1
x = self.encoder_blocks(x, n_valid_tokens1_new, pos_embed)
# Apply normalization if specified
if self.norm is not None:
x = self.norm(x)
x_cls = x[:, 0]
x_cls = self.decoder(x_cls)
# x_cls = self.decoder(x_cls + x[:,1:].max(dim=1)[0])
return x_cls
from torch_geometric.nn import GINConv, global_add_pool
class GIN(torch.nn.Module):
def __init__(self, dim_h, num_node_features=1, num_classes=2):
super(GIN, self).__init__()
self.conv1 = GINConv(Sequential(Linear(num_node_features, dim_h), BatchNorm1d(dim_h), ReLU(), Linear(dim_h, dim_h), ReLU()))
self.conv2 = GINConv(Sequential(Linear(dim_h, dim_h), BatchNorm1d(dim_h), ReLU(), Linear(dim_h, dim_h), ReLU()))
self.conv3 = GINConv(Sequential(Linear(dim_h, dim_h), BatchNorm1d(dim_h), ReLU(), Linear(dim_h, dim_h), ReLU()))
self.lin1 = Linear(3*dim_h, 3*dim_h)
self.lin2 = Linear(3*dim_h, num_classes)
def forward(self, data):
x, edge_index, batch = data.node_feat, data.edge_index, data.batch
# node embedding
h1 = self.conv1(x, edge_index)
h2 = self.conv2(h1, edge_index)
h3 = self.conv3(h2, edge_index)
# graph-level readout
h1 = global_add_pool(h1, batch)
h2 = global_add_pool(h2, batch)
h3 = global_add_pool(h3, batch)
# concatenate graph embeddings
h = torch.cat([h1, h2, h3], dim=1) # (bs, 3*dim_h)
# Classifier
h = self.lin1(h)
h = h.relu()
h = F.dropout(h, p=0.5, training=self.training)
h = self.lin2(h)
return F.log_softmax(h, dim=1)
class GIN_assisted(torch.nn.Module):
def __init__(self, transformer, dim_h, num_node_features=1, num_classes=2, assist='concat'):
super(GIN_assisted, self).__init__()
self.conv1 = GINConv(Sequential(Linear(num_node_features, dim_h), BatchNorm1d(dim_h), ReLU(), Linear(dim_h, dim_h), ReLU()))
self.conv2 = GINConv(Sequential(Linear(dim_h, dim_h), BatchNorm1d(dim_h), ReLU(), Linear(dim_h, dim_h), ReLU()))
self.conv3 = GINConv(Sequential(Linear(dim_h, dim_h), BatchNorm1d(dim_h), ReLU(), Linear(dim_h, dim_h), ReLU()))
self.transformer = transformer
if assist == 'concat':
self.lin1 = Linear(3*dim_h + 192, 3*dim_h)
elif assist == 'sum':
self.lin1 = Linear(3*dim_h, 3*dim_h)
self.lin2 = Linear(3*dim_h, num_classes)
self.assist = assist
def forward(self, data):
x, edge_index, batch, qepd = data.node_feat, data.edge_index, data.batch, data.ppd
# node embedding
h1 = self.conv1(x, edge_index)
h2 = self.conv2(h1, edge_index)
h3 = self.conv3(h2, edge_index)
# graph-level readout
h1 = global_add_pool(h1, batch)
h2 = global_add_pool(h2, batch)
h3 = global_add_pool(h3, batch)
# concatenate graph embeddings
h = torch.cat([h1, h2, h3], dim=1) # (bs, 3*dim_h)
# transformer
ppd = data.ppd
cls_token = self.transformer(ppd)
if self.assist == 'concat':
h = torch.cat([h, cls_token], dim=1) # (bs, 3*dim_h + embed_dim)
elif self.assist == 'sum':
h = h + cls_token
# Classifier
h = self.lin1(h)
h = h.relu()
h = F.dropout(h, p=0.5, training=self.training)
h = self.lin2(h)
return F.log_softmax(h, dim=1)