-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathllm.py
1601 lines (1321 loc) · 75.5 KB
/
llm.py
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 argparse
import logging
import random
import shutil
import time
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm, trange
import transformers
try:
from transformers import (
ConstantLRSchedule, WarmupLinearSchedule, WarmupConstantSchedule)
except:
from transformers import get_constant_schedule, get_constant_schedule_with_warmup, get_linear_schedule_with_warmup
import wandb
from utils import data_utils
from utils import utils
import numpy as np
import os
import sys
import subprocess
# llm
# from transformers import T5Tokenizer, T5Model
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, AutoModelForCausalLM
from sklearn import metrics
# peft
from peft import get_peft_config, get_peft_model, PromptTuningInit, PromptTuningConfig, TaskType, PeftType, LoraConfig
# gnn
import gnn
import math
from torch_geometric.nn import GATConv, GIN
from moe import MoE
try:
import pickle
except:
pass
logger = logging.getLogger(__name__)
def set_random_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.random.manual_seed(seed)
torch.backends.cudnn.determinstic = True
def load_data(args, devices, kg):
one_process_at_a_time = args.data_loader_one_process_at_a_time
if args.local_rank != -1 and one_process_at_a_time:
for p_rank in range(args.world_size):
if args.local_rank != p_rank: # Barrier
torch.distributed.barrier()
dataset = data_utils.DataLoader(args, args.train_statements, args.train_adj,
args.dev_statements, args.dev_adj,
args.test_statements, args.test_adj,
batch_size=args.batch_size, eval_batch_size=args.eval_batch_size,
device=devices,
model_name=args.encoder,
max_node_num=args.max_node_num, max_seq_length=args.max_seq_len,
is_inhouse=args.inhouse, inhouse_train_qids_path=args.inhouse_train_qids,
subsample=args.subsample, n_train=args.n_train, debug=args.debug, cxt_node_connects_all=args.cxt_node_connects_all, kg=kg)
if args.local_rank == p_rank: # End of barrier
torch.distributed.barrier()
else:
dataset = data_utils.DataLoader(args, args.train_statements, args.train_adj,
args.dev_statements, args.dev_adj,
args.test_statements, args.test_adj,
batch_size=args.batch_size, eval_batch_size=args.eval_batch_size,
device=devices,
model_name=args.encoder,
max_node_num=args.max_node_num, max_seq_length=args.max_seq_len,
is_inhouse=args.inhouse, inhouse_train_qids_path=args.inhouse_train_qids,
subsample=args.subsample, n_train=args.n_train, debug=args.debug, cxt_node_connects_all=args.cxt_node_connects_all, kg=kg)
return dataset
class GAT(torch.nn.Module):
def __init__(self, args, in_channels, hidden_channels, out_channels, n_ntype, n_etype, heads, gnn_layers=3):
super().__init__()
self.gnn_layers = gnn_layers
if args.use_relational_gnn:
assert gnn_layers >= 2
self.middle_conv_list = nn.ModuleList([gnn.GATConvE(args, hidden_channels, n_ntype, n_etype) for _ in range(gnn_layers-1)])
self.end_conv = gnn.GATConvE(args, hidden_channels, n_ntype, n_etype)
else:
self.start_conv = GATConv(in_channels, hidden_channels, heads, dropout=0.6)
if gnn_layers >= 3:
self.middle_conv_list = nn.ModuleList([GATConv(hidden_channels * heads, hidden_channels, heads=heads, dropout=0.6) for i in range(gnn_layers-2)])
self.end_conv = GATConv(hidden_channels * heads, out_channels, heads=1, concat=False, dropout=0.6)
def forward(self, x, edge_index, edge_type, node_type):
if args.use_relational_gnn:
x = F.dropout(x, p=0.6, training=self.training)
for middle_conv in self.middle_conv_list:
x = middle_conv(x, edge_index, edge_type, node_type)
x = F.elu(x)
x = F.dropout(x, p=0.6, training=self.training)
x = self.end_conv(x, edge_index, edge_type, node_type)
else:
x = F.dropout(x, p=0.6, training=self.training)
x = self.start_conv(x, edge_index)
# middle layers
if self.gnn_layers >= 3:
for middle_conv in self.middle_conv_list:
x = F.elu(x)
x = F.dropout(x, p=0.6, training=self.training)
x = middle_conv(x, edge_index)
# output layer
x = F.elu(x)
x = F.dropout(x, p=0.6, training=self.training)
x = self.end_conv(x, edge_index)
return x
class ShallowQFormer(nn.Module):
def __init__(self, dim_input, n_query, n_layers=1): # , dim_output
super(ShallowQFormer, self).__init__()
self.n_query = n_query
self.queries = nn.Parameter(torch.randn(n_query, dim_input), requires_grad=True)
self.model = nn.TransformerDecoder(
nn.TransformerDecoderLayer(d_model=dim_input, dim_feedforward=dim_input * 4, nhead=8, batch_first=True), # , dropout=0.2
num_layers=n_layers
)
def forward(self, input_feats, memory_mask):
# input_feats: shape B x n_patch x dim_input
memory_mask = memory_mask.repeat(8, 1, self.n_query)
memory_mask = torch.transpose(memory_mask, 2, 1)
print('tgt: ', self.queries.unsqueeze(0).expand(len(input_feats), *self.queries.shape).shape)
x = self.model(tgt=self.queries.unsqueeze(0).expand(len(input_feats), *self.queries.shape), memory=input_feats, memory_mask=memory_mask)
x = F.dropout(x, p=0.2, training=self.training)
return x
class CrossModalityPooler(nn.Module):
def __init__(self, args, dim_input, n_query, n_layers=1): # , dim_output
super(CrossModalityPooler, self).__init__()
self.n_query = n_query
self.dim_input = dim_input
self.queries = nn.Parameter(torch.randn(n_query, dim_input), requires_grad=True)
self.model = nn.TransformerDecoder(
nn.TransformerDecoderLayer(d_model=dim_input, dim_feedforward=dim_input * 4, nhead=8, batch_first=True), # , dropout=0.2
num_layers=n_layers
)
def forward(self, input_feats, memory_mask, valid_text_emb):
# text input
valid_text_emb = valid_text_emb.unsqueeze(1)
if args.token_dim < self.dim_input:
raise ValueError("Need a mapping to increase the dimension of valid_text_emb to match self.dim_input")
valid_text_emb = valid_text_emb.view(valid_text_emb.size(0), -1, self.dim_input)
cur_diff_between_dim_input_and_token_dim = args.token_dim / self.dim_input
valid_text_emb = valid_text_emb.repeat(args.num_choice, self.n_query, 1)
# memory mask
memory_mask = memory_mask.repeat(8, 1, int(self.n_query*cur_diff_between_dim_input_and_token_dim))
memory_mask = torch.transpose(memory_mask, 2, 1)
x = self.model(tgt=valid_text_emb, memory=input_feats, memory_mask=memory_mask)
return x
class CrossModalityMHA(nn.Module):
def __init__(self, args, dim_input, n_layers=1): # , dim_output
super(CrossModalityMHA, self).__init__()
self.dim_input = dim_input
self.model = nn.TransformerDecoder(
nn.TransformerDecoderLayer(d_model=dim_input, dim_feedforward=dim_input * 4, nhead=8, batch_first=True),
num_layers=n_layers
)
self.linear_text_emb = nn.Sequential(nn.Linear(args.token_dim, dim_input), gnn.GELU(), nn.Linear(dim_input, dim_input))
def forward(self, input_gnn_feats, input_gnn_mask, text_emb, text_mask):
text_emb = text_emb.to(torch.float32)
text_mask = text_mask.to(torch.float32)
text_emb = text_emb.repeat(args.num_choice, 1, 1)
text_mask = text_mask.repeat(args.num_choice, 1)
text_emb = self.linear_text_emb(text_emb)
x = self.model(tgt=input_gnn_feats, tgt_key_padding_mask=input_gnn_mask, memory=text_emb, memory_key_padding_mask=text_mask)
return x
class CrossModalityMHA_for_text(nn.Module):
def __init__(self, args, dim_input, n_layers=1):
super(CrossModalityMHA_for_text, self).__init__()
self.dim_input = dim_input
self.model = nn.TransformerDecoder(
nn.TransformerDecoderLayer(d_model=args.token_dim, dim_feedforward=args.token_dim * 4, nhead=8, batch_first=True),
num_layers=n_layers
)
self.linear_gnn_emb = nn.Sequential(nn.Linear(dim_input, args.token_dim), gnn.GELU(), nn.Linear(args.token_dim, args.token_dim))
def forward(self, input_gnn_feats, input_gnn_mask, text_emb, text_mask=None):
text_emb = text_emb.to(torch.float32)
if text_mask != None:
text_mask = text_mask.to(torch.float32)
input_gnn_feats = input_gnn_feats.view(text_emb.size(0), -1, input_gnn_feats.size(2))
input_gnn_mask = input_gnn_mask.view(text_emb.size(0), -1)
input_gnn_feats = self.linear_gnn_emb(input_gnn_feats)
if text_mask == None:
x = self.model(tgt=text_emb, memory=input_gnn_feats, memory_key_padding_mask=input_gnn_mask)
else:
x = self.model(tgt=text_emb, tgt_key_padding_mask=text_mask, memory=input_gnn_feats, memory_key_padding_mask=input_gnn_mask)
return x
class MyGNN(nn.Module):
def __init__(self, args, cp_emb):
super(MyGNN, self).__init__()
# init gat
self.gnn_layers = args.gnn_layers
self.hidden_size = args.gnn_dim
self.n_ntype = args.n_ntype
self.n_etype = args.n_etype
args.gnn_edge_dim = int(args.gnn_dim / 4)
self.gat = GAT(args, self.hidden_size, self.hidden_size, self.hidden_size, self.n_ntype, self.n_etype, heads=4, gnn_layers=self.gnn_layers)
# init concept embedding layer
self.concept_num = args.concept_num
self.concept_in_dim = args.concept_in_dim
self.freeze_ent_emb = args.freeze_ent_emb
self.concept_emb = gnn.OriginConceptEmbedding(concept_num=self.concept_num, concept_out_dim=self.hidden_size, concept_in_dim=self.concept_in_dim, pretrained_concept_emb=cp_emb, freeze_ent_emb=self.freeze_ent_emb)
self.activation = gnn.GELU()
self.p_dropout_gnn = args.p_dropout_gnn
if args.cross_modality_layers > 0:
self.cross_modality_MHA = CrossModalityMHA(args, self.hidden_size, n_layers=args.cross_modality_layers)
# init projector
if args.moe_experts:
args.num_activated_experts = args.moe_experts
assert args.num_activated_experts <= args.moe_experts
self.projector = MoE(input_size=self.hidden_size, hidden_size=self.hidden_size, output_size=args.token_dim, num_experts=args.moe_experts, k=args.num_activated_experts, noisy_gating=True)
else:
self.projector = nn.Sequential(nn.Linear(self.hidden_size, self.hidden_size), gnn.GELU(), nn.Linear(self.hidden_size, args.token_dim))
# link prediction task
if args.link_task:
if args.link_decoder == 'DistMult':
self.link_pred = gnn.DistMultDecoder(args, num_rels=self.n_etype, h_dim=self.hidden_size)
elif args.link_decoder == 'TransE':
self.link_pred = gnn.TransEDecoder(args, num_rels=self.n_etype, h_dim=self.hidden_size)
elif args.link_decoder == 'RotatE':
self.link_pred = gnn.RotatEDecoder(args, num_rels=self.n_etype, h_dim=self.hidden_size)
else:
raise NotImplementedError
if args.link_proj_headtail:
self.link_pred_proj = nn.Linear(self.hidden_size, self.hidden_size)
if args.link_normalize_headtail == 3:
self.link_pred_emb_LayerNorm = nn.LayerNorm(self.hidden_size)
def batch_graph(self, edge_index_init, edge_type_init, pos_triples_init, neg_nodes_init, n_nodes):
"""
edge_index_init: list of (n_examples, ). each entry is torch.tensor(2, E?) ==> [2, total_E]
edge_type_init: list of (n_examples, ). each entry is torch.tensor(E?, ) ==> [total_E, ]
pos_triples_init: list of (n_examples, ). each entry is [h,r,t] where h/r/t: torch.tensor(n_triple?, ) ==> [3, `total_n_triple`]
neg_nodes_init: list of (n_examples, ). each entry is torch.tensor(n_triple?, n_neg) ==> [`total_n_triple`, n_neg]
"""
n_examples = len(edge_index_init)
edge_index = [edge_index_init[_i_] + _i_ * n_nodes for _i_ in range(n_examples)]
edge_index = torch.cat(edge_index, dim=1) # [2, total_E]
edge_type = torch.cat(edge_type_init, dim=0) # [total_E, ]
pos_triples = [[], [], []]
for _i_ in range(n_examples):
h = pos_triples_init[_i_][0] + _i_ * n_nodes # tensor[n_triple?,]
r = pos_triples_init[_i_][1] # tensor[n_triple?,]
t = pos_triples_init[_i_][2] + _i_ * n_nodes # tensor[n_triple?,]
pos_triples[0].append(h)
pos_triples[1].append(r)
pos_triples[2].append(t)
pos_triples = torch.stack([torch.cat(item) for item in pos_triples]) # [3, `total_n_triple`] where `total_n_triple` is sum of n_triple within batch
assert pos_triples.size(0) == 3
neg_nodes = [neg_nodes_init[_i_] + _i_ * n_nodes for _i_ in range(n_examples)]
neg_nodes = torch.cat(neg_nodes) # [`total_n_triple`, n_neg]
assert neg_nodes.dim() == 2
assert pos_triples.size(1) == neg_nodes.size(0)
return edge_index, edge_type, pos_triples, neg_nodes
def calc_link_loss(self, pos_triples, neg_nodes, gnn_output):
# pos_triples: [3, `total_n_triple`], neg_nodes: [`total_n_triple`, n_neg]
pos_samples = pos_triples # [3, `total_n_triple`]
_n_neg = neg_nodes.size(1)
head_negative_sample = neg_nodes[:, :_n_neg//2] # [`total_n_triple`, n_neg//2]
tail_negative_sample = neg_nodes[:, _n_neg//2:_n_neg//2*2] # [`total_n_triple`, n_neg//2]
_bs, _, gnn_dim = gnn_output.size()
embs = gnn_output.view(-1, gnn_dim) # [`total_n_nodes`, gnn_dim]
if args.link_proj_headtail:
embs = self.link_pred_proj(embs)
if args.link_normalize_headtail == 1:
embs = embs / torch.norm(embs, p=2, dim=1, keepdim=True).detach()
elif args.link_normalize_headtail == 2:
embs = torch.tanh(embs)
elif args.link_normalize_headtail == 3:
embs = self.link_pred_emb_LayerNorm(embs)
positive_score = self.link_pred(embs, pos_samples) # [`total_n_triple`, 1]
head_neg_scores = self.link_pred(embs, (pos_samples, head_negative_sample), mode='head-batch')
tail_neg_scores = self.link_pred(embs, (pos_samples, tail_negative_sample), mode='tail-batch')
negative_score = torch.cat([head_neg_scores, tail_neg_scores], dim=-1) # [`total_n_triple`, total_n_neg]
scores = (positive_score, negative_score)
link_loss, pos_link_loss, neg_link_loss = self.link_pred.loss(scores)
return link_loss
def forward(self, graph_inputs, text_to_GNN_inputs):
edge_index, edge_type, pos_triples, neg_nodes = [sum(x, []) for x in graph_inputs[:4]]
concept_ids, node_type_ids, node_scores, adj_lengths = [x.reshape(x.size(0) * x.size(1), *x.size()[2:]) for x in graph_inputs[4:]]
edge_index, edge_type, pos_triples, neg_nodes = self.batch_graph(edge_index, edge_type, pos_triples, neg_nodes, concept_ids.size(1))
# GNN inputs
concept_ids[concept_ids == 0] = self.concept_num + 2
gnn_input = self.concept_emb(concept_ids - 1).to(node_type_ids.device)
gnn_input[:, 0] = 0
X = gnn_input
_X = X.view(-1, X.size(2)).contiguous() # [`total_n_nodes`, d_node] where `total_n_nodes` = b_size * n_node
_node_type = node_type_ids.view(-1).contiguous() # [`total_n_nodes`, ]
# regular GAT
_X = self.gat(_X, edge_index, edge_type, _node_type)
X = _X.view(node_type_ids.size(0), -1, node_type_ids.size(1), self.hidden_size) # [4*batch_size, final num_virtual_tokens/4 (only last layer or multi-layer output), n_node, dim]
num_tokens = int(args.num_choice * X.size(1))
X = X.squeeze() # squeeze if we only have 4 gnn tokens
gnn_output = X
# obtain node_mask (1 means masked out)
node_mask = torch.arange(node_type_ids.size(1), device=node_type_ids.device) >= adj_lengths.unsqueeze(1) # [4bs, 200 (nodes)]
if num_tokens > args.num_choice:
# include node_mask for 3 layers concat output
valid_node_mask = (~node_mask).float().unsqueeze(2).unsqueeze(1)
memory_mask = node_mask.unsqueeze(2).unsqueeze(1)
else:
valid_node_mask = (~node_mask).float().unsqueeze(2)
memory_mask = node_mask.unsqueeze(2)
gnn_output = gnn_output * valid_node_mask # [4bs, 200, hidden_dim]
# link prediction
if args.link_task:
link_loss = self.calc_link_loss(pos_triples, neg_nodes, gnn_output)
else:
link_loss = 0.0
# Cross Modality MHA: input GNN features, memory is LLM tokens
if args.cross_modality_layers > 0:
inputs_embeds, attention_mask = text_to_GNN_inputs
attention_mask_for_padding = ~attention_mask.to(torch.bool)
graph_vecs = self.cross_modality_MHA(gnn_output, node_mask, inputs_embeds, attention_mask_for_padding)
else:
graph_vecs = gnn_output
# average pooling
graph_vecs = graph_vecs * valid_node_mask
graph_vecs = graph_vecs.sum(1) / ((graph_vecs != 0).sum(1) + 1e-10)
graph_vecs = graph_vecs.unsqueeze(1)
graph_vecs = graph_vecs.view(-1, int(graph_vecs.size(1))*args.num_choice, graph_vecs.size(2))
# projector
if args.no_projector:
try:
graph_vecs = graph_vecs.view(graph_vecs.size(0), -1, args.token_dim)
# for odd token numbers
except:
if args.dataset == 'bioasq':
temp_solution = torch.zeros(graph_vecs.size(0), 2, graph_vecs.size(2)).to(graph_vecs.device)
else:
temp_solution = torch.zeros(graph_vecs.size(0), 1, graph_vecs.size(2)).to(graph_vecs.device)
graph_vecs = torch.cat([graph_vecs, temp_solution], dim=1)
graph_vecs = graph_vecs.view(graph_vecs.size(0), -1, args.token_dim)
moe_loss = 0.0
else:
if args.moe_experts:
temp_bs = graph_vecs.size(0)
graph_vecs = graph_vecs.view(-1, graph_vecs.size(-1))
graph_vecs, moe_loss = self.projector(graph_vecs)
graph_vecs = graph_vecs.view(temp_bs, -1, graph_vecs.size(-1))
else:
graph_vecs = self.projector(graph_vecs)
moe_loss = 0.0
if args.use_cross_modality_for_text:
return graph_vecs, gnn_output, node_mask, attention_mask_for_padding
return graph_vecs, link_loss, moe_loss
class MyModel(nn.Module):
def __init__(self, args, cp_emb):
super(MyModel, self).__init__()
num_device = torch.cuda.device_count()
if num_device == 1:
my_max_memory = {0: "12GB"}
elif num_device == 2:
my_max_memory = {0: "10GB", 1: "12GB"}
elif num_device == 3:
my_max_memory = {0: "0GB", 1: "12GB", 2: "12GB"}
elif num_device == 4:
my_max_memory = {0: "0GB", 1: "12GB", 2: "12GB", 3: "12GB"}
else:
my_max_memory = {}
my_max_memory[0] = "0GB"
for i in range(1, 8):
my_max_memory[i] = "12GB"
if args.prompt == False:
self.llm = AutoModelForSeq2SeqLM.from_pretrained(args.encoder, torch_dtype=torch.bfloat16, device_map='auto')
self.llm.gradient_checkpointing_enable()
elif args.prompt == 'regular':
self.llm = AutoModelForSeq2SeqLM.from_pretrained(args.encoder, torch_dtype=torch.bfloat16, device_map='auto')
self.llm.gradient_checkpointing_enable()
else:
self.llm = AutoModelForSeq2SeqLM.from_pretrained(args.encoder, torch_dtype=torch.bfloat16, device_map='auto', max_memory=my_max_memory)
self.llm.gradient_checkpointing_enable()
print(self.llm.hf_device_map)
# LoRA
if args.lora:
peft_config = LoraConfig(
r=16,
lora_alpha=32,
target_modules=["q", "v"],
lora_dropout=0.05,
bias="none",
task_type=TaskType.SEQ_2_SEQ_LM
)
self.llm = get_peft_model(self.llm, peft_config)
print('using lora !!!!')
# word_embeddings
for named_param, value in list(self.llm.named_parameters()):
if named_param == 'shared.weight' or named_param == 'base_model.model.shared.weight': # t5
self.word_embeddings = self.llm.get_submodule(named_param.replace(".weight", ""))
args.token_dim = self.word_embeddings.weight.shape[1]
break
try:
print('self.word_embeddings: ', self.word_embeddings)
except:
raise ValueError("self.word_embeddings cannot be found")
# regular prompt
if args.prompt == 'regular':
self.num_virtual_tokens = args.num_virtual_tokens
if args.use_wandb:
wandb.run.summary["num_virtual_tokens"] = self.num_virtual_tokens
self.token_dim = self.word_embeddings.weight.shape[1]
# manual prompt word initialization
init_text = 'Choose the best option to answer the question.'
init_tokenizer = AutoTokenizer.from_pretrained(args.encoder)
init_token_ids = init_tokenizer(init_text)["input_ids"]
# Trim or iterate until num_text_tokens matches total_virtual_tokens
num_text_tokens = len(init_token_ids)
if num_text_tokens > self.num_virtual_tokens:
init_token_ids = init_token_ids[:self.num_virtual_tokens]
elif num_text_tokens < self.num_virtual_tokens:
num_reps = math.ceil(self.num_virtual_tokens / num_text_tokens)
init_token_ids = init_token_ids * num_reps
init_token_ids = init_token_ids[:self.num_virtual_tokens]
self.prompt = nn.Parameter(self.word_embeddings(torch.LongTensor(init_token_ids)).detach().clone().to(torch.float32))
# GNN prompt
elif args.prompt == 'gnn':
self.gnn_model = MyGNN(args, cp_emb).to('cuda:0') # self.llm.device
print('self.gnn_model: ', self.gnn_model)
# how many tokens we get from gnn output
self.record_gnn_num_virtual_tokens = True
if args.use_cross_modality_for_text:
self.cross_modality_MHA_for_text = CrossModalityMHA_for_text(args, args.gnn_dim, n_layers=args.cross_modality_for_text_layers)
self.cross_modality_MHA_for_text.to(self.llm.device)
if args.dataset_level_prompt:
# prompt
self.num_virtual_tokens = args.num_virtual_tokens
self.token_dim = self.word_embeddings.weight.shape[1]
# manual prompt word initialization
init_text = 'Choose the best option to answer the question based on the context. Context:'
init_tokenizer = AutoTokenizer.from_pretrained(args.encoder)
init_token_ids = init_tokenizer(init_text)["input_ids"]
# Trim or iterate until num_text_tokens matches total_virtual_tokens
num_text_tokens = len(init_token_ids)
if num_text_tokens > self.num_virtual_tokens:
init_token_ids = init_token_ids[:self.num_virtual_tokens]
elif num_text_tokens < self.num_virtual_tokens:
num_reps = math.ceil(self.num_virtual_tokens / num_text_tokens)
init_token_ids = init_token_ids * num_reps
init_token_ids = init_token_ids[:self.num_virtual_tokens]
self.prompt = nn.Parameter(self.word_embeddings(torch.LongTensor(init_token_ids)).detach().clone().to(torch.float32))
def generate(self, input_ids, attention_mask, graph_inputs):
with torch.no_grad():
inputs_embeds = self.word_embeddings(input_ids)
if args.prompt == 'regular':
input_prompt = self.prompt.repeat(inputs_embeds.size(0), 1, 1)
inputs_embeds = torch.cat((input_prompt, inputs_embeds), dim=1)
prefix_attention_mask = torch.ones(inputs_embeds.size(0), self.num_virtual_tokens).to(attention_mask.device)
attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=1)
elif args.prompt == 'gnn':
# prepare for cross-modality attention
text_to_GNN_inputs = inputs_embeds.to('cuda:0'), attention_mask.to('cuda:0')
# attention from gnn to llm
if args.use_cross_modality_for_text:
# gnn to llm attention: attention on an additional token
input_prompt, gnn_output, node_mask, attention_mask_for_padding = self.gnn_model(graph_inputs, text_to_GNN_inputs)
input_prompt = input_prompt.to(inputs_embeds.device)
gnn_output = gnn_output.to(inputs_embeds.device)
node_mask = node_mask.to(inputs_embeds.device)
attention_mask_for_padding = attention_mask_for_padding.to(inputs_embeds.device)
valid_text_emb = inputs_embeds * attention_mask.unsqueeze(2).to(inputs_embeds.device)
valid_text_emb = valid_text_emb.sum(1) / ((valid_text_emb != 0).sum(1) + 1e-10)
valid_text_emb = valid_text_emb.unsqueeze(1)
special_token_gnn_to_llm_embeds = self.cross_modality_MHA_for_text(gnn_output, node_mask, valid_text_emb)
inputs_embeds = torch.cat((input_prompt, special_token_gnn_to_llm_embeds, inputs_embeds), dim=1)
prefix_attention_mask = torch.ones(inputs_embeds.size(0), input_prompt.size(1)+special_token_gnn_to_llm_embeds.size(1)).to(attention_mask.device)
# NO attention from gnn to llm
else:
gnn_input_prompt, _, _ = self.gnn_model(graph_inputs, text_to_GNN_inputs)
gnn_input_prompt = gnn_input_prompt.to(inputs_embeds.device)
gnn_prefix_attention_mask = torch.ones(inputs_embeds.size(0), gnn_input_prompt.size(1)).to(attention_mask.device)
if args.dataset_level_prompt:
dataset_level_input_prompt = self.prompt.repeat(inputs_embeds.size(0), 1, 1)
dataset_level_prefix_attention_mask = torch.ones(dataset_level_input_prompt.size(0), self.num_virtual_tokens).to(attention_mask.device)
inputs_embeds = torch.cat((dataset_level_input_prompt, gnn_input_prompt, inputs_embeds), dim=1)
attention_mask = torch.cat((dataset_level_prefix_attention_mask, gnn_prefix_attention_mask, attention_mask), dim=1)
else:
inputs_embeds = torch.cat((gnn_input_prompt, inputs_embeds), dim=1)
attention_mask = torch.cat((gnn_prefix_attention_mask, attention_mask), dim=1)
return self.llm.generate(inputs_embeds=inputs_embeds, attention_mask=attention_mask, max_new_tokens=30)
def forward(self, input_ids, attention_mask, labels, graph_inputs):
inputs_embeds = self.word_embeddings(input_ids)
if args.prompt == 'regular':
input_prompt = self.prompt.repeat(inputs_embeds.size(0), 1, 1)
inputs_embeds = torch.cat((input_prompt, inputs_embeds), dim=1)
prefix_attention_mask = torch.ones(inputs_embeds.size(0), self.num_virtual_tokens).to(attention_mask.device)
attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=1)
elif args.prompt == 'gnn':
# prepare for cross-modality attention
text_to_GNN_inputs = inputs_embeds.to('cuda:0'), attention_mask.to('cuda:0')
# attention from gnn to llm
if args.use_cross_modality_for_text:
# gnn to llm attention: attention on an additional token
input_prompt, gnn_output, node_mask, attention_mask_for_padding = self.gnn_model(graph_inputs, text_to_GNN_inputs)
input_prompt = input_prompt.to(inputs_embeds.device)
gnn_output = gnn_output.to(inputs_embeds.device)
node_mask = node_mask.to(inputs_embeds.device)
attention_mask_for_padding = attention_mask_for_padding.to(inputs_embeds.device)
valid_text_emb = inputs_embeds * attention_mask.unsqueeze(2).to(inputs_embeds.device)
valid_text_emb = valid_text_emb.sum(1) / ((valid_text_emb != 0).sum(1) + 1e-10)
valid_text_emb = valid_text_emb.unsqueeze(1)
special_token_gnn_to_llm_embeds = self.cross_modality_MHA_for_text(gnn_output, node_mask, valid_text_emb)
inputs_embeds = torch.cat((input_prompt, special_token_gnn_to_llm_embeds, inputs_embeds), dim=1)
prefix_attention_mask = torch.ones(inputs_embeds.size(0), input_prompt.size(1)+special_token_gnn_to_llm_embeds.size(1)).to(attention_mask.device)
cur_num_virtual_tokens = input_prompt.size(1)
# NO attention from gnn to llm
else:
gnn_input_prompt, link_loss, moe_loss = self.gnn_model(graph_inputs, text_to_GNN_inputs)
gnn_input_prompt = gnn_input_prompt.to(inputs_embeds.device)
gnn_prefix_attention_mask = torch.ones(inputs_embeds.size(0), gnn_input_prompt.size(1)).to(attention_mask.device)
if args.dataset_level_prompt:
dataset_level_input_prompt = self.prompt.repeat(inputs_embeds.size(0), 1, 1)
dataset_level_prefix_attention_mask = torch.ones(dataset_level_input_prompt.size(0), self.num_virtual_tokens).to(attention_mask.device)
inputs_embeds = torch.cat((dataset_level_input_prompt, gnn_input_prompt, inputs_embeds), dim=1)
attention_mask = torch.cat((dataset_level_prefix_attention_mask, gnn_prefix_attention_mask, attention_mask), dim=1)
cur_num_virtual_tokens = dataset_level_input_prompt.size(1) + gnn_input_prompt.size(1)
else:
inputs_embeds = torch.cat((gnn_input_prompt, inputs_embeds), dim=1)
attention_mask = torch.cat((gnn_prefix_attention_mask, attention_mask), dim=1)
cur_num_virtual_tokens = gnn_input_prompt.size(1)
# record num_virtual_tokens
if self.record_gnn_num_virtual_tokens and args.use_wandb:
wandb.run.summary["num_virtual_tokens"] = int(cur_num_virtual_tokens)
self.record_gnn_num_virtual_tokens = False
return self.llm(inputs_embeds=inputs_embeds, attention_mask=attention_mask, labels=labels), link_loss, moe_loss
return self.llm(inputs_embeds=inputs_embeds, attention_mask=attention_mask, labels=labels)
def print_trainable_parameters(self):
"""
Prints the number of trainable parameters in the model.
"""
trainable_params = 0
all_param = 0
for _, param in self.named_parameters():
num_params = param.numel()
# if using DS Zero 3 and the weights are initialized empty
if num_params == 0 and hasattr(param, "ds_numel"):
num_params = param.ds_numel
all_param += num_params
if param.requires_grad:
trainable_params += num_params
print(
f"trainable params: {trainable_params:,d} || all params: {all_param:,d} || trainable%: {100 * trainable_params / all_param}"
)
def construct_model(args, kg, dataset):
print('constructing model ...')
# Load pretrained concept embeddings
cp_emb = [np.load(path) for path in args.ent_emb_paths]
cp_emb = np.concatenate(cp_emb, 1)
cp_emb = torch.tensor(cp_emb, dtype=torch.float)
concept_num, concept_in_dim = cp_emb.size(0), cp_emb.size(1)
print('| num_concepts: {}, concept_in_dim: {} |'.format(concept_num, concept_in_dim))
args.concept_num = concept_num
if args.random_ent_emb:
cp_emb = None
args.freeze_ent_emb = False
args.concept_in_dim = args.gnn_dim
else:
args.concept_in_dim = concept_in_dim
if args.dataset == 'csqa':
args.num_choice = 5
elif args.dataset == 'obqa':
args.num_choice = 4
elif args.dataset == 'riddle':
args.num_choice = 5
elif args.dataset == 'medqa':
args.num_choice = 4
elif args.dataset == 'arc':
args.num_choice = 4
elif args.dataset == 'piqa':
args.num_choice = 2
elif args.dataset == 'pubmedqa':
args.num_choice = 3
elif args.dataset == 'bioasq':
args.num_choice = 2
elif args.dataset == 'cosmosqa':
args.num_choice = 4
else:
raise ValueError("Please indicate how many answer choices this dataset has.")
# Build model
if kg == "cpnet":
n_ntype = 4
n_etype = 38
# assert n_etype == dataset.final_num_relation *2
elif kg == "ddb":
n_ntype = 4
n_etype = 34
# assert n_etype == dataset.final_num_relation *2
elif kg == "umls":
n_ntype = 4
n_etype = dataset.final_num_relation * 2
print('final_num_relation', dataset.final_num_relation,
'len(id2relation)', len(dataset.id2relation))
print('final_num_relation', dataset.final_num_relation,
'len(id2relation)', len(dataset.id2relation), file=sys.stderr)
else:
raise ValueError("Invalid KG.")
if args.cxt_node_connects_all:
n_etype += 2
print('n_ntype', n_ntype, 'n_etype', n_etype)
print('n_ntype', n_ntype, 'n_etype', n_etype, file=sys.stderr)
args.n_ntype = n_ntype
args.n_etype = n_etype
model = MyModel(args, cp_emb)
# freeze llm for prompt tuning
if args.prompt == 'regular':
if not args.lora:
# Freeze all the parameters in the model
for param in model.parameters():
param.requires_grad = False
# Unfreeze the prompt Parameter, we want to keep this as trainable
model.prompt.requires_grad = True
elif args.prompt == 'gnn':
if not args.lora:
for param in model.llm.parameters():
param.requires_grad = False
elif args.prompt == False:
print('!!!'*20)
print('fine-tuning the full LLM')
print()
else:
raise ValueError('Not Implemented. What is the args.prompt?')
model.print_trainable_parameters()
return model
def sep_params(model, loaded_roberta_keys):
"""Separate the parameters into loaded and not loaded."""
loaded_params = dict()
not_loaded_params = dict()
params_to_freeze = []
small_lr_params = dict()
large_lr_params = dict()
for n, p in model.named_parameters():
if n in loaded_roberta_keys:
loaded_params[n] = p
params_to_freeze.append(p)
small_lr_params[n] = p
else:
not_loaded_params[n] = p
large_lr_params[n] = p
return loaded_params, not_loaded_params, params_to_freeze, small_lr_params, large_lr_params
def count_parameters(loaded_params, not_loaded_params):
num_params = sum(p.numel()
for p in not_loaded_params.values() if p.requires_grad)
num_fixed_params = sum(p.numel()
for p in not_loaded_params.values() if not p.requires_grad)
num_loaded_params = sum(p.numel() for p in loaded_params.values())
print('num_trainable_params (out of not_loaded_params):', num_params)
print('num_fixed_params (out of not_loaded_params):', num_fixed_params)
print('num_loaded_params:', num_loaded_params)
print('num_total_params:', num_params +
num_fixed_params + num_loaded_params)
def calc_acc_only(outputs, labels):
if outputs is None:
return 0
else:
return metrics.accuracy_score(labels, outputs)
def add_manual_prompts_to_flattern_graph_str_list(input):
output = []
which_option_list = ['first', 'second', 'third', 'fourth', 'fifth']
output.append('Based on the following concepts of each option, choose the best option to answer the question.')
for i, concept_of_a_choice_str in enumerate(input):
output.append('Concept of the ' + which_option_list[i] + ' option: ' + concept_of_a_choice_str + '\n')
return output
def merge_encoded_encoded_flattern_graph_str_list(input):
output = []
for i, concept_of_a_choice_list in enumerate(input):
output.extend(concept_of_a_choice_list)
return torch.LongTensor(output)
def calc_eval_accuracy(args, eval_set, model, cur_save_model_wrong_prediction=False, epoch_id=None):
"""Eval on the dev or test set - calculate loss and accuracy"""
model.eval()
tokenizer = AutoTokenizer.from_pretrained(args.encoder)
# gpt
if 'bloomz' in args.encoder:
tokenizer.padding_side = "left"
tokenizer.pad_token = tokenizer.eos_token
with torch.no_grad():
all_outputs = []
all_labels = []
all_qids = []
for qids, labels, batch_lm_inputs, batch_input_masks, batch_graph_inputs in tqdm(eval_set, desc="Eval batch"):
# baseline: flattern
if args.baseline_flattern:
if args.case_study:
all_triplets_list, node_type_in_triplets = batch_graph_inputs[-1]
all_triplets_list = list(set(all_triplets_list))
print('len(all_triplets_list): ', len(all_triplets_list))
print('len(node_type_in_triplets): ', len(node_type_in_triplets))
else:
flattern_graph_str_list = batch_graph_inputs[-1]
batch_graph_inputs = batch_graph_inputs[:-1]
flattern_graph_str_list = add_manual_prompts_to_flattern_graph_str_list(flattern_graph_str_list)
encoded_flattern_graph_list = tokenizer(flattern_graph_str_list, padding=False, truncation=True, return_token_type_ids=True, return_special_tokens_mask=True).input_ids # no padding
encoded_flattern_graph_input = merge_encoded_encoded_flattern_graph_str_list(encoded_flattern_graph_list)
encoded_flattern_graph_input = encoded_flattern_graph_input.unsqueeze(0)
encoded_flattern_graph_input = encoded_flattern_graph_input.to(batch_lm_inputs.device)
# prepare batch_lm_inputs
assert batch_lm_inputs.size(-1) == args.max_seq_len
batch_lm_inputs = batch_lm_inputs.view(-1, args.max_seq_len) # 1*100
batch_input_masks = batch_input_masks.view(-1, args.max_seq_len) # 1*100
# baseline: flattern. add gnn input to llm input
if args.baseline_flattern:
if not args.case_study:
batch_lm_inputs = torch.cat([encoded_flattern_graph_input, batch_lm_inputs], 1) # first gnn prompt, then QA pair
flattern_graph_input_mask = torch.ones(encoded_flattern_graph_input.size()).to(batch_input_masks.device)
batch_input_masks = torch.cat([flattern_graph_input_mask, batch_input_masks], 1) # first gnn prompt, then QA pair
# validate batch_lm_inputs
if args.debug2:
decoded_inputs = tokenizer.batch_decode(batch_lm_inputs, skip_special_tokens=True)
decoded_inputs = decoded_inputs[0]
print('decoded_inputs: ', decoded_inputs)
# validate the labels
decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
all_labels.extend(decoded_labels)
if args.debug2:
print('decoded_labels:', decoded_labels)
outputs = model.generate(input_ids=batch_lm_inputs, attention_mask=batch_input_masks, graph_inputs=batch_graph_inputs)
decoded_outputs = tokenizer.batch_decode(outputs, skip_special_tokens=True)
all_outputs.extend(decoded_outputs)
if args.debug2:
print('decoded_outputs:', decoded_outputs)
all_qids.extend(qids)
if args.case_study:
if decoded_outputs != decoded_labels:
with open('case_study/'+qids[0], 'wb') as f:
pickle.dump([decoded_inputs, decoded_labels[0], decoded_outputs[0], all_triplets_list, node_type_in_triplets], f)
all_labels = [i.lower() for i in all_labels]
all_outputs = [i.lower() for i in all_outputs]
if cur_save_model_wrong_prediction:
all_labels_wrong_prediction = []
all_outputs_wrong_prediction = []
all_qids_wrong_prediction = []
for idx in range(len(all_labels)):
cur_label = all_labels[idx]
cur_output = all_outputs[idx]
cur_qid = all_qids[idx]
if cur_label != cur_output:
all_labels_wrong_prediction.append(cur_label)
all_outputs_wrong_prediction.append(cur_output)
all_qids_wrong_prediction.append(cur_qid)
with open('case_study/gnn_wrong_pred/'+'epoch_'+str(epoch_id), 'wb') as f:
pickle.dump([all_labels_wrong_prediction, all_outputs_wrong_prediction, all_qids_wrong_prediction], f)
print('save successfully.')
total_loss_avg = 0
end_loss_avg = 0
out_accuracy = calc_acc_only(all_outputs, all_labels)
return total_loss_avg, end_loss_avg, out_accuracy
def train(args, resume, has_test_split, devices, kg):
print("args: {}".format(args))
if resume:
args.save_dir = os.path.dirname(args.resume_checkpoint)
if not args.debug:
if args.local_rank in [-1, 0]:
log_path = os.path.join(args.save_dir, 'log.csv')
utils.check_path(log_path)
if not resume:
with open(log_path, 'w') as fout:
fout.write(
'epoch,step,dev_acc,test_acc,best_dev_acc,final_test_acc,best_dev_epoch\n')
config_path = os.path.join(args.save_dir, 'config.json')
utils.export_config(args, config_path)
model_path = os.path.join(args.save_dir, 'model.pt')
# load datasets
dataset = load_data(args, devices, kg)
dev_dataloader = dataset.dev()
if has_test_split:
test_dataloader = dataset.test()
train_eval_dataloader = dataset.train_eval()
model = construct_model(args, kg, dataset)
INHERIT_BERT = os.environ.get('INHERIT_BERT', 0)
model.llm.resize_token_embeddings(len(dataset.tokenizer))
def _rename_key(key):
return "lmgnn." + key
optimizer = torch.optim.AdamW(model.parameters(), lr=args.learning_rate)
# Optionally loading from a checkpoint
if resume:
print("loading from checkpoint: {}".format(args.resume_checkpoint))
checkpoint = torch.load(args.resume_checkpoint, map_location='cpu')
last_epoch = checkpoint['epoch']
global_step = checkpoint['global_step']
model.load_state_dict(checkpoint["model"], strict=False)
optimizer.load_state_dict(checkpoint["optimizer"])
best_dev_epoch = checkpoint["best_dev_epoch"]
best_dev_acc = checkpoint["best_dev_acc"]
final_test_acc = checkpoint["final_test_acc"]
print(
f"resume from global_step {global_step}, last_epoch {last_epoch}")
else:
last_epoch = -1
global_step = 0
best_dev_epoch = best_dev_acc = final_test_acc = 0
# Create a scheduler
if args.lr_schedule == 'fixed':
try:
scheduler = ConstantLRSchedule(optimizer)
except:
scheduler = get_constant_schedule(optimizer)
elif args.lr_schedule == 'warmup_constant':
try:
scheduler = WarmupConstantSchedule(
optimizer, warmup_steps=args.warmup_steps, last_epoch=last_epoch)
except:
scheduler = get_constant_schedule_with_warmup(
optimizer, num_warmup_steps=args.warmup_steps, last_epoch=last_epoch)
elif args.lr_schedule == 'warmup_linear':
max_steps = int(
args.n_epochs * (dataset.train_size() / args.batch_size))
try:
scheduler = WarmupLinearSchedule(
optimizer, warmup_steps=args.warmup_steps, t_total=max_steps, last_epoch=last_epoch)
except:
scheduler = get_linear_schedule_with_warmup(
optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=max_steps, last_epoch=last_epoch)
if resume:
scheduler.load_state_dict(checkpoint["scheduler"])
print("loaded scheduler", checkpoint["scheduler"])
# Distributed training (should be after apex fp16 initialization)
if args.local_rank != -1:
model = torch.nn.parallel.DistributedDataParallel(
model, device_ids=[
args.local_rank], output_device=args.local_rank, find_unused_parameters=True
)
# Construct the loss function
if args.loss == 'margin_rank':
loss_func = nn.MarginRankingLoss(margin=0.1, reduction='mean')