-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathgraph_attention_transformer.py
More file actions
executable file
·1016 lines (844 loc) · 41 KB
/
graph_attention_transformer.py
File metadata and controls
executable file
·1016 lines (844 loc) · 41 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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import torch
from torch_cluster import radius_graph
from torch_scatter import scatter
import e3nn
from e3nn import o3
from e3nn.util.jit import compile_mode
from e3nn.nn.models.v2106.gate_points_message_passing import tp_path_exists
import torch_geometric
import math
from .registry import register_model
from .instance_norm import EquivariantInstanceNorm
from .graph_norm import EquivariantGraphNorm
from .layer_norm import EquivariantLayerNormV2
from .fast_layer_norm import EquivariantLayerNormFast
from .radial_func import RadialProfile
from .tensor_product_rescale import (TensorProductRescale, LinearRS,
FullyConnectedTensorProductRescale, irreps2gate, sort_irreps_even_first)
from .fast_activation import Activation, Gate
from .drop import EquivariantDropout, EquivariantScalarsDropout, GraphDropPath
from .gaussian_rbf import GaussianRadialBasisLayer
# for bessel radial basis
from ocpmodels.models.gemnet.layers.radial_basis import RadialBasis
_RESCALE = True
_USE_BIAS = True
# QM9
_MAX_ATOM_TYPE = 5
# Statistics of QM9 with cutoff radius = 5
_AVG_NUM_NODES = 18.03065905448718
_AVG_DEGREE = 15.57930850982666
def get_norm_layer(norm_type):
if norm_type == 'graph':
return EquivariantGraphNorm
elif norm_type == 'instance':
return EquivariantInstanceNorm
elif norm_type == 'layer':
return EquivariantLayerNormV2
elif norm_type == 'fast_layer':
return EquivariantLayerNormFast
elif norm_type is None:
return None
else:
raise ValueError('Norm type {} not supported.'.format(norm_type))
class SmoothLeakyReLU(torch.nn.Module):
def __init__(self, negative_slope=0.2):
super().__init__()
self.alpha = negative_slope
def forward(self, x):
x1 = ((1 + self.alpha) / 2) * x
x2 = ((1 - self.alpha) / 2) * x * (2 * torch.sigmoid(x) - 1)
return x1 + x2
def extra_repr(self):
return 'negative_slope={}'.format(self.alpha)
def get_mul_0(irreps):
mul_0 = 0
for mul, ir in irreps:
if ir.l == 0 and ir.p == 1:
mul_0 += mul
return mul_0
class FullyConnectedTensorProductRescaleNorm(FullyConnectedTensorProductRescale):
def __init__(self, irreps_in1, irreps_in2, irreps_out,
bias=True, rescale=True,
internal_weights=None, shared_weights=None,
normalization=None, norm_layer='graph'):
super().__init__(irreps_in1, irreps_in2, irreps_out,
bias=bias, rescale=rescale,
internal_weights=internal_weights, shared_weights=shared_weights,
normalization=normalization)
self.norm = get_norm_layer(norm_layer)(self.irreps_out)
def forward(self, x, y, batch, weight=None):
out = self.forward_tp_rescale_bias(x, y, weight)
out = self.norm(out, batch=batch)
return out
class FullyConnectedTensorProductRescaleNormSwishGate(FullyConnectedTensorProductRescaleNorm):
def __init__(self, irreps_in1, irreps_in2, irreps_out,
bias=True, rescale=True,
internal_weights=None, shared_weights=None,
normalization=None, norm_layer='graph'):
irreps_scalars, irreps_gates, irreps_gated = irreps2gate(irreps_out)
if irreps_gated.num_irreps == 0:
gate = Activation(irreps_out, acts=[torch.nn.SiLU()])
else:
gate = Gate(
irreps_scalars, [torch.nn.SiLU() for _, ir in irreps_scalars], # scalar
irreps_gates, [torch.sigmoid for _, ir in irreps_gates], # gates (scalars)
irreps_gated # gated tensors
)
super().__init__(irreps_in1, irreps_in2, gate.irreps_in,
bias=bias, rescale=rescale,
internal_weights=internal_weights, shared_weights=shared_weights,
normalization=normalization, norm_layer=norm_layer)
self.gate = gate
def forward(self, x, y, batch, weight=None):
out = self.forward_tp_rescale_bias(x, y, weight)
out = self.norm(out, batch=batch)
out = self.gate(out)
return out
class FullyConnectedTensorProductRescaleSwishGate(FullyConnectedTensorProductRescale):
def __init__(self, irreps_in1, irreps_in2, irreps_out,
bias=True, rescale=True,
internal_weights=None, shared_weights=None,
normalization=None):
irreps_scalars, irreps_gates, irreps_gated = irreps2gate(irreps_out)
if irreps_gated.num_irreps == 0:
gate = Activation(irreps_out, acts=[torch.nn.SiLU()])
else:
gate = Gate(
irreps_scalars, [torch.nn.SiLU() for _, ir in irreps_scalars], # scalar
irreps_gates, [torch.sigmoid for _, ir in irreps_gates], # gates (scalars)
irreps_gated # gated tensors
)
super().__init__(irreps_in1, irreps_in2, gate.irreps_in,
bias=bias, rescale=rescale,
internal_weights=internal_weights, shared_weights=shared_weights,
normalization=normalization)
self.gate = gate
def forward(self, x, y, weight=None):
out = self.forward_tp_rescale_bias(x, y, weight)
out = self.gate(out)
return out
def DepthwiseTensorProduct(irreps_node_input, irreps_edge_attr, irreps_node_output,
internal_weights=False, bias=True):
'''
The irreps of output is pre-determined.
`irreps_node_output` is used to get certain types of vectors.
'''
irreps_output = []
instructions = []
for i, (mul, ir_in) in enumerate(irreps_node_input):
for j, (_, ir_edge) in enumerate(irreps_edge_attr):
for ir_out in ir_in * ir_edge:
if ir_out in irreps_node_output or ir_out == o3.Irrep(0, 1):
k = len(irreps_output)
irreps_output.append((mul, ir_out))
instructions.append((i, j, k, 'uvu', True))
irreps_output = o3.Irreps(irreps_output)
irreps_output, p, _ = sort_irreps_even_first(irreps_output) #irreps_output.sort()
instructions = [(i_1, i_2, p[i_out], mode, train)
for i_1, i_2, i_out, mode, train in instructions]
tp = TensorProductRescale(irreps_node_input, irreps_edge_attr,
irreps_output, instructions,
internal_weights=internal_weights,
shared_weights=internal_weights,
bias=bias, rescale=_RESCALE)
return tp
class SeparableFCTP(torch.nn.Module):
'''
Use separable FCTP for spatial convolution.
'''
def __init__(self, irreps_node_input, irreps_edge_attr, irreps_node_output,
fc_neurons, use_activation=False, norm_layer='graph',
internal_weights=False):
super().__init__()
self.irreps_node_input = o3.Irreps(irreps_node_input)
self.irreps_edge_attr = o3.Irreps(irreps_edge_attr)
self.irreps_node_output = o3.Irreps(irreps_node_output)
norm = get_norm_layer(norm_layer)
self.dtp = DepthwiseTensorProduct(self.irreps_node_input, self.irreps_edge_attr,
self.irreps_node_output, bias=False, internal_weights=internal_weights)
self.dtp_rad = None
if fc_neurons is not None:
self.dtp_rad = RadialProfile(fc_neurons + [self.dtp.tp.weight_numel])
for (slice, slice_sqrt_k) in self.dtp.slices_sqrt_k.values():
self.dtp_rad.net[-1].weight.data[slice, :] *= slice_sqrt_k
self.dtp_rad.offset.data[slice] *= slice_sqrt_k
irreps_lin_output = self.irreps_node_output
irreps_scalars, irreps_gates, irreps_gated = irreps2gate(self.irreps_node_output)
if use_activation:
irreps_lin_output = irreps_scalars + irreps_gates + irreps_gated
irreps_lin_output = irreps_lin_output.simplify()
self.lin = LinearRS(self.dtp.irreps_out.simplify(), irreps_lin_output)
self.norm = None
if norm_layer is not None:
self.norm = norm(self.lin.irreps_out)
self.gate = None
if use_activation:
if irreps_gated.num_irreps == 0:
gate = Activation(self.irreps_node_output, acts=[torch.nn.SiLU()])
else:
gate = Gate(
irreps_scalars, [torch.nn.SiLU() for _, ir in irreps_scalars], # scalar
irreps_gates, [torch.sigmoid for _, ir in irreps_gates], # gates (scalars)
irreps_gated # gated tensors
)
self.gate = gate
def forward(self, node_input, edge_attr, edge_scalars, batch=None, **kwargs):
'''
Depthwise TP: `node_input` TP `edge_attr`, with TP parametrized by
self.dtp_rad(`edge_scalars`).
'''
weight = None
if self.dtp_rad is not None and edge_scalars is not None:
weight = self.dtp_rad(edge_scalars)
out = self.dtp(node_input, edge_attr, weight)
out = self.lin(out)
if self.norm is not None:
out = self.norm(out, batch=batch)
if self.gate is not None:
out = self.gate(out)
return out
@compile_mode('script')
class Vec2AttnHeads(torch.nn.Module):
'''
Reshape vectors of shape [N, irreps_mid] to vectors of shape
[N, num_heads, irreps_head].
'''
def __init__(self, irreps_head, num_heads):
super().__init__()
self.num_heads = num_heads
self.irreps_head = irreps_head
self.irreps_mid_in = []
for mul, ir in irreps_head:
self.irreps_mid_in.append((mul * num_heads, ir))
self.irreps_mid_in = o3.Irreps(self.irreps_mid_in)
self.mid_in_indices = []
start_idx = 0
for mul, ir in self.irreps_mid_in:
self.mid_in_indices.append((start_idx, start_idx + mul * ir.dim))
start_idx = start_idx + mul * ir.dim
def forward(self, x):
N, _ = x.shape
out = []
for ir_idx, (start_idx, end_idx) in enumerate(self.mid_in_indices):
temp = x.narrow(1, start_idx, end_idx - start_idx)
temp = temp.reshape(N, self.num_heads, -1)
out.append(temp)
out = torch.cat(out, dim=2)
return out
def __repr__(self):
return '{}(irreps_head={}, num_heads={})'.format(
self.__class__.__name__, self.irreps_head, self.num_heads)
@compile_mode('script')
class AttnHeads2Vec(torch.nn.Module):
'''
Convert vectors of shape [N, num_heads, irreps_head] into
vectors of shape [N, irreps_head * num_heads].
'''
def __init__(self, irreps_head):
super().__init__()
self.irreps_head = irreps_head
self.head_indices = []
start_idx = 0
for mul, ir in self.irreps_head:
self.head_indices.append((start_idx, start_idx + mul * ir.dim))
start_idx = start_idx + mul * ir.dim
def forward(self, x):
N, _, _ = x.shape
out = []
for ir_idx, (start_idx, end_idx) in enumerate(self.head_indices):
temp = x.narrow(2, start_idx, end_idx - start_idx)
temp = temp.reshape(N, -1)
out.append(temp)
out = torch.cat(out, dim=1)
return out
def __repr__(self):
return '{}(irreps_head={})'.format(self.__class__.__name__, self.irreps_head)
class ConcatIrrepsTensor(torch.nn.Module):
def __init__(self, irreps_1, irreps_2):
super().__init__()
assert irreps_1 == irreps_1.simplify()
self.check_sorted(irreps_1)
assert irreps_2 == irreps_2.simplify()
self.check_sorted(irreps_2)
self.irreps_1 = irreps_1
self.irreps_2 = irreps_2
self.irreps_out = irreps_1 + irreps_2
self.irreps_out, _, _ = sort_irreps_even_first(self.irreps_out) #self.irreps_out.sort()
self.irreps_out = self.irreps_out.simplify()
self.ir_mul_list = []
lmax = max(irreps_1.lmax, irreps_2.lmax)
irreps_max = []
for i in range(lmax + 1):
irreps_max.append((1, (i, -1)))
irreps_max.append((1, (i, 1)))
irreps_max = o3.Irreps(irreps_max)
start_idx_1, start_idx_2 = 0, 0
dim_1_list, dim_2_list = self.get_irreps_dim(irreps_1), self.get_irreps_dim(irreps_2)
for _, ir in irreps_max:
dim_1, dim_2 = None, None
index_1 = self.get_ir_index(ir, irreps_1)
index_2 = self.get_ir_index(ir, irreps_2)
if index_1 != -1:
dim_1 = dim_1_list[index_1]
if index_2 != -1:
dim_2 = dim_2_list[index_2]
self.ir_mul_list.append((start_idx_1, dim_1, start_idx_2, dim_2))
start_idx_1 = start_idx_1 + dim_1 if dim_1 is not None else start_idx_1
start_idx_2 = start_idx_2 + dim_2 if dim_2 is not None else start_idx_2
def get_irreps_dim(self, irreps):
muls = []
for mul, ir in irreps:
muls.append(mul * ir.dim)
return muls
def check_sorted(self, irreps):
lmax = None
p = None
for _, ir in irreps:
if p is None and lmax is None:
p = ir.p
lmax = ir.l
continue
if ir.l == lmax:
assert p < ir.p, 'Parity order error: {}'.format(irreps)
assert lmax <= ir.l
def get_ir_index(self, ir, irreps):
for index, (_, irrep) in enumerate(irreps):
if irrep == ir:
return index
return -1
def forward(self, feature_1, feature_2):
output = []
for i in range(len(self.ir_mul_list)):
start_idx_1, mul_1, start_idx_2, mul_2 = self.ir_mul_list[i]
if mul_1 is not None:
output.append(feature_1.narrow(-1, start_idx_1, mul_1))
if mul_2 is not None:
output.append(feature_2.narrow(-1, start_idx_2, mul_2))
output = torch.cat(output, dim=-1)
return output
def __repr__(self):
return '{}(irreps_1={}, irreps_2={})'.format(self.__class__.__name__,
self.irreps_1, self.irreps_2)
@compile_mode('script')
class GraphAttention(torch.nn.Module):
'''
1. Message = Alpha * Value
2. Two Linear to merge src and dst -> Separable FCTP -> 0e + (0e+1e+...)
3. 0e -> Activation -> Inner Product -> (Alpha)
4. (0e+1e+...) -> (Value)
'''
def __init__(self,
irreps_node_input, irreps_node_attr,
irreps_edge_attr, irreps_node_output,
fc_neurons,
irreps_head, num_heads, irreps_pre_attn=None,
rescale_degree=False, nonlinear_message=False,
alpha_drop=0.1, proj_drop=0.1):
super().__init__()
self.irreps_node_input = o3.Irreps(irreps_node_input)
self.irreps_node_attr = o3.Irreps(irreps_node_attr)
self.irreps_edge_attr = o3.Irreps(irreps_edge_attr)
self.irreps_node_output = o3.Irreps(irreps_node_output)
self.irreps_pre_attn = self.irreps_node_input if irreps_pre_attn is None \
else o3.Irreps(irreps_pre_attn)
self.irreps_head = o3.Irreps(irreps_head)
self.num_heads = num_heads
self.rescale_degree = rescale_degree
self.nonlinear_message = nonlinear_message
# Merge src and dst
self.merge_src = LinearRS(self.irreps_node_input, self.irreps_pre_attn, bias=True)
self.merge_dst = LinearRS(self.irreps_node_input, self.irreps_pre_attn, bias=False)
irreps_attn_heads = irreps_head * num_heads
irreps_attn_heads, _, _ = sort_irreps_even_first(irreps_attn_heads) #irreps_attn_heads.sort()
irreps_attn_heads = irreps_attn_heads.simplify()
mul_alpha = get_mul_0(irreps_attn_heads)
mul_alpha_head = mul_alpha // num_heads
irreps_alpha = o3.Irreps('{}x0e'.format(mul_alpha)) # for attention score
irreps_attn_all = (irreps_alpha + irreps_attn_heads).simplify()
self.sep_act = None
if self.nonlinear_message:
# Use an extra separable FCTP and Swish Gate for value
self.sep_act = SeparableFCTP(self.irreps_pre_attn,
self.irreps_edge_attr, self.irreps_pre_attn, fc_neurons,
use_activation=True, norm_layer=None, internal_weights=False)
self.sep_alpha = LinearRS(self.sep_act.dtp.irreps_out, irreps_alpha)
self.sep_value = SeparableFCTP(self.irreps_pre_attn,
self.irreps_edge_attr, irreps_attn_heads, fc_neurons=None,
use_activation=False, norm_layer=None, internal_weights=True)
self.vec2heads_alpha = Vec2AttnHeads(o3.Irreps('{}x0e'.format(mul_alpha_head)),
num_heads)
self.vec2heads_value = Vec2AttnHeads(self.irreps_head, num_heads)
else:
self.sep = SeparableFCTP(self.irreps_pre_attn,
self.irreps_edge_attr, irreps_attn_all, fc_neurons,
use_activation=False, norm_layer=None)
self.vec2heads = Vec2AttnHeads(
(o3.Irreps('{}x0e'.format(mul_alpha_head)) + irreps_head).simplify(),
num_heads)
self.alpha_act = Activation(o3.Irreps('{}x0e'.format(mul_alpha_head)),
[SmoothLeakyReLU(0.2)])
self.heads2vec = AttnHeads2Vec(irreps_head)
self.mul_alpha_head = mul_alpha_head
self.alpha_dot = torch.nn.Parameter(torch.randn(1, num_heads, mul_alpha_head))
torch_geometric.nn.inits.glorot(self.alpha_dot) # Following GATv2
self.alpha_dropout = None
if alpha_drop != 0.0:
self.alpha_dropout = torch.nn.Dropout(alpha_drop)
self.proj = LinearRS(irreps_attn_heads, self.irreps_node_output)
self.proj_drop = None
if proj_drop != 0.0:
self.proj_drop = EquivariantDropout(self.irreps_node_input,
drop_prob=proj_drop)
def forward(self, node_input, node_attr, edge_src, edge_dst, edge_attr, edge_scalars,
batch, **kwargs):
message_src = self.merge_src(node_input)
message_dst = self.merge_dst(node_input)
message = message_src[edge_src] + message_dst[edge_dst]
if self.nonlinear_message:
weight = self.sep_act.dtp_rad(edge_scalars)
message = self.sep_act.dtp(message, edge_attr, weight)
alpha = self.sep_alpha(message)
alpha = self.vec2heads_alpha(alpha)
value = self.sep_act.lin(message)
value = self.sep_act.gate(value)
value = self.sep_value(value, edge_attr=edge_attr, edge_scalars=edge_scalars)
value = self.vec2heads_value(value)
else:
message = self.sep(message, edge_attr=edge_attr, edge_scalars=edge_scalars)
message = self.vec2heads(message)
head_dim_size = message.shape[-1]
alpha = message.narrow(2, 0, self.mul_alpha_head)
value = message.narrow(2, self.mul_alpha_head, (head_dim_size - self.mul_alpha_head))
# inner product
alpha = self.alpha_act(alpha)
alpha = torch.einsum('bik, aik -> bi', alpha, self.alpha_dot)
alpha = torch_geometric.utils.softmax(alpha, edge_dst)
alpha = alpha.unsqueeze(-1)
if self.alpha_dropout is not None:
alpha = self.alpha_dropout(alpha)
attn = value * alpha
attn = scatter(attn, index=edge_dst, dim=0, dim_size=node_input.shape[0])
attn = self.heads2vec(attn)
if self.rescale_degree:
degree = torch_geometric.utils.degree(edge_dst,
num_nodes=node_input.shape[0], dtype=node_input.dtype)
degree = degree.view(-1, 1)
attn = attn * degree
node_output = self.proj(attn)
if self.proj_drop is not None:
node_output = self.proj_drop(node_output)
return node_output
def extra_repr(self):
output_str = super(GraphAttention, self).extra_repr()
output_str = output_str + 'rescale_degree={}, '.format(self.rescale_degree)
return output_str
@compile_mode('script')
class FeedForwardNetwork(torch.nn.Module):
'''
Use two (FCTP + Gate)
'''
def __init__(self,
irreps_node_input, irreps_node_attr,
irreps_node_output, irreps_mlp_mid=None,
proj_drop=0.1):
super().__init__()
self.irreps_node_input = o3.Irreps(irreps_node_input)
self.irreps_node_attr = o3.Irreps(irreps_node_attr)
self.irreps_mlp_mid = o3.Irreps(irreps_mlp_mid) if irreps_mlp_mid is not None \
else self.irreps_node_input
self.irreps_node_output = o3.Irreps(irreps_node_output)
self.fctp_1 = FullyConnectedTensorProductRescaleSwishGate(
self.irreps_node_input, self.irreps_node_attr, self.irreps_mlp_mid,
bias=True, rescale=_RESCALE)
self.fctp_2 = FullyConnectedTensorProductRescale(
self.irreps_mlp_mid, self.irreps_node_attr, self.irreps_node_output,
bias=True, rescale=_RESCALE)
self.proj_drop = None
if proj_drop != 0.0:
self.proj_drop = EquivariantDropout(self.irreps_node_output,
drop_prob=proj_drop)
def forward(self, node_input, node_attr, **kwargs):
node_output = self.fctp_1(node_input, node_attr)
node_output = self.fctp_2(node_output, node_attr)
if self.proj_drop is not None:
node_output = self.proj_drop(node_output)
return node_output
@compile_mode('script')
class TransBlock(torch.nn.Module):
'''
1. Layer Norm 1 -> GraphAttention -> Layer Norm 2 -> FeedForwardNetwork
2. Use pre-norm architecture
'''
def __init__(self,
irreps_node_input, irreps_node_attr,
irreps_edge_attr, irreps_node_output,
fc_neurons,
irreps_head, num_heads, irreps_pre_attn=None,
rescale_degree=False, nonlinear_message=False,
alpha_drop=0.1, proj_drop=0.1,
drop_path_rate=0.0,
irreps_mlp_mid=None,
norm_layer='layer'):
super().__init__()
self.irreps_node_input = o3.Irreps(irreps_node_input)
self.irreps_node_attr = o3.Irreps(irreps_node_attr)
self.irreps_edge_attr = o3.Irreps(irreps_edge_attr)
self.irreps_node_output = o3.Irreps(irreps_node_output)
self.irreps_pre_attn = self.irreps_node_input if irreps_pre_attn is None \
else o3.Irreps(irreps_pre_attn)
self.irreps_head = o3.Irreps(irreps_head)
self.num_heads = num_heads
self.rescale_degree = rescale_degree
self.nonlinear_message = nonlinear_message
self.irreps_mlp_mid = o3.Irreps(irreps_mlp_mid) if irreps_mlp_mid is not None \
else self.irreps_node_input
self.norm_1 = get_norm_layer(norm_layer)(self.irreps_node_input)
self.ga = GraphAttention(irreps_node_input=self.irreps_node_input,
irreps_node_attr=self.irreps_node_attr,
irreps_edge_attr=self.irreps_edge_attr,
irreps_node_output=self.irreps_node_input,
fc_neurons=fc_neurons,
irreps_head=self.irreps_head,
num_heads=self.num_heads,
irreps_pre_attn=self.irreps_pre_attn,
rescale_degree=self.rescale_degree,
nonlinear_message=self.nonlinear_message,
alpha_drop=alpha_drop,
proj_drop=proj_drop)
self.drop_path = GraphDropPath(drop_path_rate) if drop_path_rate > 0. else None
self.norm_2 = get_norm_layer(norm_layer)(self.irreps_node_input)
#self.concat_norm_output = ConcatIrrepsTensor(self.irreps_node_input,
# self.irreps_node_input)
self.ffn = FeedForwardNetwork(
irreps_node_input=self.irreps_node_input, #self.concat_norm_output.irreps_out,
irreps_node_attr=self.irreps_node_attr,
irreps_node_output=self.irreps_node_output,
irreps_mlp_mid=self.irreps_mlp_mid,
proj_drop=proj_drop)
self.ffn_shortcut = None
if self.irreps_node_input != self.irreps_node_output:
self.ffn_shortcut = FullyConnectedTensorProductRescale(
self.irreps_node_input, self.irreps_node_attr,
self.irreps_node_output,
bias=True, rescale=_RESCALE)
def forward(self, node_input, node_attr, edge_src, edge_dst, edge_attr, edge_scalars,
batch, **kwargs):
node_output = node_input
node_features = node_input
node_features = self.norm_1(node_features, batch=batch)
#norm_1_output = node_features
node_features = self.ga(node_input=node_features,
node_attr=node_attr,
edge_src=edge_src, edge_dst=edge_dst,
edge_attr=edge_attr, edge_scalars=edge_scalars,
batch=batch)
if self.drop_path is not None:
node_features = self.drop_path(node_features, batch)
node_output = node_output + node_features
node_features = node_output
node_features = self.norm_2(node_features, batch=batch)
#node_features = self.concat_norm_output(norm_1_output, node_features)
node_features = self.ffn(node_features, node_attr)
if self.ffn_shortcut is not None:
node_output = self.ffn_shortcut(node_output, node_attr)
if self.drop_path is not None:
node_features = self.drop_path(node_features, batch)
node_output = node_output + node_features
return node_output
class NodeEmbeddingNetwork(torch.nn.Module):
def __init__(self, irreps_node_embedding, max_atom_type=_MAX_ATOM_TYPE, bias=True):
super().__init__()
self.max_atom_type = max_atom_type
self.irreps_node_embedding = o3.Irreps(irreps_node_embedding)
self.atom_type_lin = LinearRS(o3.Irreps('{}x0e'.format(self.max_atom_type)),
self.irreps_node_embedding, bias=bias)
self.atom_type_lin.tp.weight.data.mul_(self.max_atom_type ** 0.5)
def forward(self, node_atom):
'''
`node_atom` is a LongTensor.
'''
node_atom_onehot = torch.nn.functional.one_hot(node_atom, self.max_atom_type).float()
node_attr = node_atom_onehot
node_embedding = self.atom_type_lin(node_atom_onehot)
return node_embedding, node_attr, node_atom_onehot
class ScaledScatter(torch.nn.Module):
def __init__(self, avg_aggregate_num):
super().__init__()
self.avg_aggregate_num = avg_aggregate_num + 0.0
def forward(self, x, index, **kwargs):
out = scatter(x, index, **kwargs)
out = out.div(self.avg_aggregate_num ** 0.5)
return out
def extra_repr(self):
return 'avg_aggregate_num={}'.format(self.avg_aggregate_num)
class EdgeDegreeEmbeddingNetwork(torch.nn.Module):
def __init__(self, irreps_node_embedding, irreps_edge_attr, fc_neurons, avg_aggregate_num):
super().__init__()
self.exp = LinearRS(o3.Irreps('1x0e'), irreps_node_embedding,
bias=_USE_BIAS, rescale=_RESCALE)
self.dw = DepthwiseTensorProduct(irreps_node_embedding,
irreps_edge_attr, irreps_node_embedding,
internal_weights=False, bias=False)
self.rad = RadialProfile(fc_neurons + [self.dw.tp.weight_numel])
for (slice, slice_sqrt_k) in self.dw.slices_sqrt_k.values():
self.rad.net[-1].weight.data[slice, :] *= slice_sqrt_k
self.rad.offset.data[slice] *= slice_sqrt_k
self.proj = LinearRS(self.dw.irreps_out.simplify(), irreps_node_embedding)
self.scale_scatter = ScaledScatter(avg_aggregate_num)
def forward(self, node_input, edge_attr, edge_scalars, edge_src, edge_dst, batch):
node_features = torch.ones_like(node_input.narrow(1, 0, 1))
node_features = self.exp(node_features)
weight = self.rad(edge_scalars)
edge_features = self.dw(node_features[edge_src], edge_attr, weight)
edge_features = self.proj(edge_features)
node_features = self.scale_scatter(edge_features, edge_dst, dim=0,
dim_size=node_features.shape[0])
return node_features
class GraphAttentionTransformer(torch.nn.Module):
def __init__(self,
irreps_in='5x0e',
irreps_node_embedding='128x0e+64x1e+32x2e', num_layers=6,
irreps_node_attr='1x0e', irreps_sh='1x0e+1x1e+1x2e',
max_radius=5.0,
number_of_basis=128, basis_type='gaussian', fc_neurons=[64, 64],
irreps_feature='512x0e',
irreps_head='32x0e+16x1o+8x2e', num_heads=4, irreps_pre_attn=None,
rescale_degree=False, nonlinear_message=False,
irreps_mlp_mid='128x0e+64x1e+32x2e',
norm_layer='layer',
alpha_drop=0.2, proj_drop=0.0, out_drop=0.0,
drop_path_rate=0.0,
mean=None, std=None, scale=None, atomref=None):
super().__init__()
self.max_radius = max_radius
self.number_of_basis = number_of_basis
self.alpha_drop = alpha_drop
self.proj_drop = proj_drop
self.out_drop = out_drop
self.drop_path_rate = drop_path_rate
self.norm_layer = norm_layer
self.task_mean = mean
self.task_std = std
self.scale = scale
self.register_buffer('atomref', atomref)
self.irreps_node_attr = o3.Irreps(irreps_node_attr)
self.irreps_node_input = o3.Irreps(irreps_in)
self.irreps_node_embedding = o3.Irreps(irreps_node_embedding)
self.lmax = self.irreps_node_embedding.lmax
self.irreps_feature = o3.Irreps(irreps_feature)
self.num_layers = num_layers
self.irreps_edge_attr = o3.Irreps(irreps_sh) if irreps_sh is not None \
else o3.Irreps.spherical_harmonics(self.lmax)
self.fc_neurons = [self.number_of_basis] + fc_neurons
self.irreps_head = o3.Irreps(irreps_head)
self.num_heads = num_heads
self.irreps_pre_attn = irreps_pre_attn
self.rescale_degree = rescale_degree
self.nonlinear_message = nonlinear_message
self.irreps_mlp_mid = o3.Irreps(irreps_mlp_mid)
self.atom_embed = NodeEmbeddingNetwork(self.irreps_node_embedding, _MAX_ATOM_TYPE)
self.basis_type = basis_type
if self.basis_type == 'gaussian':
self.rbf = GaussianRadialBasisLayer(self.number_of_basis, cutoff=self.max_radius)
elif self.basis_type == 'bessel':
self.rbf = RadialBasis(self.number_of_basis, cutoff=self.max_radius,
rbf={'name': 'spherical_bessel'})
else:
raise ValueError
self.edge_deg_embed = EdgeDegreeEmbeddingNetwork(self.irreps_node_embedding,
self.irreps_edge_attr, self.fc_neurons, _AVG_DEGREE)
self.blocks = torch.nn.ModuleList()
self.build_blocks()
self.norm = get_norm_layer(self.norm_layer)(self.irreps_feature)
self.out_dropout = None
if self.out_drop != 0.0:
self.out_dropout = EquivariantDropout(self.irreps_feature, self.out_drop)
self.head = torch.nn.Sequential(
LinearRS(self.irreps_feature, self.irreps_feature, rescale=_RESCALE),
Activation(self.irreps_feature, acts=[torch.nn.SiLU()]),
LinearRS(self.irreps_feature, o3.Irreps('1x0e'), rescale=_RESCALE))
self.scale_scatter = ScaledScatter(_AVG_NUM_NODES)
self.apply(self._init_weights)
def build_blocks(self):
for i in range(self.num_layers):
if i != (self.num_layers - 1):
irreps_block_output = self.irreps_node_embedding
else:
irreps_block_output = self.irreps_feature
blk = TransBlock(irreps_node_input=self.irreps_node_embedding,
irreps_node_attr=self.irreps_node_attr,
irreps_edge_attr=self.irreps_edge_attr,
irreps_node_output=irreps_block_output,
fc_neurons=self.fc_neurons,
irreps_head=self.irreps_head,
num_heads=self.num_heads,
irreps_pre_attn=self.irreps_pre_attn,
rescale_degree=self.rescale_degree,
nonlinear_message=self.nonlinear_message,
alpha_drop=self.alpha_drop,
proj_drop=self.proj_drop,
drop_path_rate=self.drop_path_rate,
irreps_mlp_mid=self.irreps_mlp_mid,
norm_layer=self.norm_layer)
self.blocks.append(blk)
def _init_weights(self, m):
if isinstance(m, torch.nn.Linear):
if m.bias is not None:
torch.nn.init.constant_(m.bias, 0)
elif isinstance(m, torch.nn.LayerNorm):
torch.nn.init.constant_(m.bias, 0)
torch.nn.init.constant_(m.weight, 1.0)
@torch.jit.ignore
def no_weight_decay(self):
no_wd_list = []
named_parameters_list = [name for name, _ in self.named_parameters()]
for module_name, module in self.named_modules():
if (isinstance(module, torch.nn.Linear)
or isinstance(module, torch.nn.LayerNorm)
or isinstance(module, EquivariantLayerNormV2)
or isinstance(module, EquivariantInstanceNorm)
or isinstance(module, EquivariantGraphNorm)
or isinstance(module, GaussianRadialBasisLayer)
or isinstance(module, RadialBasis)):
for parameter_name, _ in module.named_parameters():
if isinstance(module, torch.nn.Linear) and 'weight' in parameter_name:
continue
global_parameter_name = module_name + '.' + parameter_name
assert global_parameter_name in named_parameters_list
no_wd_list.append(global_parameter_name)
return set(no_wd_list)
def forward(self, f_in, pos, batch, node_atom, **kwargs) -> torch.Tensor:
edge_src, edge_dst = radius_graph(pos, r=self.max_radius, batch=batch,
max_num_neighbors=1000)
edge_vec = pos.index_select(0, edge_src) - pos.index_select(0, edge_dst)
edge_sh = o3.spherical_harmonics(l=self.irreps_edge_attr,
x=edge_vec, normalize=True, normalization='component')
node_atom = node_atom.new_tensor([-1, 0, -1, -1, -1, -1, 1, 2, 3, 4])[node_atom]
atom_embedding, atom_attr, atom_onehot = self.atom_embed(node_atom)
edge_length = edge_vec.norm(dim=1)
#edge_length_embedding = sin_pos_embedding(x=edge_length,
# start=0.0, end=self.max_radius, number=self.number_of_basis,
# cutoff=False)
edge_length_embedding = self.rbf(edge_length)
edge_degree_embedding = self.edge_deg_embed(atom_embedding, edge_sh,
edge_length_embedding, edge_src, edge_dst, batch)
node_features = atom_embedding + edge_degree_embedding
node_attr = torch.ones_like(node_features.narrow(1, 0, 1))
for blk in self.blocks:
node_features = blk(node_input=node_features, node_attr=node_attr,
edge_src=edge_src, edge_dst=edge_dst, edge_attr=edge_sh,
edge_scalars=edge_length_embedding,
batch=batch)
node_features = self.norm(node_features, batch=batch)
if self.out_dropout is not None:
node_features = self.out_dropout(node_features)
outputs = self.head(node_features)
outputs = self.scale_scatter(outputs, batch, dim=0)
if self.scale is not None:
outputs = self.scale * outputs
return outputs
@register_model
def graph_attention_transformer_l2(irreps_in, radius, num_basis=128,
atomref=None, task_mean=None, task_std=None, **kwargs):
model = GraphAttentionTransformer(
irreps_in=irreps_in,
irreps_node_embedding='128x0e+64x1e+32x2e', num_layers=6,
irreps_node_attr='1x0e', irreps_sh='1x0e+1x1e+1x2e',
max_radius=radius,
number_of_basis=num_basis, fc_neurons=[64, 64],
irreps_feature='512x0e',
irreps_head='32x0e+16x1e+8x2e', num_heads=4, irreps_pre_attn=None,
rescale_degree=False, nonlinear_message=False,
irreps_mlp_mid='384x0e+192x1e+96x2e',
norm_layer='layer',
alpha_drop=0.2, proj_drop=0.0, out_drop=0.0, drop_path_rate=0.0,
mean=task_mean, std=task_std, scale=None, atomref=atomref)
return model
@register_model
def graph_attention_transformer_nonlinear_l2(irreps_in, radius, num_basis=128,
atomref=None, task_mean=None, task_std=None, **kwargs):
model = GraphAttentionTransformer(
irreps_in=irreps_in,
irreps_node_embedding='128x0e+64x1e+32x2e', num_layers=6,
irreps_node_attr='1x0e', irreps_sh='1x0e+1x1e+1x2e',
max_radius=radius,
number_of_basis=num_basis, fc_neurons=[64, 64],
irreps_feature='512x0e',
irreps_head='32x0e+16x1e+8x2e', num_heads=4, irreps_pre_attn=None,
rescale_degree=False, nonlinear_message=True,
irreps_mlp_mid='384x0e+192x1e+96x2e',
norm_layer='layer',
alpha_drop=0.2, proj_drop=0.0, out_drop=0.0, drop_path_rate=0.0,
mean=task_mean, std=task_std, scale=None, atomref=atomref)
return model
@register_model
def graph_attention_transformer_nonlinear_l2_e3(irreps_in, radius, num_basis=128,
atomref=None, task_mean=None, task_std=None, **kwargs):
model = GraphAttentionTransformer(
irreps_in=irreps_in,
irreps_node_embedding='128x0e+32x0o+32x1e+32x1o+16x2e+16x2o', num_layers=6,
irreps_node_attr='1x0e', irreps_sh='1x0e+1x1o+1x2e',
max_radius=radius,
number_of_basis=num_basis, fc_neurons=[64, 64],
irreps_feature='512x0e',
irreps_head='32x0e+8x0o+8x1e+8x1o+4x2e+4x2o', num_heads=4, irreps_pre_attn=None,
rescale_degree=False, nonlinear_message=True,
irreps_mlp_mid='384x0e+96x0o+96x1e+96x1o+48x2e+48x2o',
norm_layer='layer',
alpha_drop=0.2, proj_drop=0.0, out_drop=0.0, drop_path_rate=0.0,
mean=task_mean, std=task_std, scale=None, atomref=atomref)
return model
# Equiformer, L_max = 2, Bessel radial basis, dropout = 0.2
@register_model
def graph_attention_transformer_nonlinear_bessel_l2(irreps_in, radius, num_basis=128,
atomref=None, task_mean=None, task_std=None, **kwargs):
model = GraphAttentionTransformer(
irreps_in=irreps_in,
irreps_node_embedding='128x0e+64x1e+32x2e', num_layers=6,
irreps_node_attr='1x0e', irreps_sh='1x0e+1x1e+1x2e',
max_radius=radius,
number_of_basis=num_basis, fc_neurons=[64, 64], basis_type='bessel',
irreps_feature='512x0e',
irreps_head='32x0e+16x1e+8x2e', num_heads=4, irreps_pre_attn=None,
rescale_degree=False, nonlinear_message=True,
irreps_mlp_mid='384x0e+192x1e+96x2e',
norm_layer='layer',
alpha_drop=0.2, proj_drop=0.0, out_drop=0.0, drop_path_rate=0.0,
mean=task_mean, std=task_std, scale=None, atomref=atomref)
return model
# Equiformer, L_max = 2, Bessel radial basis, dropout = 0.1
@register_model
def graph_attention_transformer_nonlinear_bessel_l2_drop01(irreps_in, radius, num_basis=128,
atomref=None, task_mean=None, task_std=None, **kwargs):
model = GraphAttentionTransformer(
irreps_in=irreps_in,
irreps_node_embedding='128x0e+64x1e+32x2e', num_layers=6,
irreps_node_attr='1x0e', irreps_sh='1x0e+1x1e+1x2e',
max_radius=radius,
number_of_basis=num_basis, fc_neurons=[64, 64], basis_type='bessel',
irreps_feature='512x0e',
irreps_head='32x0e+16x1e+8x2e', num_heads=4, irreps_pre_attn=None,
rescale_degree=False, nonlinear_message=True,
irreps_mlp_mid='384x0e+192x1e+96x2e',
norm_layer='layer',
alpha_drop=0.1, proj_drop=0.0, out_drop=0.0, drop_path_rate=0.0,
mean=task_mean, std=task_std, scale=None, atomref=atomref)
return model
# Equiformer, L_max = 2, Bessel radial basis, dropout = 0.0
@register_model