-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_abulation.py
More file actions
2303 lines (1900 loc) · 94.6 KB
/
Copy pathmain_abulation.py
File metadata and controls
2303 lines (1900 loc) · 94.6 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 csv
import gc
import logging
import math
import os, sys
import random
import time
from tqdm import tqdm
from tqdm.contrib.logging import logging_redirect_tqdm
from functools import lru_cache
from collections import deque
from typing import Literal
import torch.nn as nn
import optuna
import pandas as pd
import dgl
import numpy as np
import torch
from torch.utils.data import DataLoader, TensorDataset, Subset
import torch.nn.functional as F
import torch.optim as optim
import torch.optim.lr_scheduler as lr_scheduler
from torch.cuda.amp import autocast, GradScaler
from torch_scatter import scatter_mean, scatter_add
from pytorch_metric_learning import losses
from src.utils import set_logging, to_numpy
from src.misc.revgat.loss import loss_kd_only
from src.model.lm_gnn import RevGAT, HSAGE, MLP, global_entropy, graph_reconstruction_loss
from src.model import get_model_class
from src.args import parse_args, save_args
import src.lora as lora
from src.trainer import get_trainer_class, TextDataset, Code_Trainer
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, roc_auc_score, matthews_corrcoef,jaccard_score
from data_loader import CodeEvaluator,GraphTextDataset,collate_fn
from torch_scatter import scatter_add
from torch_geometric.nn import MessagePassing
from torch_geometric.utils import add_self_loops
from src.utils import search_best_threshold, search_best_alpha_threshold
logger = logging.getLogger(__name__)
logging.getLogger("torch").setLevel(logging.ERROR)
# os.environ["DGL_WORKER_CPU_PINNING"] = "0"
def worker_init_fn(worker_id):
sys.stderr = open(os.devnull, 'w') # 屏蔽 worker 进程的 stderr
sys.stdout = open(os.devnull, 'w') # 屏蔽 stdout
np.random.seed(42 + worker_id)
random.seed(42 + worker_id)
torch.manual_seed(42 + worker_id)
def seed(seed=0):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
dgl.random.seed(seed)
def check_nan(model):
for name, param in model.named_parameters():
if param.requires_grad and torch.isnan(param).any():
raise ValueError(f"NaN detected in parameter {name}")
if param.grad is not None and torch.isnan(param.grad).any():
raise ValueError(f"NaN detected in gradient of {name}")
def top2n_recall(y_true, y_prob, k=2):
n_pos = sum(y_true)
if n_pos > 0:
top_k = math.ceil(k * n_pos)
topk_indices = np.argsort(y_prob)[-top_k:]
true_positives = sum(y_true[i] for i in topk_indices)
recall = true_positives / n_pos if n_pos > 0 else 0
else:
recall = 0
return recall
def topkk_recall(y_true, y_prob, k=5):
n_pos = sum(y_true)
if n_pos > 0:
top_k = n_pos+k
topk_indices = np.argsort(y_prob)[-top_k:]
true_positives = sum(y_true[i] for i in topk_indices)
recall = true_positives / n_pos
else:
recall = 0
return recall
def collate_fn1(batch):
# 初始化空列表,用于存储批次数据
graphs = []
input_ids_list = []
attention_mask_list = []
labels = []
# 遍历批次中的每个样本
for item in batch:
graphs.append(item['graph'])
input_ids_list.append(item['input_ids'])
attention_mask_list.append(item['attention_mask'])
labels.append(item['labels']) # 每个样本的label是一个张量
# 拼接图数据
batched_graph = dgl.batch(graphs)
# 拼接文本数据
input_ids = torch.cat(input_ids_list, dim=0) # 纵向拼接input_ids
attention_mask = torch.cat(attention_mask_list, dim=0) # 纵向拼接attention_mask
# 拼接labels
labels = torch.cat(labels, dim=0) # 将labels拼接成一个张量
# 返回批次数据
return {
'graph': batched_graph,
'input_ids': input_ids,
'attention_mask': attention_mask,
'labels': labels
}
def multi_hop_self_agg(grad, edge_index, num_hops=1, alpha=0.5):
"""
使用自身 + 多跳邻居梯度估计进行梯度补偿
参数:
- grad: (num_nodes, feature_dim) 原始梯度张量
- edge_index: (2, num_edges) 图的边索引
- num_hops: 传播的跳数
- alpha: 邻居梯度衰减因子(仅适用于 num_hops > 1)
返回:
- compensated_grad: (num_nodes, feature_dim) 经过补偿后的梯度
"""
num_nodes = grad.shape[0]
compensated_grad = grad.clone() # 先初始化为自身梯度
node_weight = torch.ones((num_nodes, 1), device=grad.device) # 记录权重归一化因子
current_grad = grad.clone() # 作为初始梯度
for hop in range(num_hops):
# 计算一跳邻居梯度均值
neighbor_grad = torch.zeros_like(grad)
neighbor_weight = torch.zeros((num_nodes, 1), device=grad.device)
# 聚合邻居的梯度
scatter_add(current_grad[edge_index[0]], edge_index[1], dim=0, out=neighbor_grad)
scatter_add(torch.ones_like(node_weight)[edge_index[0]], edge_index[1], dim=0, out=neighbor_weight)
# 归一化:如果节点没有邻居,避免除以 0
neighbor_weight = torch.where(neighbor_weight > 0, neighbor_weight, torch.ones_like(neighbor_weight))
neighbor_grad /= neighbor_weight # 计算均值
# 计算当前 hop 的补偿
compensated_grad += alpha**hop * neighbor_grad
node_weight += alpha**hop # 累计归一化因子
# 更新 current_grad 为本次邻居梯度,以便用于下一跳
current_grad = neighbor_grad.clone()
# 最终归一化
compensated_grad /= node_weight
return compensated_grad
def multi_hop_aggregation(grad, edge_index, num_nodes, num_hops=1, decay=0.5):
"""
对所有节点进行多跳梯度聚合。
当 num_hops=1 时,直接聚合一跳邻居的梯度信息。
参数:
grad: 原始梯度信息,形状为 [num_nodes, feature_dim]
edge_index: 图的边索引,形状为 [2, E],第一行为源节点,第二行为目标节点
num_nodes: 节点总数
num_hops: 聚合跳数,>=1 表示至少聚合一跳邻居信息
decay: 衰减因子,用于降低多跳传播时越远节点的影响
返回:
聚合后的梯度,形状为 [num_nodes, feature_dim]
"""
aggregated_grad = 0 # 用于累加每一跳的聚合结果
current_grad = grad # 初始梯度
for hop in range(num_hops):
# 每一次循环将 current_grad 聚合到目标节点上
current_grad = scatter_mean(current_grad[edge_index[0]], edge_index[1], dim=0, dim_size=num_nodes)
aggregated_grad += (decay ** hop) * current_grad
return aggregated_grad
class FocalLoss(torch.nn.Module):
def __init__(self,
alpha=None,
class_counts=None,
alpha_smoothing='log', # 'none', 'log', 'sqrt'
normalize_alpha=True, # 是否归一化为均值 1
gamma=1.0,
smoothing=0.1,
reduction='mean'):
super().__init__()
self.gamma = gamma
self.smoothing = smoothing
self.reduction = reduction
if alpha is None and class_counts is not None:
counts = torch.tensor(class_counts, dtype=torch.float32)
total = counts.sum()
alpha = total / counts
if alpha_smoothing == 'log':
alpha = torch.log1p(alpha)
alpha = torch.sqrt(alpha)
elif alpha_smoothing == 'sqrt':
alpha = torch.sqrt(alpha)
if normalize_alpha:
alpha = alpha / alpha.mean()
if alpha is not None:
self.register_buffer('alpha', alpha)
else:
self.alpha = None
def forward(self, inputs, targets):
os.environ["CUDA_LAUNCH_BLOCKING"] = "1"
num_classes = inputs.size(1)
device = inputs.device
with torch.no_grad():
true_dist = torch.full_like(inputs, self.smoothing / (num_classes - 1))
true_dist.scatter_(1, targets.unsqueeze(1), 1.0 - self.smoothing)
log_probs = F.log_softmax(inputs, dim=1)
probs = log_probs.exp()
pt = torch.sum(probs * true_dist, dim=1)
log_pt = torch.sum(log_probs * true_dist, dim=1)
if self.alpha is not None:
assert targets.dtype == torch.long, f"targets.dtype={targets.dtype}, must be torch.long"
assert targets.min() >= 0, f"target min = {targets.min().item()} < 0"
assert targets.max() < num_classes, f"target max = {targets.max().item()} >= num_classes={num_classes}"
alpha_t = self.alpha.to(device)[targets]
else:
alpha_t = 1.0
loss = -alpha_t * (1 - pt) ** self.gamma * log_pt
os.environ["CUDA_LAUNCH_BLOCKING"] = "0"
if self.reduction == 'mean':
return loss.mean()
elif self.reduction == 'sum':
return loss.sum()
else:
return loss
class ReplaceRowsFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, input, rows, replacement, num_nodes, edge_index):
"""
input: 原始特征矩阵,shape为 [N, F]
rows: 被替换行的索引
replacement: 替换的特征,这部分节点需要梯度
edge_index: 图的边索引,shape为 [2, E]
num_nodes: 节点总数
"""
ctx.save_for_backward(input, rows, replacement)
ctx.edge_index = edge_index
ctx.num_nodes = num_nodes
output = input.clone()
output[rows] = replacement
return output
@staticmethod
def backward(ctx, grad_output):
input, rows, replacement = ctx.saved_tensors
edge_index = ctx.edge_index
num_nodes = ctx.num_nodes
grad_input = grad_output.clone()
grad_input[rows] = 0
alpha = 0.05 # 可调超参数,调节补偿力度
# # 全图平均估计 采样消融可以使用
# mask = torch.ones(grad_output.shape[0], dtype=torch.bool, device=grad_output.device)
# mask[rows] = False
# # 计算未替换节点的全局平均梯度
# if mask.sum() > 0:
# global_avg = grad_output[mask].mean(dim=0)
# else:
# global_avg = torch.zeros_like(grad_output[0])
# grad_replacement = grad_output[rows] + alpha * global_avg
# grad_replacement = grad_output[rows].clone()
# 局部邻居估计
grad_neighbor = multi_hop_aggregation(grad_output, edge_index, num_nodes, 2, alpha)
grad_replacement = 1/(1+alpha)*(grad_output[rows] + alpha * grad_neighbor[rows])
#grad_replacement = grad_output[rows]
return grad_input, None, grad_replacement, None, None
# #可以考虑补偿-qianwen 函数
# @staticmethod
# def backward(ctx, grad_output):
# input, rows, replacement = ctx.saved_tensors
# edge_index = ctx.edge_index
# num_nodes = ctx.num_nodes
# # === 明确两个超参数 ===
# decay = 0.5 # 多跳内部衰减(控制 G1, G2, ... 的权重)
# beta = 0.1 # 最终补偿强度(控制原始梯度和平滑梯度的混合比例)
# grad_input = grad_output.clone()
# grad_input[rows] = 0
# # 调用时显式指定参数名,避免混淆
# grad_neighbor = multi_hop_aggregation(
# grad=grad_output,
# edge_index=edge_index,
# num_nodes=num_nodes,
# num_hops=2,
# decay=decay # ← 不再用 alpha!
# )
# # 使用清晰的凸组合
# grad_replacement = (1 - beta) * grad_output[rows] + beta * grad_neighbor[rows]
# return grad_input, None, grad_replacement, None, None
replace_rows = ReplaceRowsFunction.apply
class BiDirectNeighborSampler(dgl.dataloading.NeighborSampler):
def sample_neighbors(self, g, nodes):
in_neighbors = g.in_edges(nodes)[0] # 采样入度邻居
out_neighbors = g.out_edges(nodes)[1] # 采样出度邻居
all_neighbors = torch.cat([in_neighbors, out_neighbors]) # 合并
return g.subgraph(all_neighbors)
class MeanAggregation(MessagePassing):
def __init__(self):
super(MeanAggregation, self).__init__(aggr='mean')
def forward(self, x, edge_index):
# x has shape [N, in_channels]
# edge_index has shape [2, E]
# Step 1: Add self-loops to the adjacency matrix.
_edge_index, _ = add_self_loops(edge_index, num_nodes=x.size(0))
# Step 4-5: Start propagating messages.
return self.propagate(_edge_index, x=x)
def compute_jsd(dist1, dist2):
dist_mean = (dist1 + dist2) / 2.
jsd = (F.kl_div(dist_mean.log(), dist1, reduction='none') +
F.kl_div(dist_mean.log(), dist2, reduction='none')) / 2.
return jsd
class LM_GNN():
def __init__(self, args, **kwargs) -> None:
# 参数初始化
self.args = args
self.epsilon = args.eps if args.eps is not None else 1 - math.log(2)
self.device = torch.device(f"cuda:{args.gpu}" if not args.cpu else "cpu") # 设备设置
self.dtype = torch.float16 if args.fp16 else torch.float32 # 数据类型选择
# 数据相关
self.data=[] #存储富文本图数据
self.graphs = [] # 存储所有的图
self.text_tokens = [] # 存储所有图的tokenized文本数据
self.feat_static = None # 图的静态特征
# self.feat = None
self.labels = None # 存储所有图的标签数据
self.uids = None
self.train_idx = None # 存储所有训练集索引
self.val_idx = None # 存储所有验证集索引
self.test_idx = None # 存储所有测试集索引
self.split_idx = None # 数据集划分信息(train, valid, test)
self.train_dataset = None
self.test_dataset = None
#self.preds = None
# 模型相关
self.model_lm = None # 语言模型
self.model_gnn = None # 图神经网络模型
self.is_lm = [] # 语言模型参数标记
self.require_grad = [] # 需要梯度更新的参数
self.lora_added = False # 是否使用LoRA
# 训练相关
self.optimizer = None # 优化器
self.criterion = None # 损失函数
self.NTXentLoss = losses.NTXentLoss(temperature = self.args.label_smoothing)
self.SupConLoss = losses.SupConLoss(temperature = self.args.label_smoothing)
self.evaluator = None # 模型评估器,仅lm预训练使用
self.whole_graph = False # 是否使用整个图
# 试验相关
self.trial = kwargs.pop("trial", None) # 试验编号
# 辅助信息
self.n_node = 0 # 节点数(可以根据需要更新)
self.gpt_preds = None # GPT模型预测(如果有)
# GradScaler(用于FP16训练)
self.scaler = GradScaler() if self.args.fp16 else None
# 设备转移标记
self.args.grad_padding2 = 0
self.train_data_loader = None
if(self.args.lm_x):
self.node_classifier = nn.Linear(self.args.adapter_hidden_size, 2).to(self.device)
def preprocess(self):
# global n_node_feats
# make bidirected
# feat = graph.ndata["feat"]
for i, g in enumerate(self.graphs):
g = g.remove_self_loop()
ne = g.num_edges()
g = dgl.add_reverse_edges(g, copy_ndata=True, copy_edata=True)
g = g.add_self_loop()
etype = torch.zeros(g.num_edges(), dtype=torch.long)
etype[ne:ne*2] = 1
etype[ne*2:] = 2
g.edata["type"] = etype
self.graphs[i] = g
# logger.info(f"Total edges after adding self-loop {self.graph.number_of_edges()}")
# self.graph.create_formats_()
self.args.n_edge_types = 3
def prepare(self):
'''device, scaler, criterion, metrics'''
if self.args.cpu:
self.device = torch.device("cpu")
else:
self.device = torch.device(f"cuda:{self.args.gpu}")
# self.labels, self.val_idx, self.test_idx = map(
# lambda x: x.to(self.device), (self.labels, self.val_idx, self.test_idx)
# )
self.labels = self.labels.to(self.device)
# 初始化GradScaler
self.scaler = GradScaler() if self.args.fp16 else None
num_total = self.data['attr']['n_nodes']
num_pos = self.data['attr']['n_vul_nodes']
# self.args.loss_weight = torch.tensor([weight_neg, weight_pos], dtype=torch.float32)
# self.criterion = torch.nn.CrossEntropyLoss(label_smoothing=self.args.label_smoothing, reduction =self.args.loss_reduction)
# self.criterion = torch.nn.CrossEntropyLoss(label_smoothing=self.args.label_smoothing, reduction =self.args.loss_reduction, weight=self.args.loss_weight)
self.criterion = FocalLoss(class_counts=[num_total-num_pos, num_pos],
alpha_smoothing='log',
gamma=self.args.focal_loss_gamma,
smoothing=self.args.label_smoothing_factor,
reduction=self.args.loss_reduction,
normalize_alpha = False
#normalize_alpha = True
)
self.metrics = {
'acc' : lambda y_true,y_pred,y_prob: accuracy_score(y_true, y_pred),
'f1' : lambda y_true,y_pred,y_prob: f1_score(y_true, y_pred, average="weighted")\
if self.args.num_labels > 2 else f1_score(y_true, y_pred),
'prec': lambda y_true,y_pred,y_prob: precision_score(y_true, y_pred, average="weighted")\
if self.args.num_labels > 2 else precision_score(y_true, y_pred),
'rec' : lambda y_true,y_pred,y_prob: recall_score(y_true, y_pred, average="weighted")\
if self.args.num_labels > 2 else recall_score(y_true, y_pred),
'auc': lambda y_true,y_pred,y_prob: roc_auc_score(y_true, y_prob, multi_class="ovo", average="micro")\
if self.args.num_labels > 2 else roc_auc_score(y_true, y_prob),
'auc1': lambda y_true,y_pred,y_prob: roc_auc_score(y_true, y_prob, multi_class="ovo", average="micro")\
if self.args.num_labels > 2 else roc_auc_score(y_true, y_prob),
'mcc': lambda y_true,y_pred,y_prob: matthews_corrcoef(y_true, y_pred),
# 'iou1':lambda y_true,y_pred: jaccard_score(y_true, y_pred, average="micro")\
# if self.args.num_labels > 2 else jaccard_score(y_true, y_pred),
'iou':lambda y_true,y_pred,y_prob: jaccard_score(y_true, y_pred, average="micro")\
if self.args.num_labels > 2 else jaccard_score(y_true, y_pred),
}
self.metrics_test = {
'acc' : lambda y_true,y_pred,y_prob: accuracy_score(y_true, y_pred),
'f1' : lambda y_true,y_pred,y_prob: f1_score(y_true, y_pred, average="weighted")\
if self.args.num_labels > 2 else f1_score(y_true, y_pred),
'prec': lambda y_true,y_pred,y_prob: precision_score(y_true, y_pred, average="weighted")\
if self.args.num_labels > 2 else precision_score(y_true, y_pred),
'rec' : lambda y_true,y_pred,y_prob: recall_score(y_true, y_pred, average="weighted")\
if self.args.num_labels > 2 else recall_score(y_true, y_pred),
'auc': lambda y_true,y_pred,y_prob: roc_auc_score(y_true, y_prob, multi_class="ovo", average="micro")\
if self.args.num_labels > 2 else roc_auc_score(y_true, y_prob),
'auc1': lambda y_true,y_pred,y_prob: roc_auc_score(y_true, y_pred, multi_class="ovo", average="micro")\
if self.args.num_labels > 2 else roc_auc_score(y_true, y_pred),
'mcc': lambda y_true,y_pred,y_prob: matthews_corrcoef(y_true, y_pred),
# 'iou1':lambda y_true,y_pred: jaccard_score(y_true, y_pred, average="micro")\
# if self.args.num_labels > 2 else jaccard_score(y_true, y_pred),
'iou':lambda y_true,y_pred,y_prob: jaccard_score(y_true, y_pred, average="micro")\
if self.args.num_labels > 2 else jaccard_score(y_true, y_pred),
'rec@2n':lambda y_true,y_pred,y_prob: top2n_recall(y_true,y_prob, k=2),
'rec@1.5n':lambda y_true,y_pred,y_prob: top2n_recall(y_true,y_prob, k=1.5),
'rec@3+':lambda y_true,y_pred,y_prob: topkk_recall(y_true,y_prob,k=3),
'rec@5+':lambda y_true,y_pred,y_prob: topkk_recall(y_true,y_prob,k=5),
}
def save_stat(self, epoch, e2e, best, name):
out_dir = f"{self.args.save}/ckpt"
fname = os.path.join(out_dir, f"{name}_stat.pt")
torch.save({
'epoch': epoch,
'gnn_dict': self.model_gnn.state_dict(),
'lm_dict': self.model_lm.state_dict() if self.model_lm else None,
'optm_dict': self.optimizer.state_dict(),
'feat_static': self.feat_static,
'full_ft': e2e,
# 'args': self.args,
'best': best
# 可以添加其他你需要保存的状态
}, fname)
logger.info(f"Saving stat ckpt for {name} ...")
def save_pred(self, pred, name):
os.makedirs(f"{self.args.save}/cached_embs", exist_ok=True)
torch.save(pred, f"{self.args.save}/cached_embs/logits_{name}.pt")
torch.save(self.feat_static, f"{self.args.save}/cached_embs/x_embs_{name}.pt")
logger.warning(f"Saving logits & x_embs to {self.args.save}/cached_embs/_{name}.pt")
# @lru_cache(8)
def cal_labels(self, length, labels, idx = None):
'''label编码'''
onehot = torch.zeros([length, self.args.num_labels], device=self.device,
# dtype=self.dtype
)
if idx is not None and len(idx) > 0:
onehot[idx, labels[idx]] = 1
elif length == len(labels):
onehot.scatter_(1, labels.unsqueeze(1), 1)
return onehot
def custom_loss(self, labels, x1, feat, batch_size=0, lambda_1=0.2, lambda_2=0.1, tau=0.1, device=None):
"""
labels: (batch_size,)
x1: (batch_size, embedding_dim) # 假设 x1 是特征表示
is_batch: 如果为True,则分批次计算LSelf和LWeakly;否则正常计算
"""
if device == 'cpu':
labels = labels.to('cpu')
x1 = x1.to('cpu')
# 1. Cross-Entropy Loss (LCE)
y1 = self.criterion(x1, labels)
# y1 = F.cross_entropy(x1, labels, reduction=self.args.loss_reduction, label_smoothing=self.args.label_smoothing)
LCE = torch.log(self.epsilon + y1) - math.log(self.epsilon)
# loss = LCE
# 2. Self-Supervised Loss (LSelf) & Weakly-Supervised Loss (LWeakly)
if torch.any(labels != 0):
if batch_size > 0:
# 分批次计算
n = feat.size(0)
LSelf = 0.0
LWeakly = 0.0
deno = 0
for i in range(0, n, batch_size): # 分成两批计算
end = min(i + batch_size, n)
x1_batch = feat[i:end]
labels_batch = labels[i:end]
if torch.any(labels_batch != 0):
LSelf += self.NTXentLoss(x1_batch, labels_batch)
LWeakly += self.SupConLoss(x1_batch, labels_batch)
deno += 1
if deno > 0:
LSelf /= deno # 平均两批的结果
LWeakly /= deno # 平均两批的结果
else:
#正常计算
LSelf = self.NTXentLoss(feat, labels)
LWeakly = self.SupConLoss(feat, labels)
if LSelf.item() == 0.0 and LWeakly.item() == 0.0:
loss = LCE
else:
loss = 0.6*LCE + lambda_1 * LSelf + lambda_2 * LWeakly
else:
loss = LCE
return loss
def init_loader(self):
'''dataloader,节点采样在这里进行'''
self.graph_loaders = [] # 用于保存每张图的 DataLoader
self.graph_loaders_sec = []
for batch in self.train_data_loader:
batched_graph = batch['graph']#.to(device=self.device)
if self.args.grad_padding > 0:
# 控制采样:低->高,1随机一个节点,-1所有节点
grad_block = [self.args.grad_k for _ in range(self.args.grad_padding)]
if self.args.secsam_method == "nearby":
self.args.grad_padding2 = self.args.grad_padding + 1
grad_sec = [-1 for _ in range(self.args.grad_padding)]
elif self.args.secsam_method == "morehop":
self.args.grad_padding2 = self.args.grad_padding + 2
grad_sec = [self.args.grad_k for _ in range(self.args.grad_padding2)]
else:
grad_sec = []
if self.args.frozen_padding >= 0:
fz_block = [-1 for _ in range(self.args.frozen_padding)]
if self.args.grad_padding2 > 0:
sampler_sec = BiDirectNeighborSampler(fz_block + grad_sec)
graph_loader_sec = dgl.dataloading.DataLoader(
batched_graph, range(batched_graph.number_of_nodes()),sampler_sec,
batch_size=self.args.kernel_size,
shuffle=False,
drop_last=False,
num_workers=self.args.num_workers,
# persistent_workers=True, # 避免 worker 反复重启
worker_init_fn=worker_init_fn, # 让 worker 启动时重定向日志
# pin_memory=True
)
sampler = BiDirectNeighborSampler(fz_block + grad_block)
graph_loader = dgl.dataloading.DataLoader(
batched_graph,range(batched_graph.number_of_nodes()),sampler,
batch_size=self.args.kernel_size,
shuffle=False,
drop_last=False,
num_workers=self.args.num_workers,
# persistent_workers=True,
worker_init_fn=worker_init_fn,
# pin_memory=True
)
else:
sampler = dgl.dataloading.ShaDowKHopSampler(grad_block)
graph_loader = dgl.dataloading.DataLoader(
graph=batched_graph, graph_sampler=sampler,
batch_size=self.args.kernel_size,
shuffle=False,
drop_last=False,
num_workers=self.args.num_workers,
# persistent_workers=True,
worker_init_fn=worker_init_fn,
# pin_memory=True
)
# 将每张图的 DataLoader 添加到列表
self.graph_loaders.append(graph_loader)
if self.args.frozen_padding >= 0:
self.graph_loaders_sec.append(graph_loader_sec)
else:
# TODO: 对整个图进行采样
self.whole_graph = True
# 你可以在这里为单个大图使用DataLoader
pass
@lru_cache(8)
def id_in_parent(self, parent, sub):
'''index transformation in subset'''
if self.whole_graph:
return sub
sorted_parent, sorted_indices = torch.sort(parent)
sorted_pos = torch.searchsorted(sorted_parent, sub)
return sorted_indices[sorted_pos]
def get_metrics(self, y_true, y_pred, y_proba, metrics=None):
m = {}
y_true = to_numpy(y_true)
y_pred = to_numpy(y_pred)
y_proba = to_numpy(y_proba)
ytnan = np.isnan(y_true)
ypnan = np.isnan(y_proba)
nan_mask = ~(ytnan | ypnan) # 找到所有非 NaN 的索引
# 仅在发现 NaN 时才进行筛选,并记录 NaN 来源
if not nan_mask.all():
if ytnan.any():
logger.info(f"Found {ytnan.sum()} NaN in y_true")
if ypnan.any():
logger.info(f"Found {ypnan.sum()} NaN in y_proba")
y_true = y_true[nan_mask]
y_proba = y_proba[nan_mask]
for k, metric in metrics.items():
m[k] = metric(y_true,y_pred,y_proba)
return m
# @torch.no_grad()
# def evaluate(self, evaluator,epoch, e2e):
# # 设置模型为评估模式
# self.model_gnn.eval()
# if self.model_lm and e2e:
# self.model_lm.eval()
# # 初始化评估指标和损失
# preds = []
# # onehot_labels = self.cal_labels(self.n_node, self.labels)
# onehot_labels = self.cal_labels(self.n_node, [], None)
# if e2e:
# self.out_lm, self.feat_static = self.get_feat()
# # 遍历所有评估批次
# train_loss, val_loss, test_loss = 0.0, 0.0, 0.0
# n_train = len(self.data['train']['graphs'])
# n_val = len(self.data['valid']['graphs'])
# n_test = len(self.data['test']['graphs'])
# # with torch.no_grad():
# for batch in self.all_data_loader: # 获取每个批次
# node_ids = batch['graph'].ndata['uid'] # 获取当前图的节点ID
# batched_graph = batch['graph'].to(device=self.device) # 当前批次的DGL图
# node_type_feat = batch['graph'].ndata['type'].to(device=self.device)
# edge_type_feat = batch['graph'].edata['type'].to(device=self.device)
# # if e2e:
# # feat_eval = self.get_feat(batch=batch, device=self.device)
# # else:
# feat_eval = self.feat_static[node_ids].to(self.device) # 获取当前批次的特征
# out_lm = self.out_lm[node_ids].to(self.device)
# # loss = self.custom_loss(self.labels[node_ids], out_lm, feat = feat_eval, batch_size=256).item()
# # 如果使用标签,合并标签特征
# if self.args.use_labels:
# feat_eval = torch.cat([feat_eval, onehot_labels[node_ids]], dim=-1)
# # feat_eval = feat_eval.to(torch.float32) # 确保数据类型正确
# feat_eval = torch.cat([node_type_feat, feat_eval], dim=-1)
# # 获取预测结果
# nnan = torch.isnan(feat_eval).sum()
# if nnan > 0:
# logger.warning(f"{torch.isnan(feat_eval).sum()} NaN in feat_eval")
# # 如果有标签迭代,进行n_label_iters次标签更新
# if self.args.n_label_iters > 0:
# gnn_pred = self.model_gnn(batched_graph, feat_eval, edge_type_feat)
# # unlabel_idx = torch.cat([torch.tensor(self.val_idx), torch.tensor(self.test_idx)])
# for _ in range(self.args.n_label_iters):
# # gnn_pred = F.softmax(gnn_pred, dim=-1)
# feat_eval[:,-self.args.num_labels:] = F.softmax(gnn_pred, dim=-1)
# gnn_pred, gnn_feat = self.model_gnn(batched_graph, feat_eval, edge_type_feat, rt_feat = True)
# else:
# gnn_pred, gnn_feat = self.model_gnn(batched_graph, feat_eval, edge_type_feat, rt_feat = True)
# pred = 0.5*(gnn_pred + out_lm)
# if(self.args.lm_x):
# pred = out_lm
# if(self.args.gnn_x):
# pred = gnn_pred
# # 存储预测结果和标签
# preds.append(pred)
# preds = torch.cat(preds, dim=0)
# # labels = torch.cat(labels, dim=0)
# y_probs = preds.softmax(dim=1)[:, 1]
# y_preds = (y_probs >= 0.4).long()
# if(self.args.lm_x):
# y_preds = (y_probs >= 0.6).long()
# # 计算损失
# train_metrics=[]
# val_metrics=[]
# test_metrics=[]
# if n_train:
# train_loss = self.criterion(preds[self.train_idx], self.labels[self.train_idx]).item()
# train_metrics = self.get_metrics(self.labels[self.train_idx], y_preds[self.train_idx], y_probs[self.train_idx], self.metrics)
# if n_val:
# val_loss = self.criterion(preds[self.val_idx], self.labels[self.val_idx]).item()
# val_metrics = self.get_metrics(self.labels[self.val_idx], y_preds[self.val_idx], y_probs[self.val_idx], self.metrics)
# if n_test:
# test_loss = self.criterion(preds[self.test_idx], self.labels[self.test_idx]).item()
# test_metrics = self.get_metrics(self.labels[self.test_idx], y_preds[self.test_idx], y_probs[self.test_idx],self.metrics_test)
# # 保存每个节点的预测结果
# if(self.args.test_only):
# # 构建 DataFrame
# node_results_df = pd.DataFrame({
# 'node_id': list(range(len(y_preds))), # 假设节点按顺序编号
# 'y_true': self.labels.cpu().numpy(),
# 'y_pred': y_preds.cpu().numpy(),
# 'y_prob': y_probs.detach().cpu().numpy(),
# })
# # 创建输出目录(可选)
# output_dir = "./out/test_pred"
# os.makedirs(output_dir, exist_ok=True)
# # 构建文件路径,带上 epoch 信息便于追踪
# output_path = os.path.join(output_dir, f"cwe_node_preds.csv")
# # 保存为 CSV
# node_results_df.to_csv(output_path, index=False, encoding='utf-8-sig')
# logger.info(f"节点预测结果已保存到: {output_path}")
# torch.cuda.empty_cache()
# # 返回评估结果,包括准确率、损失和其他指标
# return train_metrics, val_metrics, test_metrics, train_loss, val_loss, test_loss, preds
@torch.no_grad()
def evaluate(self, evaluator, epoch, e2e):
# =====================================================
# 0. 模式判断
# =====================================================
only_lm = self.args.lm_x
only_gnn = self.args.gnn_x
assert not (only_lm and only_gnn), \
"错误:lm_x 和 gnn_x 不能同时为 True!"
# =====================================================
# 1. 设置 eval 模式
# =====================================================
self.model_gnn.eval()
if self.model_lm:
self.model_lm.eval()
# =====================================================
# 2. 如果 e2e,需要重新提取 LM 特征
# =====================================================
if e2e:
self.out_lm, self.feat_static = self.get_feat()
preds = []
# =====================================================
# 3. 遍历所有 batch
# =====================================================
for batch in self.all_data_loader:
graph = batch["graph"].to(self.device)
node_ids = graph.ndata["uid"]
node_type_feat = graph.ndata["type"].to(self.device)
edge_type_feat = graph.edata["type"].to(self.device)
# =====================================================
# ✅ Mode A: Only LM(只用语言模型)
# =====================================================
if only_lm:
input_ids = batch["input_ids"].to(self.device)
attention_mask = batch["attention_mask"].to(self.device)
# eval 模式
self.model_lm.eval()
self.node_classifier.eval()
# forward LM
out_lm, lm_feat = self.model_lm(
input_ids,
attention_mask,
return_hidden=True
)
# CLS pooling
if lm_feat.dim() == 3:
lm_feat = lm_feat[:, 0, :]
# ✅node logits
pred = self.node_classifier(lm_feat)
preds.append(pred)
continue
# =====================================================
# ✅ Mode B: Only GNN(只用图模型)
# =====================================================
if only_gnn:
# frozen LM 特征作为输入
feat_eval = self.feat_static[node_ids.cpu()].to(self.device)
# 拼接节点类型
feat_eval = torch.cat([node_type_feat, feat_eval], dim=-1)
# forward GNN
gnn_pred, gnn_feat = self.model_gnn(
graph, feat_eval, edge_type_feat, rt_feat=True
)
pred = gnn_pred
preds.append(pred)
continue # ⚠️关键:跳过 LM fusion
# =====================================================
# ✅ Mode C: 融合模式(LM + GNN)
# =====================================================
# --- LM 输出 ---
feat_eval = self.feat_static[node_ids.cpu()].to(self.device)
out_lm = self.out_lm[node_ids.cpu()].to(self.device)
feat_eval = torch.cat([node_type_feat, feat_eval], dim=-1)
# --- forward GNN ---
gnn_pred, gnn_feat = self.model_gnn(
graph, feat_eval, edge_type_feat, rt_feat=True
)
# --- 融合预测 ---
pred = 0.5 * (gnn_pred + out_lm)
preds.append(pred)
# =====================================================
# 4. 拼接所有预测
# =====================================================
preds = torch.cat(preds, dim=0)
# =====================================================
# 5. 计算概率与分类结果
# =====================================================
y_probs = preds.softmax(dim=1)[:, 1]
# 阈值可调
threshold = 0.4
y_preds = (y_probs >= threshold).long()
# =====================================================
# 6. 计算指标
# =====================================================
train_loss, val_loss, test_loss = 0.0, 0.0, 0.0
train_metrics, val_metrics, test_metrics = [], [], []
if len(self.train_idx) > 0:
train_loss = self.criterion(
preds[self.train_idx],
self.labels[self.train_idx]
).item()
train_metrics = self.get_metrics(
self.labels[self.train_idx],
y_preds[self.train_idx],
y_probs[self.train_idx],
self.metrics
)
if len(self.val_idx) > 0:
val_loss = self.criterion(
preds[self.val_idx],
self.labels[self.val_idx]
).item()
val_metrics = self.get_metrics(
self.labels[self.val_idx],
y_preds[self.val_idx],
y_probs[self.val_idx],
self.metrics
)
if len(self.test_idx) > 0:
test_loss = self.criterion(
preds[self.test_idx],
self.labels[self.test_idx]
).item()
test_metrics = self.get_metrics(
self.labels[self.test_idx],
y_preds[self.test_idx],
y_probs[self.test_idx],
self.metrics_test
)
# =====================================================
# 7. test_only 保存结果
# =====================================================
if self.args.test_only:
node_results_df = pd.DataFrame({
"node_id": list(range(len(y_preds))),
"y_true": self.labels.cpu().numpy(),
"y_pred": y_preds.cpu().numpy(),
"y_prob": y_probs.detach().cpu().numpy(),
})
output_dir = "./out/test_pred"
os.makedirs(output_dir, exist_ok=True)
output_path = os.path.join(output_dir, "cwe_node_preds.csv")
node_results_df.to_csv(output_path, index=False, encoding="utf-8-sig")
logger.info(f"节点预测结果已保存到: {output_path}")
torch.cuda.empty_cache()
return (
train_metrics, val_metrics, test_metrics,
train_loss, val_loss, test_loss,
preds
)
def load_data(self):
"""加载多个图数据并根据训练集、验证集、测试集分割"""
if self.args.test_only:
#data_path = f"processed_data/{self.args.CWE_name}_all_dataset.pt"
data_path = f"processed_data/{self.args.dataset}_all_dataset.pt"