File size: 39,672 Bytes
81dc001 |
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 |
# utils_qwen.py
# Author: Yaning
from collections import deque
from string import punctuation
from transformers import AutoTokenizer, AddedToken
from functools import partial
from numpy.random import default_rng
from nltk.tree import ParentedTree
import torch
##############################################################################
# CONSTANTS
##############################################################################
BABYLM_SPLITS = ['100M', '10M', 'dev', 'test', 'unittest']
# Yj: 用于在参数解析和数据加载时指定数据集
# 影响数据集的预处理过程,如生成训练、开发、测试和单元测试集。
SEEDS = [21, 57, 84]
CHECKPOINTS = list(range(50, 501, 50))
GENRES = {
"aochildes": "CHILDES",
"bnc_spoken": "British National Corpus (BNC)",
"cbt": "Children’s Book Test",
"children_stories": "Children’s Stories Text Corpus",
"gutenberg": "Standardized Project Gutenberg Corpus",
"open_subtitles": "OpenSubtitles",
"qed": "QCRI Educational Domain Corpus",
"simple_wikipedia": "Simple Wikipedia",
"switchboard": "Switchboard Dialog Act Corpus",
"wikipedia": "Wikipedia"
}
CHECKPOINT_WRITE_PATH = "/nlp/scr3/nlp/llms-in-llms/babylm_models"
CHECKPOINT_READ_PATH = "/nlp/scr3/nlp/llms-in-llms/babylm_models"
# BABYLM_DATA_PATH = "/nlp/scr3/nlp/llms-in-llms/babylm_data"
BABYLM_DATA_PATH = "."
MARKER_HOP_SING = "🅂"
MARKER_HOP_PLUR = "🄿"
MARKER_REV = "🅁"
BOS_TOKEN = "<BOS_TOKEN>"
PART_TOKENS = set(["n't", "'ll", "'s", "'re", "'ve", "'m"])
PUNCT_TOKENS = set(punctuation)
MODEL_NAME = "gpt2"
##############################################################################
# PARENS MODELS (Structurally-pretrained)
##############################################################################
PAREN_MODEL_PATH = "/u/scr/isabelvp//tilt-stuff/tilt-finetuning/pretrained_checkpoints/"
PAREN_MODELS = {
"CROSS": "flat-parens_vocab500-uniform_deplength-nesting-nolimit",
"NEST": "nested-parens0.49_vocab500-uniform",
"RAND": "random_vocab500-uniform",
}
##############################################################################
# HELPER FUNCTIONS
##############################################################################
def write_file(directory, filename, lines):
f = open(directory + filename, "w")
f.writelines(lines)
f.close()
def get_qwen_tokenizer_with_markers(marker_list):
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
# If no new markers to add, return normal tokenizer
if len(marker_list) == 0:
return tokenizer
# Create tokens and return modified tokenizer
new_tokens = []
for marker in marker_list:
new_tokens.append(AddedToken(marker, lstrip=True, rstrip=False))
tokenizer.add_tokens(new_tokens)
return tokenizer
qwen_original_tokenizer = get_qwen_tokenizer_with_markers([])
# GPT-2 hop tokenization
qwen_hop_tokenizer = get_qwen_tokenizer_with_markers(
[MARKER_HOP_SING, MARKER_HOP_PLUR])
# Get ids of marker tokens
marker_sg_token = qwen_hop_tokenizer.get_added_vocab()[
MARKER_HOP_SING]
# Yj:获取分词器中所有自定义添加的标记及其对应的 token ID
marker_pl_token = qwen_hop_tokenizer.get_added_vocab()[
MARKER_HOP_PLUR]
# Qwen reverse tokenization
qwen_rev_tokenizer = get_qwen_tokenizer_with_markers(
[MARKER_REV])
# Get ids of marker tokens
marker_rev_token = qwen_rev_tokenizer.get_added_vocab()[
MARKER_REV]
# Qwen determiner tokenization
qwen_det_tokenizer = get_qwen_tokenizer_with_markers(
[BOS_TOKEN])
# Get id of BOS token
bos_token_id = qwen_det_tokenizer.get_added_vocab()[BOS_TOKEN]
MARKER_TOKEN_IDS = [marker_sg_token, marker_pl_token, marker_rev_token]
def compute_surprisals(model, input_ids):
# Get the log probabilities from the model
with torch.no_grad():
outputs = model(input_ids)
logits = outputs.logits[:, :-1]
shifted_input_ids = input_ids[:, 1:]
# Get the log probabilities for the actual next tokens
log_probs = torch.log2(torch.nn.functional.softmax(logits, dim=-1))
true_log_probs = log_probs.gather(
2, shifted_input_ids.unsqueeze(-1)).squeeze(-1)
# Get the negative log probabilities
neg_log_probs = (-true_log_probs).tolist()
surprisals = [[None] + probs for probs in neg_log_probs]
return surprisals
def compute_token_probabilities(model, input_ids, token_id, pad_token_id):
# Get the log probabilities from the model
with torch.no_grad():
outputs = model(input_ids)
logits = outputs.logits[:, :-1]
probs = torch.nn.functional.softmax(logits, dim=-1)
# Get the probabilities for the specified token at each position
token_probs = probs[:, :, token_id]
# Convert to list and add None at the beginning to align with input tokens
# Put null probability for instances of pad token
token_probs_list = []
for batch_i, probs in enumerate(token_probs):
input_ids_seq = input_ids[batch_i].tolist() + [pad_token_id]
filtered = [p if input_ids_seq[pos_i+1] !=
pad_token_id else None for pos_i, p in enumerate(probs.tolist())]
token_probs_list.append([None] + filtered)
return token_probs_list
def merge_part_tokens(words):
result = []
for s in words:
if result and s in PART_TOKENS and len(result) > 0:
result[-1] += s
else:
result.append(s)
return result
def __affect_hop_word(word):
return word["feats"] and "Person=3" in word["feats"] \
and "Tense=Pres" in word["feats"] \
and "VerbForm=Fin" in word["feats"] \
and "Number" in word["feats"]
def __perturb_hop_words(sent, num_hops, marker_sg, marker_pl):
perturbed_tokens, _ = __perturb_hop_words_complete_hops(
sent, num_hops, marker_sg, marker_pl)
return perturbed_tokens
def check_word_hops_completed(sent, num_hops=4, marker=MARKER_HOP_SING):
_, hops_completed = __perturb_hop_words_complete_hops(
sent, num_hops, marker, marker)
return hops_completed
def __perturb_hop_words_complete_hops(sent, num_hops, marker_sg, marker_pl):
word_annotations = sent["word_annotations"].copy()
word_annotations.reverse()
hop_completed = []
new_sent = []
for word in word_annotations:
# Identify 3.pres verbs
if __affect_hop_word(word):
# Lemmatize verb if possible
new_sent.append(
word["lemma"] if word["lemma"] is not None else word["text"])
# Marker hopping logic
insert_index = len(new_sent)-1
skipped_words = 0
while skipped_words < num_hops and insert_index > 0:
# Handle edge case when punctuation (or sequence of
# punctuation) begin the sentence
if (not any([c.isalnum() for c in
"".join(new_sent[:insert_index])])):
break
# Yj: 如果字符串中不存在任何字母或数字字符(即都是标点、空格等)
# Count word as skipped if it is not a special token
if (new_sent[insert_index] not in PART_TOKENS) and \
(not set(new_sent[insert_index]).issubset(PUNCT_TOKENS)):
skipped_words += 1
insert_index -= 1
# Handle edge case when insert index is punctuation (and this is not
# sentence-initial punctuation)
if any([c.isalnum() for c in
"".join(new_sent[:insert_index])]):
while insert_index != 0 and (new_sent[insert_index] in PART_TOKENS
or set(new_sent[insert_index]).issubset(PUNCT_TOKENS)):
insert_index -= 1
# Handle edge case when token before insert index is part/aux token
if insert_index != 0 and new_sent[insert_index-1] in PART_TOKENS:
insert_index -= 1
# Log if this sentence had all full hops
hop_completed.append(skipped_words == num_hops)
# Use correct marker for singular vs. plural
if "Number=Sing" in word["feats"]:
new_sent.insert(insert_index, marker_sg)
elif "Number=Plur" in word["feats"]:
new_sent.insert(insert_index, marker_pl)
else:
raise Exception(
"Number not in verb features\n" + sent["sent_text"])
else:
new_sent.append(word["text"])
new_sent.reverse()
sent_string = " ".join(merge_part_tokens(new_sent))
tokens = qwen_hop_tokenizer.encode(sent_string)
return tokens, all(hop_completed) and len(hop_completed) > 0
def __perturb_hop_tokens(sent, num_hops):
word_annotations = sent["word_annotations"].copy()
word_annotations.reverse()
new_sent = deque()
tokens = []
for word in word_annotations:
# Identify 3.pres verbs
if __affect_hop_word(word):
# Lemmatize verb if possible
lemma = word["lemma"] if word["lemma"] is not None else word["text"]
if len(new_sent) > 0 and new_sent[0] in PART_TOKENS:
lemma = lemma + new_sent[0]
new_sent.popleft()
if len(new_sent) > 0:
sent_string = " ".join(merge_part_tokens(new_sent))
tokens = qwen_hop_tokenizer.encode(
" " + sent_string) + tokens
# Use correct marker for singular vs. plural
if "Number=Sing" in word["feats"]:
tokens.insert(num_hops, marker_sg_token)
elif "Number=Plur" in word["feats"]:
tokens.insert(num_hops, marker_pl_token)
else:
raise Exception(
"Number not in verb features\n" + sent["sent_text"])
new_sent = deque()
new_sent.append(lemma)
else:
new_sent.appendleft(word["text"])
if len(new_sent) > 0:
sent_string = " ".join(merge_part_tokens(new_sent))
tokens = qwen_hop_tokenizer.encode(sent_string) + tokens
return tokens
def __perturb_reverse(sent, rng, reverse, full):
# Get sentence text and GPT-2 tokens
tokens = qwen_rev_tokenizer.encode(sent["sent_text"])
# Pick random index to insert REV token
i = rng.choice(len(tokens)+1)
tokens.insert(i, marker_rev_token)
# Extract tokens before/after the marker, and reverse tokens after
tokens_before = tokens[:i+1]
tokens_after = tokens[i+1:]
if reverse:
tokens_after.reverse()
new_tokens = tokens_before + tokens_after
if full:
assert not reverse
new_tokens.reverse()
return new_tokens
def __perturb_shuffle_deterministic(sent, seed, shuffle):
# Get sentence text and GPT-2 tokens
tokens = qwen_original_tokenizer.encode(sent["sent_text"])
if shuffle:
default_rng(seed).shuffle(tokens)
return tokens
def __perturb_shuffle_nondeterministic(sent, rng):
# Get sentence text and GPT-2 tokens
tokens = qwen_original_tokenizer.encode(sent["sent_text"])
rng.shuffle(tokens)
return tokens
def __perturb_shuffle_local(sent, seed, window=5):
# Get sentence text and GPT-2 tokens
tokens = qwen_original_tokenizer.encode(sent["sent_text"])
# Shuffle tokens in batches of size window
shuffled_tokens = []
for i in range(0, len(tokens), window):
batch = tokens[i:i+window].copy()
default_rng(seed).shuffle(batch)
shuffled_tokens += batch
return shuffled_tokens
def __perturb_shuffle_even_odd(sent):
# Get sentence text and GPT-2 tokens
tokens = qwen_original_tokenizer.encode(sent["sent_text"])
even = [tok for i, tok in enumerate(tokens) if i % 2 == 0]
odd = [tok for i, tok in enumerate(tokens) if i % 2 != 0]
return even + odd
##############################################################################
# AFFECT FUNCTIONS
# These functions define when a perturbation has been applied to a sentence
# not. This is used for identifying which test sentences have been
# altered to separate affected vs. unaffected senences. Affect functions are
# functions of the input sentence object and return a boolean.
##############################################################################
def affect_hop(sent):
return any([__affect_hop_word(word) for word in sent['word_annotations']]) \
and sent["constituency_parse"] is not None
def affect_reverse(sent):
return True
def affect_shuffle(sent):
return True
def affect_none(sent):
return False
##############################################################################
# FILTER FUNCTIONS
# These functions define when an affected sentence should be included in the
# final dataset. For instance, hop perturbations where the marker is placed
# at the end of the sentence should be excluded. A filter function returns
# True if an affected sentence should be included in the dataset.
##############################################################################
def filter_hop(sent):
# Assertion needed since filter function is only defined for affected
# sentences
assert (affect_hop(sent))
return check_word_hops_completed(sent, 4)
def filter_reverse(sent):
return True
def filter_shuffle(sent):
tokens = qwen_original_tokenizer.encode(sent["sent_text"])
return len(tokens) > 1 and len(tokens) <= 350
def filter_none(sent):
return False
##############################################################################
# PERTURBATION FUNCTIONS
# These functions define how a perturbation will affect a sentence. They
# take in a sentence object and an optional marker
# for verb transformations. They return a string representing the transformed
# sentence.
##############################################################################
def perturb_hop_words4(sent):
return __perturb_hop_words(sent, 4, MARKER_HOP_SING, MARKER_HOP_PLUR)
def perturb_hop_tokens4(sent):
return __perturb_hop_tokens(sent, 4)
def perturb_hop_control(sent):
return __perturb_hop_tokens(sent, 0)
def perturb_reverse(sent, rng, reverse=True, full=False):
return __perturb_reverse(sent, rng, reverse, full)
def perturb_shuffle_deterministic(sent, seed=None, shuffle=True):
return __perturb_shuffle_deterministic(sent, seed, shuffle)
def perturb_shuffle_nondeterministic(sent, rng):
return __perturb_shuffle_nondeterministic(sent, rng)
def perturb_shuffle_local(sent, seed, window):
return __perturb_shuffle_local(sent, seed, window)
def perturb_shuffle_even_odd(sent):
return __perturb_shuffle_even_odd(sent)
##############################################################################
# PERTURBATIONS
# This dict maps the name of a perturbation to its perturbation and filter
# functions. The names and functions in this dict are used throughout the
# repo.
##############################################################################
PERTURBATIONS = {
"shuffle_control": {
"perturbation_function": partial(perturb_shuffle_deterministic, seed=None, shuffle=False),
"affect_function": affect_shuffle,
"filter_function": filter_shuffle,
"qwen_tokenizer": qwen_original_tokenizer,
"color": "#606060",
},
"shuffle_nondeterministic": {
"perturbation_function": partial(perturb_shuffle_nondeterministic, rng=default_rng(0)),
"affect_function": affect_shuffle,
"filter_function": filter_shuffle,
"qwen_tokenizer": qwen_original_tokenizer,
"color": "#E8384F",
},
"shuffle_deterministic21": {
"perturbation_function": partial(perturb_shuffle_deterministic, seed=21, shuffle=True),
"affect_function": affect_shuffle,
"filter_function": filter_shuffle,
"qwen_tokenizer": qwen_original_tokenizer,
"color": "#FFB000",
},
"shuffle_deterministic57": {
"perturbation_function": partial(perturb_shuffle_deterministic, seed=57, shuffle=True),
"affect_function": affect_shuffle,
"filter_function": filter_shuffle,
"qwen_tokenizer": qwen_original_tokenizer,
"color": "#8db000",
},
"shuffle_deterministic84": {
"perturbation_function": partial(perturb_shuffle_deterministic, seed=84, shuffle=True),
"affect_function": affect_shuffle,
"filter_function": filter_shuffle,
"qwen_tokenizer": qwen_original_tokenizer,
"color": "#62BB35",
},
"shuffle_local3": {
"perturbation_function": partial(perturb_shuffle_local, seed=0, window=3),
"affect_function": affect_shuffle,
"filter_function": filter_shuffle,
"qwen_tokenizer": qwen_original_tokenizer,
"color": "#208EA3",
},
"shuffle_local5": {
"perturbation_function": partial(perturb_shuffle_local, seed=0, window=5),
"affect_function": affect_shuffle,
"filter_function": filter_shuffle,
"qwen_tokenizer": qwen_original_tokenizer,
"color": "#4178BC",
},
"shuffle_local10": {
"perturbation_function": partial(perturb_shuffle_local, seed=0, window=10),
"affect_function": affect_shuffle,
"filter_function": filter_shuffle,
"qwen_tokenizer": qwen_original_tokenizer,
"color": "#AA71FF",
},
"shuffle_even_odd": {
"perturbation_function": perturb_shuffle_even_odd,
"affect_function": affect_shuffle,
"filter_function": filter_shuffle,
"qwen_tokenizer": qwen_original_tokenizer,
"color": "#E37CFF",
},
"reverse_control": {
"perturbation_function": partial(perturb_reverse, rng=default_rng(21), reverse=False, full=False),
"affect_function": affect_reverse,
"filter_function": filter_reverse,
"qwen_tokenizer": qwen_rev_tokenizer,
"color": "#606060",
},
"reverse_partial": {
"perturbation_function": partial(perturb_reverse, rng=default_rng(21), reverse=True, full=False),
"affect_function": affect_reverse,
"filter_function": filter_reverse,
"qwen_tokenizer": qwen_rev_tokenizer,
"color": "#E5A836",
},
"reverse_full": {
"perturbation_function": partial(perturb_reverse, rng=default_rng(21), reverse=False, full=True),
"affect_function": affect_reverse,
"filter_function": filter_reverse,
"qwen_tokenizer": qwen_rev_tokenizer,
"color": "#A348A6",
},
"hop_control": {
"perturbation_function": perturb_hop_control,
"affect_function": affect_hop,
"filter_function": filter_hop,
"qwen_tokenizer": qwen_hop_tokenizer,
"color": "#606060",
},
"hop_tokens4": {
"perturbation_function": perturb_hop_tokens4,
"affect_function": affect_hop,
"filter_function": filter_hop,
"qwen_tokenizer": qwen_hop_tokenizer,
"color": "#fa8128",
},
"hop_words4": {
"perturbation_function": perturb_hop_words4,
"affect_function": affect_hop,
"filter_function": filter_hop,
"qwen_tokenizer": qwen_hop_tokenizer,
"color": "#03a0ff",
},
}
# # utils.py
# # Author: Julie Kallini
# from collections import deque
# from string import punctuation
# from transformers import AutoTokenizer, AddedToken
# from functools import partial
# from numpy.random import default_rng
# from nltk.tree import ParentedTree
# import torch
# ##############################################################################
# # CONSTANTS
# ##############################################################################
# BABYLM_SPLITS = ['100M', '10M', 'dev', 'test', 'unittest']
# # Yj: 用于在参数解析和数据加载时指定数据集
# # 影响数据集的预处理过程,如生成训练、开发、测试和单元测试集。
# SEEDS = [21, 57, 84]
# CHECKPOINTS = list(range(50, 501, 50))
# GENRES = {
# "aochildes": "CHILDES",
# "bnc_spoken": "British National Corpus (BNC)",
# "cbt": "Children’s Book Test",
# "children_stories": "Children’s Stories Text Corpus",
# "gutenberg": "Standardized Project Gutenberg Corpus",
# "open_subtitles": "OpenSubtitles",
# "qed": "QCRI Educational Domain Corpus",
# "simple_wikipedia": "Simple Wikipedia",
# "switchboard": "Switchboard Dialog Act Corpus",
# "wikipedia": "Wikipedia"
# }
# CHECKPOINT_WRITE_PATH = "/nlp/scr3/nlp/llms-in-llms/babylm_models"
# CHECKPOINT_READ_PATH = "/nlp/scr3/nlp/llms-in-llms/babylm_models"
# # BABYLM_DATA_PATH = "/nlp/scr3/nlp/llms-in-llms/babylm_data"
# BABYLM_DATA_PATH = "."
# MARKER_HOP_SING = "🅂"
# MARKER_HOP_PLUR = "🄿"
# MARKER_REV = "🅁"
# BOS_TOKEN = "<BOS_TOKEN>"
# PART_TOKENS = set(["n't", "'ll", "'s", "'re", "'ve", "'m"])
# PUNCT_TOKENS = set(punctuation)
# ##############################################################################
# # PARENS MODELS (Structurally-pretrained)
# ##############################################################################
# PAREN_MODEL_PATH = "/u/scr/isabelvp//tilt-stuff/tilt-finetuning/pretrained_checkpoints/"
# PAREN_MODELS = {
# "CROSS": "flat-parens_vocab500-uniform_deplength-nesting-nolimit",
# "NEST": "nested-parens0.49_vocab500-uniform",
# "RAND": "random_vocab500-uniform",
# }
# ##############################################################################
# # HELPER FUNCTIONS
# ##############################################################################
# def write_file(directory, filename, lines):
# f = open(directory + filename, "w")
# f.writelines(lines)
# f.close()
# def get_gpt2_tokenizer_with_markers(marker_list):
# tokenizer = AutoTokenizer.from_pretrained("gpt2")
# # If no new markers to add, return normal tokenizer
# if len(marker_list) == 0:
# return tokenizer
# # Create tokens and return modified tokenizer
# new_tokens = []
# for marker in marker_list:
# new_tokens.append(AddedToken(marker, lstrip=True, rstrip=False))
# tokenizer.add_tokens(new_tokens)
# return tokenizer
# gpt2_original_tokenizer = get_gpt2_tokenizer_with_markers([])
# # GPT-2 hop tokenization
# gpt2_hop_tokenizer = get_gpt2_tokenizer_with_markers(
# [MARKER_HOP_SING, MARKER_HOP_PLUR])
# # Get ids of marker tokens
# marker_sg_token = gpt2_hop_tokenizer.get_added_vocab()[
# MARKER_HOP_SING]
# # Yj:获取分词器中所有自定义添加的标记及其对应的 token ID
# marker_pl_token = gpt2_hop_tokenizer.get_added_vocab()[
# MARKER_HOP_PLUR]
# # GPT-2 reverse tokenization
# gpt2_rev_tokenizer = get_gpt2_tokenizer_with_markers(
# [MARKER_REV])
# # Get ids of marker tokens
# marker_rev_token = gpt2_rev_tokenizer.get_added_vocab()[
# MARKER_REV]
# # GPT-2 determiner tokenization
# gpt2_det_tokenizer = get_gpt2_tokenizer_with_markers(
# [BOS_TOKEN])
# # Get id of BOS token
# bos_token_id = gpt2_det_tokenizer.get_added_vocab()[BOS_TOKEN]
# MARKER_TOKEN_IDS = [marker_sg_token, marker_pl_token, marker_rev_token]
# def compute_surprisals(model, input_ids):
# # Get the log probabilities from the model
# with torch.no_grad():
# outputs = model(input_ids)
# logits = outputs.logits[:, :-1]
# shifted_input_ids = input_ids[:, 1:]
# # Get the log probabilities for the actual next tokens
# log_probs = torch.log2(torch.nn.functional.softmax(logits, dim=-1))
# true_log_probs = log_probs.gather(
# 2, shifted_input_ids.unsqueeze(-1)).squeeze(-1)
# # Get the negative log probabilities
# neg_log_probs = (-true_log_probs).tolist()
# surprisals = [[None] + probs for probs in neg_log_probs]
# return surprisals
# def compute_token_probabilities(model, input_ids, token_id, pad_token_id):
# # Get the log probabilities from the model
# with torch.no_grad():
# outputs = model(input_ids)
# logits = outputs.logits[:, :-1]
# probs = torch.nn.functional.softmax(logits, dim=-1)
# # Get the probabilities for the specified token at each position
# token_probs = probs[:, :, token_id]
# # Convert to list and add None at the beginning to align with input tokens
# # Put null probability for instances of pad token
# token_probs_list = []
# for batch_i, probs in enumerate(token_probs):
# input_ids_seq = input_ids[batch_i].tolist() + [pad_token_id]
# filtered = [p if input_ids_seq[pos_i+1] !=
# pad_token_id else None for pos_i, p in enumerate(probs.tolist())]
# token_probs_list.append([None] + filtered)
# return token_probs_list
# def merge_part_tokens(words):
# result = []
# for s in words:
# if result and s in PART_TOKENS and len(result) > 0:
# result[-1] += s
# else:
# result.append(s)
# return result
# def __affect_hop_word(word):
# return word["feats"] and "Person=3" in word["feats"] \
# and "Tense=Pres" in word["feats"] \
# and "VerbForm=Fin" in word["feats"] \
# and "Number" in word["feats"]
# def __perturb_hop_words(sent, num_hops, marker_sg, marker_pl):
# perturbed_tokens, _ = __perturb_hop_words_complete_hops(
# sent, num_hops, marker_sg, marker_pl)
# return perturbed_tokens
# def check_word_hops_completed(sent, num_hops=4, marker=MARKER_HOP_SING):
# _, hops_completed = __perturb_hop_words_complete_hops(
# sent, num_hops, marker, marker)
# return hops_completed
# def __perturb_hop_words_complete_hops(sent, num_hops, marker_sg, marker_pl):
# word_annotations = sent["word_annotations"].copy()
# word_annotations.reverse()
# hop_completed = []
# new_sent = []
# for word in word_annotations:
# # Identify 3.pres verbs
# if __affect_hop_word(word):
# # Lemmatize verb if possible
# new_sent.append(
# word["lemma"] if word["lemma"] is not None else word["text"])
# # Marker hopping logic
# insert_index = len(new_sent)-1
# skipped_words = 0
# while skipped_words < num_hops and insert_index > 0:
# # Handle edge case when punctuation (or sequence of
# # punctuation) begin the sentence
# if (not any([c.isalnum() for c in
# "".join(new_sent[:insert_index])])):
# break
# # Yj: 如果字符串中不存在任何字母或数字字符(即都是标点、空格等)
# # Count word as skipped if it is not a special token
# if (new_sent[insert_index] not in PART_TOKENS) and \
# (not set(new_sent[insert_index]).issubset(PUNCT_TOKENS)):
# skipped_words += 1
# insert_index -= 1
# # Handle edge case when insert index is punctuation (and this is not
# # sentence-initial punctuation)
# if any([c.isalnum() for c in
# "".join(new_sent[:insert_index])]):
# while insert_index != 0 and (new_sent[insert_index] in PART_TOKENS
# or set(new_sent[insert_index]).issubset(PUNCT_TOKENS)):
# insert_index -= 1
# # Handle edge case when token before insert index is part/aux token
# if insert_index != 0 and new_sent[insert_index-1] in PART_TOKENS:
# insert_index -= 1
# # Log if this sentence had all full hops
# hop_completed.append(skipped_words == num_hops)
# # Use correct marker for singular vs. plural
# if "Number=Sing" in word["feats"]:
# new_sent.insert(insert_index, marker_sg)
# elif "Number=Plur" in word["feats"]:
# new_sent.insert(insert_index, marker_pl)
# else:
# raise Exception(
# "Number not in verb features\n" + sent["sent_text"])
# else:
# new_sent.append(word["text"])
# new_sent.reverse()
# sent_string = " ".join(merge_part_tokens(new_sent))
# tokens = gpt2_hop_tokenizer.encode(sent_string)
# return tokens, all(hop_completed) and len(hop_completed) > 0
# def __perturb_hop_tokens(sent, num_hops):
# word_annotations = sent["word_annotations"].copy()
# word_annotations.reverse()
# new_sent = deque()
# tokens = []
# for word in word_annotations:
# # Identify 3.pres verbs
# if __affect_hop_word(word):
# # Lemmatize verb if possible
# lemma = word["lemma"] if word["lemma"] is not None else word["text"]
# if len(new_sent) > 0 and new_sent[0] in PART_TOKENS:
# lemma = lemma + new_sent[0]
# new_sent.popleft()
# if len(new_sent) > 0:
# sent_string = " ".join(merge_part_tokens(new_sent))
# tokens = gpt2_hop_tokenizer.encode(
# " " + sent_string) + tokens
# # Use correct marker for singular vs. plural
# if "Number=Sing" in word["feats"]:
# tokens.insert(num_hops, marker_sg_token)
# elif "Number=Plur" in word["feats"]:
# tokens.insert(num_hops, marker_pl_token)
# else:
# raise Exception(
# "Number not in verb features\n" + sent["sent_text"])
# new_sent = deque()
# new_sent.append(lemma)
# else:
# new_sent.appendleft(word["text"])
# if len(new_sent) > 0:
# sent_string = " ".join(merge_part_tokens(new_sent))
# tokens = gpt2_hop_tokenizer.encode(sent_string) + tokens
# return tokens
# def __perturb_reverse(sent, rng, reverse, full):
# # Get sentence text and GPT-2 tokens
# tokens = gpt2_rev_tokenizer.encode(sent["sent_text"])
# # Pick random index to insert REV token
# i = rng.choice(len(tokens)+1)
# tokens.insert(i, marker_rev_token)
# # Extract tokens before/after the marker, and reverse tokens after
# tokens_before = tokens[:i+1]
# tokens_after = tokens[i+1:]
# if reverse:
# tokens_after.reverse()
# new_tokens = tokens_before + tokens_after
# if full:
# assert not reverse
# new_tokens.reverse()
# return new_tokens
# def __perturb_shuffle_deterministic(sent, seed, shuffle):
# # Get sentence text and GPT-2 tokens
# tokens = gpt2_original_tokenizer.encode(sent["sent_text"])
# if shuffle:
# default_rng(seed).shuffle(tokens)
# return tokens
# def __perturb_shuffle_nondeterministic(sent, rng):
# # Get sentence text and GPT-2 tokens
# tokens = gpt2_original_tokenizer.encode(sent["sent_text"])
# rng.shuffle(tokens)
# return tokens
# def __perturb_shuffle_local(sent, seed, window=5):
# # Get sentence text and GPT-2 tokens
# tokens = gpt2_original_tokenizer.encode(sent["sent_text"])
# # Shuffle tokens in batches of size window
# shuffled_tokens = []
# for i in range(0, len(tokens), window):
# batch = tokens[i:i+window].copy()
# default_rng(seed).shuffle(batch)
# shuffled_tokens += batch
# return shuffled_tokens
# def __perturb_shuffle_even_odd(sent):
# # Get sentence text and GPT-2 tokens
# tokens = gpt2_original_tokenizer.encode(sent["sent_text"])
# even = [tok for i, tok in enumerate(tokens) if i % 2 == 0]
# odd = [tok for i, tok in enumerate(tokens) if i % 2 != 0]
# return even + odd
# ##############################################################################
# # AFFECT FUNCTIONS
# # These functions define when a perturbation has been applied to a sentence
# # not. This is used for identifying which test sentences have been
# # altered to separate affected vs. unaffected senences. Affect functions are
# # functions of the input sentence object and return a boolean.
# ##############################################################################
# def affect_hop(sent):
# return any([__affect_hop_word(word) for word in sent['word_annotations']]) \
# and sent["constituency_parse"] is not None
# def affect_reverse(sent):
# return True
# def affect_shuffle(sent):
# return True
# def affect_none(sent):
# return False
# ##############################################################################
# # FILTER FUNCTIONS
# # These functions define when an affected sentence should be included in the
# # final dataset. For instance, hop perturbations where the marker is placed
# # at the end of the sentence should be excluded. A filter function returns
# # True if an affected sentence should be included in the dataset.
# ##############################################################################
# def filter_hop(sent):
# # Assertion needed since filter function is only defined for affected
# # sentences
# assert (affect_hop(sent))
# return check_word_hops_completed(sent, 4)
# def filter_reverse(sent):
# return True
# def filter_shuffle(sent):
# tokens = gpt2_original_tokenizer.encode(sent["sent_text"])
# return len(tokens) > 1 and len(tokens) <= 350
# def filter_none(sent):
# return False
# ##############################################################################
# # PERTURBATION FUNCTIONS
# # These functions define how a perturbation will affect a sentence. They
# # take in a sentence object and an optional marker
# # for verb transformations. They return a string representing the transformed
# # sentence.
# ##############################################################################
# def perturb_hop_words4(sent):
# return __perturb_hop_words(sent, 4, MARKER_HOP_SING, MARKER_HOP_PLUR)
# def perturb_hop_tokens4(sent):
# return __perturb_hop_tokens(sent, 4)
# def perturb_hop_control(sent):
# return __perturb_hop_tokens(sent, 0)
# def perturb_reverse(sent, rng, reverse=True, full=False):
# return __perturb_reverse(sent, rng, reverse, full)
# def perturb_shuffle_deterministic(sent, seed=None, shuffle=True):
# return __perturb_shuffle_deterministic(sent, seed, shuffle)
# def perturb_shuffle_nondeterministic(sent, rng):
# return __perturb_shuffle_nondeterministic(sent, rng)
# def perturb_shuffle_local(sent, seed, window):
# return __perturb_shuffle_local(sent, seed, window)
# def perturb_shuffle_even_odd(sent):
# return __perturb_shuffle_even_odd(sent)
# ##############################################################################
# # PERTURBATIONS
# # This dict maps the name of a perturbation to its perturbation and filter
# # functions. The names and functions in this dict are used throughout the
# # repo.
# ##############################################################################
# PERTURBATIONS = {
# "shuffle_control": {
# "perturbation_function": partial(perturb_shuffle_deterministic, seed=None, shuffle=False),
# "affect_function": affect_shuffle,
# "filter_function": filter_shuffle,
# "gpt2_tokenizer": gpt2_original_tokenizer,
# "color": "#606060",
# },
# "shuffle_nondeterministic": {
# "perturbation_function": partial(perturb_shuffle_nondeterministic, rng=default_rng(0)),
# "affect_function": affect_shuffle,
# "filter_function": filter_shuffle,
# "gpt2_tokenizer": gpt2_original_tokenizer,
# "color": "#E8384F",
# },
# "shuffle_deterministic21": {
# "perturbation_function": partial(perturb_shuffle_deterministic, seed=21, shuffle=True),
# "affect_function": affect_shuffle,
# "filter_function": filter_shuffle,
# "gpt2_tokenizer": gpt2_original_tokenizer,
# "color": "#FFB000",
# },
# "shuffle_deterministic57": {
# "perturbation_function": partial(perturb_shuffle_deterministic, seed=57, shuffle=True),
# "affect_function": affect_shuffle,
# "filter_function": filter_shuffle,
# "gpt2_tokenizer": gpt2_original_tokenizer,
# "color": "#8db000",
# },
# "shuffle_deterministic84": {
# "perturbation_function": partial(perturb_shuffle_deterministic, seed=84, shuffle=True),
# "affect_function": affect_shuffle,
# "filter_function": filter_shuffle,
# "gpt2_tokenizer": gpt2_original_tokenizer,
# "color": "#62BB35",
# },
# "shuffle_local3": {
# "perturbation_function": partial(perturb_shuffle_local, seed=0, window=3),
# "affect_function": affect_shuffle,
# "filter_function": filter_shuffle,
# "gpt2_tokenizer": gpt2_original_tokenizer,
# "color": "#208EA3",
# },
# "shuffle_local5": {
# "perturbation_function": partial(perturb_shuffle_local, seed=0, window=5),
# "affect_function": affect_shuffle,
# "filter_function": filter_shuffle,
# "gpt2_tokenizer": gpt2_original_tokenizer,
# "color": "#4178BC",
# },
# "shuffle_local10": {
# "perturbation_function": partial(perturb_shuffle_local, seed=0, window=10),
# "affect_function": affect_shuffle,
# "filter_function": filter_shuffle,
# "gpt2_tokenizer": gpt2_original_tokenizer,
# "color": "#AA71FF",
# },
# "shuffle_even_odd": {
# "perturbation_function": perturb_shuffle_even_odd,
# "affect_function": affect_shuffle,
# "filter_function": filter_shuffle,
# "gpt2_tokenizer": gpt2_original_tokenizer,
# "color": "#E37CFF",
# },
# "reverse_control": {
# "perturbation_function": partial(perturb_reverse, rng=default_rng(21), reverse=False, full=False),
# "affect_function": affect_reverse,
# "filter_function": filter_reverse,
# "gpt2_tokenizer": gpt2_rev_tokenizer,
# "color": "#606060",
# },
# "reverse_partial": {
# "perturbation_function": partial(perturb_reverse, rng=default_rng(21), reverse=True, full=False),
# "affect_function": affect_reverse,
# "filter_function": filter_reverse,
# "gpt2_tokenizer": gpt2_rev_tokenizer,
# "color": "#E5A836",
# },
# "reverse_full": {
# "perturbation_function": partial(perturb_reverse, rng=default_rng(21), reverse=False, full=True),
# "affect_function": affect_reverse,
# "filter_function": filter_reverse,
# "gpt2_tokenizer": gpt2_rev_tokenizer,
# "color": "#A348A6",
# },
# "hop_control": {
# "perturbation_function": perturb_hop_control,
# "affect_function": affect_hop,
# "filter_function": filter_hop,
# "gpt2_tokenizer": gpt2_hop_tokenizer,
# "color": "#606060",
# },
# "hop_tokens4": {
# "perturbation_function": perturb_hop_tokens4,
# "affect_function": affect_hop,
# "filter_function": filter_hop,
# "gpt2_tokenizer": gpt2_hop_tokenizer,
# "color": "#fa8128",
# },
# "hop_words4": {
# "perturbation_function": perturb_hop_words4,
# "affect_function": affect_hop,
# "filter_function": filter_hop,
# "gpt2_tokenizer": gpt2_hop_tokenizer,
# "color": "#03a0ff",
# },
# }
|