-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlayer.py
More file actions
2737 lines (2329 loc) · 111 KB
/
layer.py
File metadata and controls
2737 lines (2329 loc) · 111 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
from typing import List, Optional, Any, Callable, Tuple, Union
from contextlib import nullcontext
from abc import ABC, abstractmethod
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import GATConv, TransformerConv
from parms_setting import settings
from utils import (
em_path,
maybe_rand_init_like,
clamp_features,
step_update,
project_to_ball,
reset_parameters,
AvgReadout,
random_permute_features,
add_noise,
attribute_mask,
noise_then_mask,
apply_augmentation,
)
# 全局参数 - 延迟初始化,避免在导入时解析命令行参数
args = None
def get_args():
"""获取全局参数,延迟初始化"""
global args
if args is None:
args = settings()
return args
# =================================================
# 编码器:gat_gt_serial(底层组件)
# =================================================
class GATGTSerial(nn.Module):
"""
先 GATConv 再 TransformerConv 的串联编码器
该类实现了一个两层的图神经网络编码器,首先使用GATConv层进行节点特征提取,
然后通过TransformerConv层进一步编码,实现图结构数据的表示学习。
"""
def __init__(self, in_dim: int, hidden1: int, hidden2: int, dropout: float, gat_heads: int = 4):
"""
初始化GATGTSerial编码器
Args:
in_dim (int): 输入特征维度
hidden1 (int): 第一层GATConv的隐藏层维度
hidden2 (int): 第二层TransformerConv的输出维度
dropout (float): Dropout概率
gat_heads (int, optional): GATConv层的注意力头数,默认为4
"""
super().__init__()
self.gat1 = GATConv(in_channels=in_dim, out_channels=hidden1, heads=gat_heads, concat=True, dropout=dropout)
self.prelu_g1 = nn.PReLU(hidden1 * gat_heads)
self.gt2 = TransformerConv(in_channels=hidden1 * gat_heads, out_channels=hidden2, heads=1, concat=False, dropout=dropout)
self.prelu_t2 = nn.PReLU(hidden2)
self.dropout = dropout
def encode(self, x: torch.Tensor, edge_index: torch.Tensor) -> torch.Tensor:
"""
对图节点进行编码
节点级编码:GAT -> Dropout -> Transformer -> PReLU
Args:
x (torch.Tensor): 节点特征矩阵,形状为 [num_nodes, in_dim]
edge_index (torch.Tensor): 图的边索引矩阵,形状为 [2, num_edges]
Returns:
torch.Tensor: 编码后的节点表示,形状为 [num_nodes, hidden2]
"""
x1 = self.prelu_g1(self.gat1(x, edge_index))
x1 = F.dropout(x1, self.dropout, training=self.training)
x2 = self.gt2(x1, edge_index)
x2 = self.prelu_t2(x2)
return x2
# =================================================
# 融合策略抽象基类
# =================================================
class FusionStrategy(nn.Module, ABC):
"""
融合策略抽象基类,支持热插拔
定义了融合策略的接口,所有具体的融合策略都需要继承此类并实现forward方法
"""
def __init__(self):
super().__init__()
@abstractmethod
def forward(self, *args, **kwargs) -> torch.Tensor:
"""
抽象前向传播方法,由子类具体实现
Returns:
torch.Tensor: 融合后的特征表示
"""
pass
# =================================================
# 协作注意力组件
# =================================================
class PairwiseCoAttention(nn.Module):
"""
成对协同注意力模块
实现两个输入张量A和B之间的双向注意力机制,其中A关注B,B也关注A。
每个方向都使用查询、键和值的线性变换,并应用注意力权重来聚合信息。
Args:
dim (int): 输入特征维度
hidden_dim (Optional[int]): 隐藏层维度,如果为None则使用输入维度
"""
def __init__(self, dim: int, hidden_dim: Optional[int] = None):
"""
初始化成对协同注意力模块
Args:
dim (int): 输入特征维度
hidden_dim (Optional[int]): 隐藏层维度,如果为None则使用输入维度
"""
super().__init__()
h = hidden_dim or dim
# A -> B 方向的注意力计算
# Wq_A: A的查询投影矩阵
# Wk_B: B的键投影矩阵
# Wv_B: B的值投影矩阵
self.Wq_A = nn.Linear(dim, h)
self.Wk_B = nn.Linear(dim, h)
self.Wv_B = nn.Linear(dim, h)
# B -> A 方向的注意力计算
# Wq_B: B的查询投影矩阵
# Wk_A: A的键投影矩阵
# Wv_A: A的值投影矩阵
self.Wq_B = nn.Linear(dim, h)
self.Wk_A = nn.Linear(dim, h)
self.Wv_A = nn.Linear(dim, h)
# 输出投影层,将注意力输出映射回原始维度
self.proj_A = nn.Linear(h, dim)
self.proj_B = nn.Linear(h, dim)
def forward(self, A: torch.Tensor, B: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
前向传播,实现A和B之间的双向注意力
Args:
A (torch.Tensor): 第一个输入张量,形状为 [..., dim]
B (torch.Tensor): 第二个输入张量,形状为 [..., dim]
Returns:
Tuple[torch.Tensor, torch.Tensor]: 更新后的A和B张量,形状与输入相同
"""
# A关注B的注意力计算
# 分别计算A的查询向量和B的键、值向量
Q_A, K_B, V_B = self.Wq_A(A), self.Wk_B(B), self.Wv_B(B)
# 计算注意力权重,使用缩放点积注意力公式
attn_AB = torch.softmax(Q_A @ K_B.T / (K_B.size(1) ** 0.5), dim=1)
# 使用注意力权重聚合B的值向量,并通过投影层得到更新部分
A_out = A + self.proj_A(attn_AB @ V_B)
# B关注A的注意力计算
# 分别计算B的查询向量和A的键、值向量
Q_B, K_A, V_A = self.Wq_B(B), self.Wk_A(A), self.Wv_A(A)
# 计算注意力权重,使用缩放点积注意力公式
attn_BA = torch.softmax(Q_B @ K_A.T / (K_A.size(1) ** 0.5), dim=1)
# 使用注意力权重聚合A的值向量,并通过投影层得到更新部分
B_out = B + self.proj_B(attn_BA @ V_A)
return A_out, B_out
class TransformerPairwiseCoAttention(nn.Module):
"""
Transformer双向协作注意力模块
实现了两个输入序列之间的双向注意力机制,其中每个序列都可以作为查询去关注另一个序列。
这种机制允许两个输入序列A和B之间进行细粒度的信息交互,并通过多头注意力和前馈网络
进行特征增强。
Attributes:
dim (int): 输入特征的维度
h (int): 注意力头的数量
d (int): 每个注意力头的维度 (dim // num_heads)
dropout (float): Dropout概率
qA (nn.Linear): 序列A的查询投影矩阵
kB (nn.Linear): 序列B的键投影矩阵
vB (nn.Linear): 序列B的值投影矩阵
qB (nn.Linear): 序列B的查询投影矩阵
kA (nn.Linear): 序列A的键投影矩阵
vA (nn.Linear): 序列A的值投影矩阵
outA (nn.Linear): 序列A方向注意力输出的投影层
outB (nn.Linear): 序列B方向注意力输出的投影层
lnA1 (nn.LayerNorm): 序列A方向第一次层归一化
lnA2 (nn.LayerNorm): 序列A方向第二次层归一化
lnB1 (nn.LayerNorm): 序列B方向第一次层归一化
lnB2 (nn.LayerNorm): 序列B方向第二次层归一化
ffnA (nn.Sequential): 序列A方向的前馈网络
ffnB (nn.Sequential): 序列B方向的前馈网络
"""
def __init__(
self,
dim: int,
num_heads: int = 4,
ffn_hidden_dim: Optional[int] = None,
dropout: float = 0.0,
use_gelu: bool = True,
):
# 调用父类初始化方法
super().__init__()
# 确保维度可以被注意力头数整除,否则无法正确分割多头注意力
assert dim % num_heads == 0, "dim must be divisible by num_heads"
# 保存维度参数:总维度、头数、每个头的维度
self.dim = dim # 总特征维度
self.h = num_heads # 注意力头数
self.d = dim // num_heads # 每个注意力头的维度
self.dropout = dropout # Dropout概率
# --- A -> B 方向的注意力投影矩阵 (查询来自A,键/值来自B) ---
self.qA = nn.Linear(dim, dim) # A的查询投影
self.kB = nn.Linear(dim, dim) # B的键投影
self.vB = nn.Linear(dim, dim) # B的值投影
# --- B -> A 方向的注意力投影矩阵 (查询来自B,键/值来自A) ---
self.qB = nn.Linear(dim, dim) # B的查询投影
self.kA = nn.Linear(dim, dim) # A的键投影
self.vA = nn.Linear(dim, dim) # A的值投影
# 多头注意力输出的投影层,用于合并多头特征
self.outA = nn.Linear(dim, dim) # A方向注意力输出的最终投影
self.outB = nn.Linear(dim, dim) # B方向注意力输出的最终投影
# LayerNorm和前馈网络(FFN),采用Transformer的设计风格
# 每个方向都有自己的层归一化和前馈网络
self.lnA1 = nn.LayerNorm(dim) # A方向第一次层归一化
self.lnA2 = nn.LayerNorm(dim) # A方向第二次层归一化(FFN后)
self.lnB1 = nn.LayerNorm(dim) # B方向第一次层归一化
self.lnB2 = nn.LayerNorm(dim) # B方向第二次层归一化(FFN后)
# 设置前馈网络隐藏层维度,如果未指定则使用4倍输入维度(Transformer的默认做法)
ffn_hidden_dim = ffn_hidden_dim or (4 * dim)
# 根据参数选择激活函数:GELU或ReLU
act = nn.GELU() if use_gelu else nn.ReLU()
# 构建A方向的前馈网络,包含两个线性层、激活函数和Dropout
self.ffnA = nn.Sequential(
nn.Linear(dim, ffn_hidden_dim), # 升维
act, # 非线性激活
nn.Dropout(dropout), # 随机失活
nn.Linear(ffn_hidden_dim, dim), # 降维回原维度
nn.Dropout(dropout), # 随机失活
)
# 构建B方向的前馈网络,结构与A方向相同但参数独立
# share same FFN structure for B (separate params)
self.ffnB = nn.Sequential(
nn.Linear(dim, ffn_hidden_dim),
act,
nn.Dropout(dropout),
nn.Linear(ffn_hidden_dim, dim),
nn.Dropout(dropout),
)
def _split_heads(self, x: torch.Tensor) -> torch.Tensor:
"""
将输入张量分割成多个注意力头
Args:
x (torch.Tensor): 输入张量,形状为[B, dim]
Returns:
torch.Tensor: 分割后的张量,形状为[B, h, d]
"""
B, D = x.shape
return x.view(B, self.h, self.d)
def _merge_heads(self, x: torch.Tensor) -> torch.Tensor:
"""
合并多个注意力头的结果
Args:
x (torch.Tensor): 输入张量,形状为[B, h, d]
Returns:
torch.Tensor: 合并后的张量,形状为[B, dim]
"""
B = x.size(0)
return x.contiguous().view(B, self.dim)
def _pairwise_attention(self, Q: torch.Tensor, K: torch.Tensor, V: torch.Tensor) -> torch.Tensor:
"""
执行配对注意力计算
Args:
Q (torch.Tensor): 查询张量,形状为[B, h, d]
K (torch.Tensor): 键张量,形状为[B, h, d]
V (torch.Tensor): 值张量,形状为[B, h, d]
Returns:
torch.Tensor: 注意力计算结果,形状为[B, dim]
"""
# scaled dot product per head -> [B, h]
scores = (Q * K).sum(dim=-1) / (self.d ** 0.5) # [B, h]
# softmax across heads (dim=-1)
weights = torch.softmax(scores, dim=-1).unsqueeze(-1) # [B, h, 1]
# weight V heads and merge
weighted = weights * V # [B, h, d]
merged = self._merge_heads(weighted) # [B, dim]
return merged
def forward(self, A: torch.Tensor, B: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
前向传播函数
Args:
A (torch.Tensor): 第一个输入序列,形状为[B, dim]
B (torch.Tensor): 第二个输入序列,形状为[B, dim]
Returns:
Tuple[torch.Tensor, torch.Tensor]: 处理后的A和B序列,形状均为[B, dim]
"""
# --- compute QKV per direction and split into heads ---
Q_A = self._split_heads(self.qA(A)) # [B, h, d]
K_B = self._split_heads(self.kB(B))
V_B = self._split_heads(self.vB(B))
Q_B = self._split_heads(self.qB(B))
K_A = self._split_heads(self.kA(A))
V_A = self._split_heads(self.vA(A))
# --- A attends to B ---
attn_out_A = self._pairwise_attention(Q_A, K_B, V_B) # [B, dim]
attn_out_A = self.outA(attn_out_A) # projection
attn_out_A = F.dropout(attn_out_A, p=self.dropout, training=self.training)
# residual + norm
A_res = self.lnA1(A + attn_out_A)
# FFN with residual
A_ffn = self.ffnA(A_res)
A_out = self.lnA2(A_res + A_ffn)
# --- B attends to A ---
attn_out_B = self._pairwise_attention(Q_B, K_A, V_A)
attn_out_B = self.outB(attn_out_B)
attn_out_B = F.dropout(attn_out_B, p=self.dropout, training=self.training)
B_res = self.lnB1(B + attn_out_B)
B_ffn = self.ffnB(B_res)
B_out = self.lnB2(B_res + B_ffn)
return A_out, B_out
class MultiHeadPairwiseCoAttention(nn.Module):
def __init__(self, dim, num_heads=4):
super().__init__()
assert dim % num_heads == 0
self.num_heads = num_heads
self.head_dim = dim // num_heads
# A -> B direction
self.qA = nn.Linear(dim, dim)
self.kB = nn.Linear(dim, dim)
self.vB = nn.Linear(dim, dim)
# B -> A direction
self.qB = nn.Linear(dim, dim)
self.kA = nn.Linear(dim, dim)
self.vA = nn.Linear(dim, dim)
self.outA = nn.Linear(dim, dim)
self.outB = nn.Linear(dim, dim)
self.scale = self.head_dim ** -0.5
def _split(self, x):
B, L, D = x.size()
return x.view(B, L, self.num_heads, self.head_dim).transpose(1, 2)
def _merge(self, x):
B, H, L, D = x.size()
return x.transpose(1, 2).contiguous().view(B, L, H * D)
def forward(self, A, B):
qA = self._split(self.qA(A))
kB = self._split(self.kB(B))
vB = self._split(self.vB(B))
qB = self._split(self.qB(B))
kA = self._split(self.kA(A))
vA = self._split(self.vA(A))
attn_AB = torch.softmax((qA @ kB.transpose(-2, -1)) * self.scale, dim=-1)
attn_BA = torch.softmax((qB @ kA.transpose(-2, -1)) * self.scale, dim=-1)
A2B = attn_AB @ vB
B2A = attn_BA @ vA
A2B = self.outA(self._merge(A2B))
B2A = self.outB(self._merge(B2A))
return A2B, B2A
class MultiHeadCoAttentionFusion(nn.Module):
def __init__(self, dim):
super().__init__()
self.gA = nn.Sequential(
nn.Linear(dim * 2, dim),
nn.ReLU(),
nn.Linear(dim, dim),
nn.Sigmoid()
)
self.gB = nn.Sequential(
nn.Linear(dim * 2, dim),
nn.ReLU(),
nn.Linear(dim, dim),
nn.Sigmoid()
)
self.out = nn.Linear(dim * 2, dim)
def forward(self, A2B, B2A):
gA = self.gA(torch.cat([A2B, B2A], dim=-1))
gB = self.gB(torch.cat([A2B, B2A], dim=-1))
fused = torch.cat([
gA * A2B + (1 - gA) * B2A,
gB * B2A + (1 - gB) * A2B
], dim=-1)
return self.out(fused)
class MultiHeadTransformerPairwiseCoAttention(nn.Module):
def __init__(self, dim, num_heads=4, dropout=0.1):
super().__init__()
self.self_attn_A = nn.MultiheadAttention(dim, num_heads, dropout=dropout, batch_first=True)
self.self_attn_B = nn.MultiheadAttention(dim, num_heads, dropout=dropout, batch_first=True)
self.co_attn = MultiHeadPairwiseCoAttention(dim, num_heads=num_heads)
self.fusion = MultiHeadCoAttentionFusion(dim)
self.norm1_A = nn.LayerNorm(dim)
self.norm1_B = nn.LayerNorm(dim)
self.norm2 = nn.LayerNorm(dim)
self.mlp = nn.Sequential(
nn.Linear(dim, dim * 4),
nn.ReLU(),
nn.Linear(dim * 4, dim)
)
def forward(self, A, B):
A2, _ = self.self_attn_A(A, A, A)
B2, _ = self.self_attn_B(B, B, B)
A = self.norm1_A(A + A2)
B = self.norm1_B(B + B2)
A2B, B2A = self.co_attn(A, B)
Z = self.fusion(A2B, B2A)
Z = self.norm2(Z + self.mlp(Z))
return Z
# =================================================
# 注意力机制工厂类 - 支持命令行配置
# =================================================
class AttentionFactory:
"""
注意力机制工厂类,支持通过配置字符串动态创建不同类型的注意力模块
"""
@staticmethod
def create_co_attention(dim: int, config_str: str = "transformer", **kwargs) -> nn.Module:
"""
根据配置字符串创建协作注意力模块
Args:
dim (int): 输入特征维度
config_str (str): 配置字符串,格式为 "type[param1=value1,param2=value2,...]"
**kwargs: 额外参数
Returns:
nn.Module: 协作注意力模块
"""
# 解析配置字符串
if '[' in config_str and ']' in config_str:
attention_type = config_str.split('[')[0]
params_str = config_str.split('[')[1].split(']')[0]
params = AttentionFactory._parse_params(params_str)
else:
attention_type = config_str
params = {}
# 合并参数
params.update(kwargs)
# 根据类型创建注意力模块
if attention_type == "pairwise":
return PairwiseCoAttention(dim, params.get('hidden_dim', dim))
elif attention_type == "transformer":
return TransformerPairwiseCoAttention(
dim=dim,
num_heads=params.get('num_heads', 4),
ffn_hidden_dim=params.get('ffn_hidden_dim', 4 * dim),
dropout=params.get('dropout', 0.0),
use_gelu=params.get('use_gelu', True)
)
elif attention_type == "multihead":
return MultiHeadPairwiseCoAttention(
dim=dim,
num_heads=params.get('num_heads', 4)
)
else:
raise ValueError(f"Unknown attention type: {attention_type}")
@staticmethod
def create_fusion_attention(dim: int, config_str: str = "self_attention", **kwargs) -> nn.Module:
"""
根据配置字符串创建融合注意力模块
Args:
dim (int): 输入特征维度
config_str (str): 配置字符串
**kwargs: 额外参数
Returns:
nn.Module: 融合注意力模块
"""
if '[' in config_str and ']' in config_str:
fusion_type = config_str.split('[')[0]
params_str = config_str.split('[')[1].split(']')[0]
params = AttentionFactory._parse_params(params_str)
else:
fusion_type = config_str
params = {}
params.update(kwargs)
if fusion_type == "self_attention":
return SelfAttentionFusion(
hidden_dim=dim,
heads=params.get('heads', 4),
dropout=params.get('dropout', 0.1)
)
elif fusion_type == "co_attention":
co_attention_config = params.get('co_attention_type', 'transformer')
return CoAttentionFusion(
hidden_dim=dim,
hidden_dim_co=params.get('hidden_dim_co', dim),
num_heads=params.get('num_heads', 4),
dropout=params.get('dropout', 0.1),
co_attention_type=co_attention_config
)
elif fusion_type == "hybrid":
co_attention_config = params.get('co_attention_type', 'transformer')
return HybridFusion(
hidden_dim=dim,
heads=params.get('heads', 4),
dropout=params.get('dropout', 0.1),
co_hidden_dim=params.get('co_hidden_dim', dim),
fusion_weight=params.get('fusion_weight', 0.5),
co_attention_type=co_attention_config
)
elif fusion_type == "transformer_multihead":
return MultiHeadTransformerPairwiseCoAttention(
dim=dim,
num_heads=params.get('num_heads', 4),
dropout=params.get('dropout', 0.1)
)
else:
raise ValueError(f"Unknown fusion type: {fusion_type}")
@staticmethod
def _parse_params(params_str: str) -> dict:
"""解析参数字符串为字典"""
params = {}
if not params_str:
return params
for param in params_str.split(','):
if '=' in param:
key, value = param.split('=', 1)
# 尝试转换为适当的类型
if value.lower() in ['true', 'false']:
params[key.strip()] = value.lower() == 'true'
elif value.replace('.', '', 1).isdigit():
params[key.strip()] = float(value) if '.' in value else int(value)
else:
params[key.strip()] = value.strip()
return params
@staticmethod
def get_available_configurations() -> dict:
"""获取所有可用的配置选项"""
return {
"co_attention_types": [
"pairwise",
"transformer[num_heads=4,dropout=0.1]",
"multihead[num_heads=4]",
],
"fusion_types": [
"self_attention[heads=4,dropout=0.1]",
"co_attention[co_attention_type=transformer]",
"hybrid[fusion_weight=0.5,co_attention_type=transformer]",
"transformer_multihead[num_heads=4]",
]
}
# =================================================
# 具体融合策略实现
# =================================================
class SelfAttentionFusion(FusionStrategy):
"""
原始的自注意力融合策略
使用多头自注意力机制对两个实体进行融合,通过堆叠两个实体表示,
然后应用自注意力和前馈网络进行特征融合。
Attributes:
hidden_dim (int): 隐藏层维度
heads (int): 注意力头数
dropout (float): Dropout概率
mha (nn.MultiheadAttention): 多头注意力层
ffn (nn.Sequential): 前馈网络
norm1 (nn.LayerNorm): 第一层归一化
norm2 (nn.LayerNorm): 第二层归一化
dropout_layer (nn.Dropout): Dropout层
"""
def __init__(self, hidden_dim: int, heads: int = 4, dropout: float = 0.1):
"""
初始化自注意力融合策略
Args:
hidden_dim (int): 隐藏层维度
heads (int): 注意力头数,默认为4
dropout (float): Dropout概率,默认为0.1
"""
super().__init__()
self.hidden_dim = hidden_dim
self.heads = heads
self.dropout = dropout
# 直接初始化模块
self.mha = nn.MultiheadAttention(
embed_dim=self.hidden_dim,
num_heads=self.heads,
dropout=self.dropout,
batch_first=True
)
self.ffn = nn.Sequential(
nn.Linear(self.hidden_dim, self.hidden_dim * 4),
nn.ReLU(),
nn.Dropout(self.dropout),
nn.Linear(self.hidden_dim * 4, self.hidden_dim),
)
self.norm1 = nn.LayerNorm(self.hidden_dim)
self.norm2 = nn.LayerNorm(self.hidden_dim)
self.dropout_layer = nn.Dropout(self.dropout)
def forward(self, e1: torch.Tensor, e2: torch.Tensor) -> torch.Tensor:
"""
前向传播函数,使用自注意力机制融合两个实体
Args:
e1 (torch.Tensor): 第一个实体的特征表示,形状为[batch_size, hidden_dim]
e2 (torch.Tensor): 第二个实体的特征表示,形状为[batch_size, hidden_dim]
Returns:
torch.Tensor: 融合后的特征表示,形状为[batch_size, 2*hidden_dim]
"""
B, H = e1.size(0), e1.size(1)
x = torch.stack([e1, e2], dim=1) # [B,2,H]
attn_out, _ = self.mha(x, x, x) # [B,2,H]
x = self.norm1(x + self.dropout_layer(attn_out))
ffn_out = self.ffn(x)
x = self.norm2(x + self.dropout_layer(ffn_out)) # [B,2,H]
x = x.reshape(B, 2 * H) # [B,2H]
return x
class CoAttentionFusion2(FusionStrategy):
"""
协作注意力融合策略,使用PairwiseCoAttention
使用协作注意力机制对两个实体进行融合,通过PairwiseCoAttention模块
实现两个实体之间的相互关注,然后拼接结果。
Attributes:
hidden_dim (int): 隐藏层维度
hidden_dim_co (int): 协作注意力的隐藏层维度
co_attn (PairwiseCoAttention): 协作注意力模块
"""
def __init__(self, hidden_dim: int, hidden_dim_co: Optional[int] = None):
"""
初始化协作注意力融合策略
Args:
hidden_dim (int): 隐藏层维度
hidden_dim_co (Optional[int]): 协作注意力的隐藏层维度,默认为None
"""
super().__init__()
self.hidden_dim = hidden_dim
self.hidden_dim_co = hidden_dim_co = hidden_dim
self.co_attn = PairwiseCoAttention(self.hidden_dim, self.hidden_dim_co)
def forward(self, e1: torch.Tensor, e2: torch.Tensor) -> torch.Tensor:
"""
前向传播函数,使用协作注意力机制融合两个实体
Args:
e1 (torch.Tensor): 第一个实体的特征表示,形状为[batch_size, hidden_dim]
e2 (torch.Tensor): 第二个实体的特征表示,形状为[batch_size, hidden_dim]
Returns:
torch.Tensor: 融合后的特征表示,形状为[batch_size, 2*hidden_dim]
"""
e1_out, e2_out = self.co_attn(e1, e2)
# 拼接两个实体的表示
return torch.cat([e1_out, e2_out], dim=1) # [B, 2H]
class CoAttentionFusion(FusionStrategy):
"""
协作注意力融合策略,可以选择使用TransformerPairwiseCoAttention或PairwiseCoAttention
使用协作注意力机制对两个实体进行融合,根据参数选择使用TransformerPairwiseCoAttention模块
或PairwiseCoAttention模块实现两个实体之间的相互关注,然后拼接结果。
Attributes:
hidden_dim (int): 隐藏层维度
hidden_dim_co (int): 协作注意力的隐藏层维度
co_attn (Union[PairwiseCoAttention, TransformerPairwiseCoAttention]): 协作注意力模块
"""
def __init__(
self,
hidden_dim: int,
hidden_dim_co: Optional[int] = None,
num_heads: int = 4,
dropout: float = 0.1,
co_attention_type: str = 'transformer'
):
super().__init__()
self.hidden_dim = hidden_dim
self.hidden_dim_co = hidden_dim if hidden_dim_co is None else hidden_dim_co
# 根据参数选择使用哪种类型的协作注意力
if co_attention_type == 'pairwise':
self.co_attn = PairwiseCoAttention(
dim=self.hidden_dim,
hidden_dim=self.hidden_dim_co
)
else: # 默认使用 transformer 类型
self.co_attn = TransformerPairwiseCoAttention(
dim=self.hidden_dim,
num_heads=num_heads,
ffn_hidden_dim=4 * self.hidden_dim, # Transformer 默认
dropout=dropout,
)
def forward(self, e1: torch.Tensor, e2: torch.Tensor) -> torch.Tensor:
"""
输入:
e1: [B, H]
e2: [B, H]
输出:
[B, 2H]
"""
e1_out, e2_out = self.co_attn(e1, e2)
return torch.cat([e1_out, e2_out], dim=1)
class HybridFusion(FusionStrategy):
"""
混合融合策略:结合自注意力和协作注意力
结合自注意力和协作注意力两种机制,通过加权融合的方式
得到最终的融合结果。
Attributes:
hidden_dim (int): 隐藏层维度
heads (int): 注意力头数
dropout (float): Dropout概率
co_hidden_dim (Optional[int]): 协作注意力的隐藏层维度
fusion_weight (float): 自注意力融合结果的权重
self_attn_fusion (SelfAttentionFusion): 自注意力融合模块
co_attn_fusion (CoAttentionFusion): 协作注意力融合模块
"""
def __init__(self, hidden_dim: int, heads: int = 4, dropout: float = 0.1,
co_hidden_dim: Optional[int] = None, fusion_weight: float = 0.5,
co_attention_type: str = 'transformer'):
"""
初始化混合融合策略
Args:
hidden_dim (int): 隐藏层维度
heads (int): 注意力头数,默认为4
dropout (float): Dropout概率,默认为0.1
co_hidden_dim (Optional[int]): 协作注意力的隐藏层维度,默认为None
fusion_weight (float): 自注意力融合结果的权重,默认为0.5
co_attention_type (str): 协作注意力类型,默认为 'transformer'
"""
super().__init__()
self.hidden_dim = hidden_dim
self.heads = heads
self.dropout = dropout
self.co_hidden_dim = co_hidden_dim
self.fusion_weight = fusion_weight
self.self_attn_fusion = SelfAttentionFusion(self.hidden_dim, self.heads, self.dropout)
self.co_attn_fusion = CoAttentionFusion(self.hidden_dim, hidden_dim_co=co_hidden_dim,
co_attention_type=co_attention_type)
def forward(self, e1: torch.Tensor, e2: torch.Tensor) -> torch.Tensor:
"""
前向传播函数,混合自注意力和协作注意力机制融合两个实体
Args:
e1 (torch.Tensor): 第一个实体的特征表示,形状为[batch_size, hidden_dim]
e2 (torch.Tensor): 第二个实体的特征表示,形状为[batch_size, hidden_dim]
Returns:
torch.Tensor: 融合后的特征表示,形状为[batch_size, 2*hidden_dim]
"""
# 自注意力融合
self_attn_out = self.self_attn_fusion.forward(e1, e2)
# 协作注意力融合
co_attn_out = self.co_attn_fusion.forward(e1, e2)
# 加权融合
return self.fusion_weight * self_attn_out + (1 - self.fusion_weight) * co_attn_out
# =================================================
# Graph Transformer 风格融合策略
# =================================================
class GraphTransformerStyleFusion(nn.Module):
"""
Graph Transformer 风格的两-token注意力 + 前馈;输出拼接为 [B, 2H]
增强版:支持协作注意力和热插拔功能
该模块将两个实体表示作为输入,通过可配置的融合策略进行特征融合,
最终将两个实体的表示拼接为一个长度为2H的向量。支持多种融合策略的
动态切换,实现热插拔功能。
Attributes:
_strategy (FusionStrategy): 融合策略实例,支持热插拔
hidden_dim (int): 隐藏层维度
heads (int): 注意力头的数量
dropout (float): Dropout概率
strategy_type (str): 当前使用的策略类型
strategy_kwargs (dict): 策略特定的额外参数
_preserve_legacy (bool): 是否保持向后兼容的原始模块
mha (nn.MultiheadAttention): 多头注意力层(仅在self_attention模式下使用)
ffn (nn.Sequential): 前馈网络(仅在self_attention模式下使用)
norm1 (nn.LayerNorm): 第一层归一化(仅在self_attention模式下使用)
norm2 (nn.LayerNorm): 第二层归一化(仅在self_attention模式下使用)
_dropout (nn.Dropout): Dropout层(仅在self_attention模式下使用)
"""
def __init__(self, hidden_dim: int, heads: int = 4, dropout: float = 0.1,
strategy_type: str = "self_attention", **strategy_kwargs):
"""
初始化GraphTransformerStyleFusion模块
Args:
hidden_dim (int): 隐藏层维度
heads (int, optional): 注意力头的数量,默认为4
dropout (float, optional): Dropout概率,默认为0.1
strategy_type (str, optional): 融合策略类型,可选 "self_attention", "co_attention", "hybrid"
**strategy_kwargs: 策略特定的额外参数
"""
super().__init__()
self.hidden_dim = hidden_dim
self.heads = heads
self.dropout = dropout
self.strategy_type = strategy_type
self.strategy_kwargs = strategy_kwargs
# 初始化融合策略
self._strategy = None
self._initialize_strategy()
# 保持向后兼容的原始模块(用于self_attention模式)
self._preserve_legacy = strategy_type == "self_attention"
if self._preserve_legacy:
self.mha = nn.MultiheadAttention(embed_dim=hidden_dim, num_heads=heads, dropout=dropout, batch_first=True)
self.ffn = nn.Sequential(
nn.Linear(hidden_dim, hidden_dim * 4),
nn.ReLU(),
nn.Dropout(dropout),
nn.Linear(hidden_dim * 4, hidden_dim),
)
self.norm1 = nn.LayerNorm(hidden_dim)
self.norm2 = nn.LayerNorm(hidden_dim)
self._dropout = nn.Dropout(dropout)
def _initialize_strategy(self):
"""初始化融合策略"""
try:
# 首先尝试使用工厂方法创建融合策略
self._strategy = AttentionFactory.create_fusion_attention(
dim=self.hidden_dim,
config_str=self.strategy_type,
heads=self.heads,
dropout=self.dropout,
**self.strategy_kwargs
)
except Exception:
# 如果工厂方法失败,回退到原有的策略创建方式
if self.strategy_type == "self_attention":
self._strategy = SelfAttentionFusion(self.hidden_dim, self.heads, self.dropout)
elif self.strategy_type == "co_attention":
# 处理参数名映射
kwargs = self.strategy_kwargs.copy()
if 'co_hidden_dim' in kwargs:
kwargs['hidden_dim_co'] = kwargs.pop('co_hidden_dim')
# 添加协作注意力类型参数
kwargs['co_attention_type'] = getattr(get_args(), 'co_attention_type', 'transformer')
self._strategy = CoAttentionFusion(self.hidden_dim, **kwargs)
elif self.strategy_type == "hybrid":
# 处理参数名映射
kwargs = self.strategy_kwargs.copy()
if 'co_hidden_dim' in kwargs:
kwargs['co_hidden_dim'] = kwargs.pop('co_hidden_dim')
# 添加协作注意力类型参数
kwargs['co_attention_type'] = getattr(get_args(), 'co_attention_type', 'transformer')
self._strategy = HybridFusion(self.hidden_dim, self.heads, self.dropout, **kwargs)
else:
raise ValueError(f"Unknown strategy_type: {self.strategy_type}")
def set_strategy(self, strategy_type: str, **strategy_kwargs):
"""
热插拔:动态设置融合策略
Args:
strategy_type (str): 新的融合策略类型
**strategy_kwargs: 策略特定的额外参数
"""
self.strategy_type = strategy_type
self.strategy_kwargs = strategy_kwargs
# 初始化新策略
self._initialize_strategy()
self._preserve_legacy = (strategy_type == "self_attention")
def get_available_strategies(self) -> List[str]:
"""获取可用的融合策略列表
Returns:
List[str]: 可用的融合策略列表
"""
return ["self_attention", "co_attention", "hybrid"]
def forward(self, e1: torch.Tensor, e2: torch.Tensor) -> torch.Tensor:
"""
前向传播函数,对两个实体表示进行特征融合
将两个实体表示通过配置的策略进行融合
Args:
e1 (torch.Tensor): 第一个实体的表示,形状为 [B, H]
e2 (torch.Tensor): 第二个实体的表示,形状为 [B, H]
Returns:
torch.Tensor: 融合后的表示,形状为 [B, 2H]
"""
if self._preserve_legacy and hasattr(self, 'mha'):
# 保持原始实现的兼容性
B, H = e1.size(0), e1.size(1)
x = torch.stack([e1, e2], dim=1) # [B,2,H]
attn_out, _ = self.mha(x, x, x) # [B,2,H]
x = self.norm1(x + self._dropout(attn_out))
ffn_out = self.ffn(x)
x = self.norm2(x + self._dropout(ffn_out)) # [B,2,H]
x = x.reshape(B, 2 * H) # [B,2H]
return x
else:
# 使用新策略
return self._strategy.forward(e1, e2)