-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgns.py
More file actions
1631 lines (1541 loc) · 77.2 KB
/
Copy pathgns.py
File metadata and controls
1631 lines (1541 loc) · 77.2 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 json
import gc
import os
import re
import torch
from transformers import (
AutoConfig,
AutoModelForSeq2SeqLM,
AutoModelForCausalLM,
AutoTokenizer,
BitsAndBytesConfig,
)
from peft import PeftModel
from solver.sketches_to_rosette import RosetteSolver
from solver.global_fixes import global_fixes
from solver.docker_evaluate import run_qemu
import time, random, itertools, difflib
from guess_and_sketch.assembly_regexes import *
from training.ft_model import prepare_sample_text
os.environ["TOKENIZERS_PARALLELISM"] = "false"
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
alignment_layer = 10
alignment_head = 14
class GuessAndSketch:
def __init__(self, args):
self.setup_from_args(args)
self.src_lang = args.source_lang
self.tgt_lang = args.target_lang
self.verbose = args.verbose
self.hole_tok = "??"
self.text_normalizer = lambda x: re.sub(
r"\.LFE[0-9]+:", ".LFE:", re.sub(r"\.LFB[0-9]+:", ".LFB:", x)
).replace(", ", ",")
self.delimiters = [" ", "\t", ",", "\n"]
# eventually we want to run guess and sketch together, and we can take advantage of this class structure for that. but in the meantime we have to move in stages
self.solver = RosetteSolver(args.source_lang, args.target_lang, args.verbose, sketch_name=args.sketch_filename)
self.do_memblock = not args.no_memblock
self.do_math = not args.no_math
self.do_strcopy = not args.no_strcopy
def convert_tensors(self, obj):
"""Recursively convert all PyTorch objects and tuples to JSON-compatible formats."""
if isinstance(obj, torch.Tensor):
return obj.tolist() # Convert Tensor to a Python list
elif isinstance(obj, tuple):
return [self.convert_tensors(i) for i in obj] # Convert tuple -> list
elif isinstance(obj, list):
return [self.convert_tensors(i) for i in obj] # Process elements in lists
elif isinstance(obj, dict):
return {k: self.convert_tensors(v) for k, v in obj.items()} # Process dict values
elif isinstance(obj, torch.dtype):
return str(obj) # Convert dtypes -> string
elif isinstance(obj, torch.device):
return str(obj) # Convert devices -> string
elif isinstance(obj, torch.nn.Parameter):
return obj.detach().tolist() # Convert nn.Parameter -> list
return obj # Return unchanged if not a Tensor
def setup_from_args(self, args):
self.args = args
self.tokenizer = AutoTokenizer.from_pretrained(
args.tokenizer_name, use_fast=True
)
self.lambda_val = args.lambda_val
if args.guess:
if args.is_enc_dec:
self.tokenizer.model_max_length = args.max_length
config = AutoConfig.from_pretrained(args.config_name)
config.vocab_size = len(self.tokenizer)
config.max_position_embeddings = args.max_length
self.model = AutoModelForSeq2SeqLM.from_pretrained(
args.model_name_or_path,
from_tf=bool(".ckpt" in args.model_name_or_path),
config=config,
device_map='auto',
).to(device)
embedding_size = self.model.get_input_embeddings().weight.shape[0]
if len(self.tokenizer) > embedding_size:
self.model.resize_token_embeddings(len(self.tokenizer))
if self.model.config.decoder_start_token_id is None:
print(
f"config.decoder_start_token_id is set to None, so auto setting to to BOS"
)
self.model.config.decoder_start_token_id = self.tokenizer.bos_token_id
self.is_enc_dec = True
self.gen_kwargs = {
"return_dict_in_generate": True,
"output_attentions": True,
"max_length": args.max_length,
"num_beams": args.k,
"no_repeat_ngram_size": 0,
"output_scores": True,
"num_return_sequences": args.k,
}
else:
if "qwen" in args.model_name_or_path.lower():
# Qwen2.5 (Decoder-Only, but NOT PEFT-based)
bnb_config = BitsAndBytesConfig(
load_in_4bit=True, # ✅ Reduces VRAM usage by 50-75%
bnb_4bit_compute_dtype=torch.float16,
bnb_4bit_use_double_quant=True
)
self.model = AutoModelForCausalLM.from_pretrained(
args.model_name_or_path,
quantization_config=bnb_config, # ✅ Apply 4-bit quantization
device_map="auto",
trust_remote_code=True
)
else:
# Other Decoder-Only Models (e.g., LLaMA, GPT, PEFT-based models)
parent_name = args.config_name
model = AutoModelForCausalLM.from_pretrained(parent_name, load_in_8bit=True, trust_remote_code=True)
self.model = PeftModel.from_pretrained(model, args.model_name_or_path)
self.is_enc_dec = False
self.gen_kwargs = {
"return_dict_in_generate": True,
"output_attentions": True,
"max_new_tokens": args.max_length,
"num_beams": args.k,
"no_repeat_ngram_size": 0,
"output_scores": True,
"num_return_sequences": args.k,
}
self.make_run_commands = {
"as_cmd": "{prefix}-linux-gnu-as",
"gcc_cmd": "{prefix}-linux-gnu-gcc -pthread",
"qemu_cmd": "qemu-{prefix} -L /usr/{prefix}-linux-gnu",
}
if "benchmarks" in args.predictions_folder:
self.make_run_commands["gcc_flags"] = "-lapr-1 -lm -lgmp" if args.target_lang == 'arm' else "$(pkg-config --libs apr-1 gmp) -lm"
self.make_run_commands["qemu_setup"] = {
"binary-trees": {
"setup": [],
"test": [],
"cleanup": [],
"qemu_args": "9", # "21",
},
"fannkuch-redux": {
"setup": [],
"test": [],
"cleanup": [],
"qemu_args": "9", # "12",
},
"pidigits": {
"setup": [],
"test": [],
"cleanup": [],
"qemu_args": "1000", # 0,
},
"nbody": {
"setup": [],
"test": [],
"cleanup": [],
"qemu_args": "500000", # 00,
},
"fasta": {
"setup": [],
"test": [],
"cleanup": [],
"qemu_args": "250", # 00000,
},
"toosimple": {
"setup": [],
"test": [],
"cleanup": [],
"qemu_args": "100000000", # 00,
},
}
elif "euler" in args.predictions_folder:
self.make_run_commands["gcc_flags"] = "-lm -lgmp" if args.target_lang == 'arm' else "$(pkg-config --libs gmp) -lm"
self.make_run_commands["qemu_setup"] = {
"problem": {"setup": [], "qemu_args": "", "test": [], "cleanup": []}
}
elif "human_eval" in args.predictions_folder:
self.make_run_commands["gcc_flags"] = "-lm -lgmp" if args.target_lang == 'arm' else "$(pkg-config --libs gmp) -lm"
self.make_run_commands["qemu_setup"] = {
"problem": {"setup": [], "qemu_args": "", "test": [], "cleanup": []}
}
elif "unix_commands" in args.predictions_folder:
self.make_run_commands["gcc_flags"] = ""
random_num = random.randint(0, 1000)
self.make_run_commands["qemu_setup"] = {
"cat": {
"setup": [
"echo hello " + str(random_num) + " > {folder}/testfile.txt"
],
"qemu_args": "{folder}/testfile.txt",
"test": [""],
"cleanup": ["rm {folder}/testfile.txt"],
},
"cd": {
"setup": [],
"qemu_args": "../../",
"test": [],
"cleanup": [],
},
"cp": {
"setup": [
"mkdir {folder}/tempfolder",
"touch {folder}/tempfolder/testfile.txt",
"echo hello "
+ str(random_num)
+ " > {folder}/tempfolder/testfile.txt",
],
"qemu_args": "{folder}/tempfolder/testfile.txt {folder}/tempfolder/copiedtestfile.txt",
"test": [
"cat {folder}/tempfolder/copiedtestfile.txt",
"ls {folder}/tempfolder",
],
"cleanup": ["rm -rf {folder}/tempfolder"],
},
"ls": {
"setup": [
"mkdir {folder}/tempfolder",
"touch {folder}/tempfolder/testfile.txt",
"echo hello "
+ str(random_num)
+ " > {folder}/tempfolder/testfile.txt",
],
"qemu_args": "{folder}/tempfolder",
"test": [],
"cleanup": ["rm -rf {folder}/tempfolder"],
},
"mkdir": {
"setup": ["mkdir -p {folder}/tempfolder/"],
"qemu_args": "{folder}/tempfolder/atestfolder",
"test": ["ls {folder}/tempfolder"],
"cleanup": ["rm -rf {folder}/tempfolder"],
},
"ps": {
"setup": [],
"qemu_args": "",
"test": [],
"cleanup": [],
},
"rm": {
"setup": [
"mkdir {folder}/tempfolder",
"touch {folder}/tempfolder/filetorm.txt",
],
"qemu_args": "{folder}/tempfolder/filetorm.txt",
"test": ["ls {folder}/tempfolder"],
"cleanup": ["rm -rf {folder}/tempfolder"],
},
"rmdir": {
"setup": [
"mkdir -p {folder}/tempfolder/newfolder",
"touch {folder}/tempfolder/afile.txt",
],
"qemu_args": "{folder}/tempfolder/newfolder",
"test": ["ls {folder}/tempfolder"],
"cleanup": ["rm -rf {folder}/tempfolder"],
},
"tee": {
"setup": [],
"qemu_args": "",
"test": [],
"cleanup": [],
},
"touch": {
"setup": [
"touch {folder}/testfile.txt",
"echo hello " + str(random_num) + " > {folder}/testfile.txt",
],
"qemu_args": "{folder}/testfile.txt",
"test": [],
"cleanup": ["rm {folder}/testfile.txt"],
},
"xargs": {
"setup": [],
"qemu_args": "",
"test": [],
"cleanup": [],
},
}
### GUESS FUNCTIONS ###
def preprocess_text(self, input_text, tgt_text):
if self.is_enc_dec:
model_inputs = self.tokenizer([input_text], return_tensors="pt")
if tgt_text is not None:
labels = self.tokenizer(text_target=[tgt_text], return_tensors="pt")
model_inputs["labels"] = labels["input_ids"]
return model_inputs
else:
input_ids, (in_start_idx, in_seq_len, out_start_idx, out_seq_len) = prepare_sample_text(self.tokenizer, {self.src_lang: input_text, self.tgt_lang:tgt_text}, self.src_lang, self.tgt_lang)
model_inputs = self.tokenizer(input_text)
model_inputs.input_ids = torch.tensor(input_ids[:,:out_start_idx])
model_inputs.labels = torch.tensor(input_ids)
model_inputs.attention_mask = torch.ones_like(model_inputs.input_ids)
model_inputs["input_ids"] = model_inputs.input_ids
model_inputs["labels"] = model_inputs.labels
model_inputs["attention_mask"] = model_inputs.attention_mask
return model_inputs, (in_start_idx, in_seq_len, out_start_idx, out_seq_len)
def filter_topk_chunks(self, chunk_pred_output, prev_pred_output, prefix_len, prior_input_len, k):
# Note that this is for windowing when the chunks are too long, and it is not currently implemented for the decoder-only because the window size is 8k
if prev_pred_output is None:
chunk_pred_output.cross_attentions = [
xattn[alignment_layer].mean(dim=1)[:,0]
for xattn in chunk_pred_output.cross_attentions
]
return chunk_pred_output
k_top = [] # k-size list of top options (index, score)
if 'sequences_scores' not in chunk_pred_output.keys():
chunk_pred_output.sequences_scores = torch.tensor([1.0])
for i, new_seq_score in enumerate(chunk_pred_output.sequences_scores):
b_idx = int(i / k)
if prev_pred_output:
prev_corresp_scores = prev_pred_output.sequences_scores[b_idx]
denom = (
1
if len(prev_pred_output.sequences_scores.shape) == 1
else prev_corresp_scores.shape[-1]
)
this_score = (
prev_corresp_scores.sum().item() + new_seq_score.item()
) / (denom + 1)
else:
this_score = new_seq_score.item()
if len(k_top) < k or this_score > k_top[-1][-1]:
k_top.append((i, b_idx, this_score))
k_top.sort(key=lambda x: x[-1], reverse=True)
if len(k_top) > k:
k_top = k_top[:k]
top_prev_idxes = [x[1] for x in k_top]
k_top = [x[0] for x in k_top]
chunk_pred_output.sequences = chunk_pred_output.sequences[k_top]
chunk_pred_output.sequences_scores = chunk_pred_output.sequences_scores[k_top]
chunk_pred_output.scores = [sc[k_top] for sc in chunk_pred_output.scores]
chunk_pred_output.cross_attentions = [
torch.cat(
(torch.zeros((len(k_top), prior_input_len)).to(device), xattn[alignment_layer][k_top].mean(dim=1)[:,0]),
dim=-1,
)
for xattn in chunk_pred_output.cross_attentions
]
prev_pred_output.sequences = torch.cat(
(
prev_pred_output.sequences[top_prev_idxes, :-1], # remove EOS from end.
chunk_pred_output.sequences[:, prefix_len+1 :], # +1 because adds a BOS in backend
),
dim=-1,
)
# if this is the first cat, expand single productions into expected dimensionality then concatenate sequence scores
if len(prev_pred_output.sequences_scores.shape) == 1:
prev_pred_output.sequences_scores = prev_pred_output.sequences_scores[:, None]
prev_pred_output.sequences_scores = torch.cat(
(
prev_pred_output.sequences_scores[top_prev_idxes],
chunk_pred_output.sequences_scores[:, None],
),
dim=-1,
) # note: HF internally doesnt score decoder input ids
# concatenate token scores for each sequence
prev_pred_output.scores = [
po_s[top_prev_idxes] for po_s in prev_pred_output.scores[:-1] # omit eos from end
] + chunk_pred_output.scores
# get alignment.
prev_pred_output.cross_attentions = [
po_s[top_prev_idxes] for po_s in prev_pred_output.cross_attentions[:-1]
] + chunk_pred_output.cross_attentions
return prev_pred_output
def translate(self, batch, offset_info, gen_kwargs):
(in_start_idx, in_seq_len) = offset_info
if self.is_enc_dec and (in_seq_len > self.args.max_length):
return self.translate_in_chunks(
batch, 200, gen_kwargs
)
breakpoint()
if self.is_enc_dec:
model_output = self.model.generate(
input_ids=batch.input_ids.to(device),
attention_mask=batch.attention_mask.to(device),
**gen_kwargs,
)
model_output.cross_attentions = [
xattn[alignment_layer].mean(dim=1)[:,0]
for xattn in model_output.cross_attentions
]
torch.cuda.empty_cache()
gc.collect()
return model_output
model_output = self.model.generate(
input_ids=batch.input_ids.to(device),
attention_mask=batch.attention_mask.to(device),
**gen_kwargs,
)
model_output.attentions = [
attn[alignment_layer][:,alignment_head].mean(dim=1)[:,in_start_idx:in_start_idx+in_seq_len] for attn in model_output.attentions
]
return model_output
def translate_in_chunks(self, batch, overlap_size, gen_kwargs):
input_ids = batch.input_ids.to(device)
k = gen_kwargs["num_return_sequences"]
max_length = self.args.max_length
assert (
input_ids.shape[0] == 1
), f"Translation in chunks should only occur for a single instance at a time, but this shape was {input_tensor.shape}"
# Initialize and set up for translation in chunks
pred_output = None
input_start_idx = 0
decoder_input_ids = None
chunk_input_ids = input_ids[
:, input_start_idx : min(input_ids.shape[-1], input_start_idx + max_length)
].to(device)
attention_mask = batch.attention_mask[
:, input_start_idx : min(input_ids.shape[-1], input_start_idx + max_length)
].to(device)
while input_start_idx < input_ids.shape[-1]:
chunk_pred_output = self.model.generate(
chunk_input_ids,
decoder_input_ids=decoder_input_ids,
attention_mask=attention_mask,
**gen_kwargs,
)
# filter chunk_pred_output to the top-k
prefix_len = decoder_input_ids.shape[-1] if decoder_input_ids is not None else 0
pred_output = self.filter_topk_chunks(chunk_pred_output, pred_output, prefix_len=prefix_len, prior_input_len=input_start_idx, k=k)
torch.cuda.empty_cache()
gc.collect()
if input_start_idx + max_length < input_ids.shape[-1]:
input_start_idx = input_start_idx + max_length - overlap_size
chunk_input_ids = input_ids[
:,
input_start_idx : min(
input_ids.shape[-1], input_start_idx + max_length
),
].to(device).expand(k, -1)
attention_mask = (
batch["attention_mask"][
:,
input_start_idx : min(
input_ids.shape[-1], input_start_idx + max_length
),
]
.to(device)
.expand(k, -1)
)
# just make them all the same, this can be looser
prefix_start = max(0, len(chunk_pred_output.cross_attentions) - overlap_size)
input_max_diff = (
chunk_pred_output.cross_attentions[prefix_start][0].argmax(dim=-1)
- input_start_idx
)
while input_max_diff != 0:
if input_max_diff > 0:
# if have been incrementing bc it was too far left, then once it hits threshold, break
if prefix_start > (
len(chunk_pred_output.cross_attentions) - overlap_size
):
break
# otherwise, keep decrementing
else:
prefix_start -= 5
else:
# if we have been decrementing bc it was too far right, then once its hits threshold, break
if prefix_start < (
len(chunk_pred_output.cross_attentions) - overlap_size
):
break
# otherwise, keep incrementing
else:
prefix_start += 5
if prefix_start > len(chunk_pred_output.cross_attentions) - 5:
prefix_start = len(chunk_pred_output.cross_attentions) - 5
break
input_max_diff = (
chunk_pred_output.cross_attentions[prefix_start][0].argmax(
dim=-1
)
- input_start_idx
)
decoder_input_ids = chunk_pred_output.sequences[
:, prefix_start:-1
] # omit eos
else:
break
if len(pred_output.sequences_scores.shape) > 1:
pred_output.sequences_scores = torch.mean(
pred_output.sequences_scores, dim=-1
)
return pred_output
def get_alignments(self, pred_outputs, input_ids, start_idxes_and_lens=None, p_mass=0.99):
if self.is_enc_dec:
attentions = pred_outputs.cross_attentions
(in_start_idx, in_seq_len, out_start_idx, out_seq_len) = (0, input_ids.shape[-1], 0, pred_outputs.sequences.shape[-1])
else:
attentions = pred_outputs.attentions
assert start_idxes_and_lens is not None, "Need start indices and sequence lengths if decoder-only model."
(in_start_idx, in_seq_len, out_start_idx, out_seq_len) = start_idxes_and_lens
input_ids = input_ids[in_start_idx:in_start_idx+in_seq_len]
pred_seqs = pred_outputs.sequences[:,out_start_idx:out_start_idx+out_seq_len]
if pred_outputs.sequences.shape[0] > 1:
seq_scores = pred_outputs.sequences_scores
else:
seq_scores = torch.tensor([1.0] * pred_seqs.shape[0])
# by chunk
top_k_translations = ([]) # list of tuple (tokenized prediction, aligned_tokens, score of prediction)
input_ids = input_ids.expand(pred_outputs.sequences.shape[0], -1) # repeat input_ids for num_generations times
existing_gens = set()
for batch_idx, (pred_seq, pred_score) in enumerate(
zip(pred_seqs, seq_scores)
):
pred_seq_str = self.tokenizer.decode(pred_seq, skip_special_tokens=True)
norm_gen = self.text_normalizer(pred_seq_str)
if norm_gen in existing_gens:
continue
existing_gens.add(norm_gen)
# Identify alignments
aligned_tokens: List[Tuple(Tuple[int], Tuple[int])] = [
None for _ in range(len(pred_outputs.scores))
]
for out_idx, (out_logits, alignment) in enumerate(
zip(pred_outputs.scores, attentions)
):
# Get top alternate tokens for out_idx+1 position
prob_distr = out_logits[batch_idx].softmax(dim=-1)
alt_toks = []
running_p_mass = 0.0
sorted_prob_distr = prob_distr.sort(descending=True)
for alt_tok, prob_val in zip(
sorted_prob_distr.indices[:4], sorted_prob_distr.values[:4]
):
alt_toks.append((alt_tok.item(), prob_val))
running_p_mass += prob_val
if (running_p_mass > p_mass) or len(alt_toks) > 5:
break
# Get top input alignments.
in_idxes = []
running_p_mass = 0.0
sequence_idx = batch_idx # if self.is_enc_dec else batch_idx*self.gen_kwargs['num_beams']
if self.is_enc_dec:
sorted_alignment = alignment[sequence_idx].sort(descending=True)
else:
sorted_alignment = alignment[sequence_idx].sort(descending=True)
for in_idx, prob_val in zip(
sorted_alignment.indices[:4], sorted_alignment.values[:4]
):
in_idxes.append(in_idx.item())
running_p_mass += prob_val
if (running_p_mass > p_mass) or len(alt_toks) > 5:
break
aligned_tokens[out_idx] = (tuple(in_idxes), tuple(alt_toks))
top_k_translations.append(
(pred_seq.tolist(), aligned_tokens, pred_score.item())
)
return top_k_translations
def guess(self, datapoint, predictions_folder, num_generations):
self.model.eval()
progname = datapoint["source"].split(".c")[0]
print(progname)
if os.path.exists(f"{predictions_folder}/guess_{progname}.json"): return
problem_prediction = {
"src": datapoint["source"],
"c": datapoint["c"],
"risc": datapoint["risc"],
"arm": datapoint["arm"],
}
# 1. generate all sequence candidates and get their probabilities
chunk_translations = [] # list. len = num chunks
# entry includes all candidate translations and probs: {fnname:fnname, translations: List[(seq tokens, alignments, corresp prob) x num_generations]}
too_long = False
with torch.no_grad():
problem_prediction[f"src_{self.src_lang}"] = {
"functions": {},
}
problem_prediction[f"tgt_{self.tgt_lang}"] = {
"functions": {},
}
# Translate fn chunks
for cloze_name, src_chunk in datapoint[f"{self.src_lang}_fns"].items():
print(cloze_name)
torch.cuda.empty_cache()
tgt_chunk = datapoint[f"{self.tgt_lang}_fns"][cloze_name]
batch = self.preprocess_text(src_chunk, tgt_chunk)
if self.is_enc_dec:
(in_start_idx, in_seq_len) = (0, batch.input_ids.shape[-1])
problem_prediction[f"src_{self.src_lang}"]["functions"][
cloze_name
] = batch.input_ids[0].tolist()
problem_prediction[f"tgt_{self.tgt_lang}"]["functions"][
cloze_name
] = batch.labels[0].tolist()
else:
batch, (in_start_idx, in_seq_len, out_start_idx, out_seq_len) = batch
if in_seq_len > self.args.max_length: return
problem_prediction[f"src_{self.src_lang}"]["functions"][
cloze_name
] = batch.input_ids[0].tolist()[in_start_idx:in_start_idx+in_seq_len]
problem_prediction[f"tgt_{self.tgt_lang}"]["functions"][
cloze_name
] = batch.labels[0].tolist()[out_start_idx:out_start_idx+out_seq_len]
pred_output = self.translate(
batch, (in_start_idx, in_seq_len), self.gen_kwargs
)
torch.cuda.empty_cache()
gc.collect()
# Get seq probs
if self.is_enc_dec:
chunk_translations.append(
{
"fnname": cloze_name,
"translations": self.get_alignments(
pred_output, batch.input_ids[0]
),
}
)
else:
chunk_translations.append(
{
"fnname": cloze_name,
"translations": self.get_alignments(
pred_output, batch.input_ids[0], (in_start_idx, in_seq_len, out_start_idx, out_seq_len)
),
}
)
# Translate cloze
batch = self.preprocess_text(
datapoint[f"{self.src_lang}_cloze"], datapoint[f"{self.tgt_lang}_cloze"]
)
if self.is_enc_dec:
(in_start_idx, in_seq_len) = (0, batch.input_ids.shape[-1])
problem_prediction[f"src_{self.src_lang}"]["cloze"] = batch.input_ids[0].tolist()
problem_prediction[f"tgt_{self.tgt_lang}"]["cloze"] =batch.labels[0].tolist()
else:
batch, (in_start_idx, in_seq_len, out_start_idx, out_seq_len) = batch
problem_prediction[f"src_{self.src_lang}"]["cloze"] = batch.input_ids[0].tolist()[in_start_idx:in_start_idx+in_seq_len]
problem_prediction[f"tgt_{self.tgt_lang}"]["cloze"] = batch.labels[0].tolist()[out_start_idx:out_start_idx+out_seq_len]
pred_output = self.translate(
batch, (in_start_idx, in_seq_len), self.gen_kwargs
)
if self.is_enc_dec:
chunk_translations.append(
{
"fnname": None,
"translations": self.get_alignments(
pred_output, batch.input_ids[0]
),
}
)
else:
chunk_translations.append(
{
"fnname": None,
"translations": self.get_alignments(
pred_output, batch.input_ids[0], (in_start_idx, in_seq_len, out_start_idx, out_seq_len)
),
}
)
# 2. DP algorithm to get the top num_generations candidates
# initialize dynamic programming structures: data storage, tracker
top_K = [] # [(indices, resulting prob, translation info dict)
# last max-prob indices initialized to the first candidate in each chunk
last_max_indices = tuple([0] * len(chunk_translations))
translation_info = [
[
chunk_info["fnname"], # the fnname
chunk_info["translations"][0][0], # the tokenized prediction
chunk_info["translations"][0][1], # the alignments
chunk_info["translations"][0][2], # the logprob
]
for chunk_info in chunk_translations
]
logprob = sum(chunk_info[3] for chunk_info in translation_info)
top_K.append(
(
last_max_indices,
logprob,
{
"logprob": logprob,
"translation_info": {
chunk_info[0]: (chunk_info[1], chunk_info[2])
for chunk_info in translation_info
},
},
)
)
max_pointer = 0
while max_pointer < num_generations and max_pointer < len(top_K):
last_max_indices = top_K[max_pointer][0]
for chunk_idx in range(len(last_max_indices)):
if last_max_indices[chunk_idx] + 1 >= len(
chunk_translations[chunk_idx]["translations"]
):
continue
new_indices = list(last_max_indices)
new_indices[chunk_idx] += 1
translation_info = [
[
chunk_translations[chunk_idx]["fnname"],
chunk_translations[chunk_idx]["translations"][gen_idx][
0
], # the tokenized prediction
chunk_translations[chunk_idx]["translations"][gen_idx][
1
], # the alignments
chunk_translations[chunk_idx]["translations"][gen_idx][
2
], # the logprob
]
for chunk_idx, gen_idx in enumerate(new_indices)
]
logprob = sum(chunk_info[3] for chunk_info in translation_info)
top_K.append(
(
tuple(new_indices),
logprob,
{
"logprob": logprob, # total logprob of this combination
"translation_info": {
chunk_info[0]: (chunk_info[1], chunk_info[2])
for chunk_info in translation_info
}, # fn name to tokenized prediction and alignments
},
)
)
top_K = sorted(top_K, key=lambda x: x[1], reverse=True)
max_pointer += 1
# 3. compile into results dictionary
problem_prediction[f"pred_{self.tgt_lang}"] = {"top_k": [
top_k_info[2] for top_k_info in top_K[:num_generations]
]}
if not os.path.exists(predictions_folder):
os.mkdir(predictions_folder)
problem_prediction[f"pred_{self.tgt_lang}"]["top_k"] = [self.convert_tensors(top_k_info) for top_k_info in problem_prediction[f"pred_{self.tgt_lang}"]["top_k"]]
#for i, entry in enumerate(problem_prediction[f"pred_{self.tgt_lang}"]["top_k"]):
#print(f"DEBUG: Entry {i} in top_k -> Type: {type(entry)}")
#if isinstance(entry, dict):
#for key, value in entry.items():
#print(f"DEBUG: Key '{key}' in top_k[{i}] -> Type: {type(value)}")
#if isinstance(value, dict):
#for subkey, subvalue in value.items():
#print(f"DEBUG: Key '{key}.{subkey}' in top_k[{i}] -> Type: {type(subvalue)}")
with open(f"{predictions_folder}/guess_{progname}.json", "w") as f:
json.dump(problem_prediction, f, indent=4)
del batch
del pred_output
torch.cuda.empty_cache()
gc.collect()
### SKETCH FUNCTIONS ###
def get_line_end_tokenized_indices(self, tokenized_sequence):
if type(tokenized_sequence[0]) == list:
tokenized_sequence = tokenized_sequence[0]
decoded_seq = self.tokenizer.decode(
tokenized_sequence, skip_special_tokens=False
)
toks_of_sequence = self.tokenizer.convert_ids_to_tokens(tokenized_sequence)
char_to_tokenized_tok = {
len(self.tokenizer.decode(tokenized_sequence[: idx + 1])): idx
for idx in range(len(tokenized_sequence))
}
line_end_idxes = []
reconstruct = ""
seq_lines = decoded_seq.splitlines(True)
for line in seq_lines:
reconstruct += line
if line[-1] == "\n":
char_idx = len(reconstruct) - 1
else:
char_idx = len(reconstruct)
while char_idx not in char_to_tokenized_tok:
char_idx += 1
if char_idx > len(char_to_tokenized_tok):
return line_end_idxes
line_end_idxes.append(char_to_tokenized_tok[char_idx] + 1) # +1 bc endidx
return line_end_idxes
def punch_uncertain_tokens(
self, line_start_tok, line_end_tok, pred_toked, token_alignments, do_punch
):
# TODO later put this back to registers but for now only punch out imms...
sketch_line = ""
line_tok_cursor = line_start_tok
last_logged_register_idx = line_start_tok
reg_strs_to_toks = []
offset = 1 # start offset to 1 because of BOS; increases with all new BOS additions (should depracate this once the BOS fix is handled in guess)
for line_tok_idx in range(line_start_tok, line_end_tok):
if do_punch:
alt_toks = token_alignments[line_tok_idx - offset][1]
if pred_toked[line_tok_idx] not in [alt_tok for (alt_tok, _) in alt_toks]: offset += 1
if alt_toks[0][1] < self.lambda_val:
sketch_line += self.tokenizer.decode(
pred_toked[line_tok_cursor:line_tok_idx], skip_special_tokens=True
)
# if re.search(re.compile('[a-z]+\s+[a-z]+\d+'), sketch_line): # disallow hole for insn or target reg
# sketch_line += "??" # TODO handle when delimiters are in uncertain token
last_arg = re.split(
",|\s|\s#",
self.tokenizer.decode(
pred_toked[line_start_tok : line_tok_idx + 1],
skip_special_tokens=True,
),
)[-1]
if (re.search(re.compile("\.?[a-z]+\s+[\"\da-z]+"), sketch_line) and
re.fullmatch(r"[,\s]*(#?-?\d+|\".*)[,\s]*", last_arg)): # disallow hole for anything but imm, string copy
replacing = self.tokenizer.decode(
pred_toked[line_tok_idx : line_tok_idx + 1]
)
if replacing[0] in self.delimiters:
sketch_line += replacing[0]
sketch_line += "??"
if replacing[-1] in self.delimiters:
sketch_line += replacing[-1]
else:
sketch_line += self.tokenizer.decode(
pred_toked[line_tok_idx : line_tok_idx + 1],
skip_special_tokens=True,
)
if len(sketch_line) > 0 and sketch_line[-1].isdigit(): # should we strip?
potential_reg_start = line_tok_idx
while potential_reg_start > last_logged_register_idx:
potential_register = self.tokenizer.decode(
pred_toked[potential_reg_start : line_tok_idx + 1]
)
register_match = re.fullmatch(
r"[\s,]*([a-z]+\d+)[,\s]*", potential_register
)
if register_match and (
(register_match.group(0)[0] in self.delimiters)
or (
potential_reg_start > 0
and self.tokenizer.decode(
[pred_toked[potential_reg_start - 1]]
)[-1]
in self.delimiters
)
):
reg_strs_to_toks.append(
(
register_match.group(1),
(potential_reg_start, line_tok_idx + 1),
)
)
last_logged_register_idx = line_tok_idx
break
potential_reg_start -= 1
line_tok_cursor = line_tok_idx + 1
# if line_tok_idx corresponds to a register, log it.
if self.tokenizer.convert_ids_to_tokens(pred_toked[line_tok_idx])[-1].isdigit():
potential_reg_start = line_tok_idx
while potential_reg_start > last_logged_register_idx:
potential_register = self.tokenizer.decode(
pred_toked[potential_reg_start : line_tok_idx + 1]
)
register_match = re.fullmatch(
r"[\s,]*([a-z]+\d+)[,\s]*", potential_register
)
if register_match and (
(register_match.group(0)[0] in self.delimiters)
or (
potential_reg_start > 0
and self.tokenizer.decode(
[pred_toked[potential_reg_start - 1]]
)[-1]
in self.delimiters
)
):
reg_strs_to_toks.append(
(
register_match.group(1),
(potential_reg_start, line_tok_idx + 1),
)
)
last_logged_register_idx = line_tok_idx
break
potential_reg_start -= 1
sketch_line += self.tokenizer.decode(
pred_toked[line_tok_cursor:line_end_tok], skip_special_tokens=True
)
if do_punch:
# now clean up the sketch line
last_delimiter_idx = 0
cleaned_sketch_line = ""
for sketch_line_char_idx in range(len(sketch_line)):
if sketch_line[sketch_line_char_idx] not in self.delimiters:
continue
if (
self.hole_tok
in sketch_line[last_delimiter_idx:sketch_line_char_idx]
):
cleaned_sketch_line += self.hole_tok
else:
cleaned_sketch_line += sketch_line[
last_delimiter_idx:sketch_line_char_idx
]
cleaned_sketch_line += sketch_line[sketch_line_char_idx]
last_delimiter_idx = sketch_line_char_idx + 1
if self.hole_tok in sketch_line[last_delimiter_idx:]:
cleaned_sketch_line += self.hole_tok
else:
cleaned_sketch_line += sketch_line[last_delimiter_idx:]
sketch_line = cleaned_sketch_line
regs = self.get_registers(sketch_line, reg_strs_to_toks)
if regs is None: return None, (None, {}), None
regt, regss = regs
return sketch_line, regt, regss
def get_registers(self, assembly_line, reg_strs_to_toks):
regex_4 = reg4_holed
regex_3 = reg3_holed
regex_2 = reg2_holed
assembly_insn = str(assembly_line)
if assembly_insn[-1] != "\n":
assembly_insn += "\n" # add a newline to end to make regex matching happy
reg_counter = 0
match4_groups = re.match(regex_4, assembly_insn)
if match4_groups is not None:
command = match4_groups.group(1)
if command == self.hole_tok: return None
regt = match4_groups.group(2)
if regt == self.hole_tok: return None
if regt != reg_strs_to_toks[reg_counter][0]: return None
regt_idxes = reg_strs_to_toks[reg_counter][1]
reg_counter += 1
regss = set()
regs1 = match4_groups.group(3)
if re.match(register_regex, regs1):
if regs1 != reg_strs_to_toks[reg_counter][0]: return None
regs1_idxes = reg_strs_to_toks[reg_counter][1]
regss.add((regs1, regs1_idxes))
reg_counter += 1
regs2 = match4_groups.group(4)
if re.match(register_regex, regs2):
if regs2 != reg_strs_to_toks[reg_counter][0]: return None
regs2_idxes = reg_strs_to_toks[reg_counter][1]
regss.add((regs2, regs2_idxes))
reg_counter += 1
# cond = match4_groups.group(5)
return (regt, regt_idxes), regss
match3_groups = re.match(regex_3, assembly_insn)
if match3_groups is not None:
command = match3_groups.group(1)
if command == self.hole_tok: return None
regt = match3_groups.group(2)
if regt == self.hole_tok: return None
if regt != reg_strs_to_toks[reg_counter][0]: return None
regt_idxes = reg_strs_to_toks[reg_counter][1]
reg_counter += 1
regss = set()
regs1 = match3_groups.group(3)
if re.match(register_regex, regs1):
if regs1 != reg_strs_to_toks[reg_counter][0]: return None
regs1_idxes = reg_strs_to_toks[reg_counter][1]
regss.add((regs1, regs1_idxes))
reg_counter += 1