CELL 1
1: import os
2: import safetensors.torch
3: 
4: weight_dict = {}
5: for root, dir, files in os.walk("./output/llama/xnli"):
6:     for file in files:
7:         if file.endswith(".safetensors") and "-6190" in root:
8:             langs = os.path.basename(os.path.dirname(root))
9:             path = os.path.join(root, file)
10:             weight_dict[langs] = safetensors.torch.load_file(path)["tensor"]
11: for root, dir, files in os.walk("./output/llama/fv"):
12:     for file in files:
13:         if file.endswith(".safetensors") and "-6250" in root:
14:             langs = os.path.basename(os.path.dirname(root))
15:             path = os.path.join(root, file)
16:             weight_dict[langs] = safetensors.torch.load_file(path)["tensor"]
17: print("Total tasks:", len(weight_dict))
18: print("Task name", "\t", "Weight", "\t", "# of up heads")
19: for k, v in sorted(weight_dict.items()):
20:     print(k, "\t", v, "\t", (v.sigmoid() >= 0.5).sum().item())

CELL 3
1: from transformers import AutoTokenizer
2: from models.modeling_llama import LlamaForCausalLM
3: from models.modeling_qwen2 import Qwen2ForCausalLM
4: from models.modeling_phi3 import Phi3ForCausalLM
5: from models.modeling_mistral import MistralForCausalLM
6: import torch
7: from torch import nn
8: DEVICE = "cuda:0"
9: 
10: MODEL_DIR = "/public/share/model/Meta-Llama-3.1-8B-Instruct"    # Your model path
11: model_name = os.path.basename(MODEL_DIR).lower()
12: tokenizer = AutoTokenizer.from_pretrained(MODEL_DIR, use_fast=True)
13: tokenizer.pad_token = tokenizer.eos_token
14: model = LlamaForCausalLM.from_pretrained(       # Change "xxxForCausalLM" to your model type
15:     MODEL_DIR, 
16:     local_files_only=True, 
17:     device_map=DEVICE, 
18:     torch_dtype=torch.bfloat16,
19:     attn_implementation="eager",
20:     max_position_embeddings=2048
21: )
22: model.generation_config.pad_token_id = tokenizer.pad_token_id
23: n_layers = model.config.num_hidden_layers
24: n_heads = model.config.num_attention_heads

CELL 5
1: TASK_DICT = {
2:     "lowercase_first_letter": "Output the first letter of the given word in lowercase.",
3:     "park-country": "Identify the country where the given national park is located.",
4:     "synonym": "Identify a synonym for the given word.",
5:     "ag_news": "Classify the given news headline into one of the categories: Business, Science, Sports, or World. Provide only the category name.",
6:     "word_length": "Determine the number of letters in the given word and output the count.",
7:     "present-past": "Convert the given verb from its present tense to its simple past tense.",
8:     "capitalize": "Output the given word with its first letter capitalized.",
9:     "landmark-country": "Identify the country where the given landmark is located.",
10:     "english-german": "Translate the given English word into German.",
11:     "sentiment": "Determine the sentiment of the given input. Output either 'positive' or 'negative'.",
12:     "country-capital": "What is the capital of the given country? Provide only the name of the capital.",
13:     "person-occupation": "Identify the occupation of the given individual.",
14:     "country-currency": "What is the official currency of the given country?",
15:     "lowercase_last_letter": "Output the last letter of the given word in lowercase.",
16:     "person-sport": "Identify the sport associated with the given individual.",
17:     "person-instrument": "Identify the musical instrument played by the given musician.",
18:     "antonym": "Identify the antonym of the given word.",
19:     "capitalize_last_letter": "Output the last letter of the given word in uppercase.",
20:     "english-french": "Translate the given English word into French.",
21:     "next_item": "What is the next sequential item following the given input?",
22:     "singular-plural": "Provide the plural form of the given singular noun.",
23:     "capitalize_second_letter": "Output the second letter of the given word in uppercase.",
24:     "prev_item": "What is the item that comes before the given input in a sequential context?",
25:     "capitalize_first_letter": "Output the first letter of the given word in uppercase.",
26:     "english-spanish": "Translate the given English word into Spanish.",
27:     "next_capital_letter": "What is the next uppercase letter in alphabetical order after the given input?",
28:     "national_parks": "Identify the U.S. state where the given national park is located.",
29:     "product-company": "Identify the company associated with the given product.",
30:     "conll2003_organization": "Extract the organization mentioned in the given text.",
31:     "conll2003_person": "Extract the name of the person mentioned in the given text.",
32:     "conll2003_location": "Extract the location mentioned in the given text.",
33:     "adjective_v_verb_3": "From the given words, identify the one that is an adjective.",
34:     "object_v_concept_3": "From the given words, identify the one that is a object.",
35:     "verb_v_adjective_3": "From the given words, identify the one that is a verb.",
36:     "fruit_v_animal_3": "From the given words, identify the one that is a fruit."
37: }

CELL 7
1: import datasets
2: import pandas as pd
3: import copy
4: import numpy as np
5: import itertools
6: from tqdm.notebook import tqdm
7: 
8: LLAMA_TEMPLATE = "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n{src}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n"
9: LLAMA_PLM_TEMPLATE = "<|begin_of_text|>{src}\n\n"
10: QWEN2_TEMPLATE = "<|im_start|>user\n{src}<|im_end|>\n<|im_start|>assistant\n"
11: QWEN2_PLM_TEMPLATE = "{src}\n\n"
12: 
13: if "llama" in model_name:
14:     if "instruct" in model_name:
15:         template = LLAMA_TEMPLATE
16:         print("using LLAMA_TEMPLATE")
17:     else:
18:         template = LLAMA_PLM_TEMPLATE
19:         print("using LLAMA_PLM_TEMPLATE")
20: elif "qwen2" in model_name:
21:     if "instruct" in model_name:
22:         template = QWEN2_TEMPLATE
23:         print("using QWEN2_TEMPLATE")
24:     else:
25:         template = QWEN2_PLM_TEMPLATE
26:         print("using QWEN2_PLM_TEMPLATE")
27: else:
28:     print("Unknown model")
29: 
30: # Build evaluation dataset
31: dev_datasets = []
32: for root, dirs, files in os.walk("./dataset/function_vectors/abstractive"):
33:     for file in files:
34:         if file.endswith(".json"):
35:             task = os.path.basename(file).split(".")[0]
36:             data_path = os.path.join(root, file)
37:             dataset = datasets.Dataset.from_json(data_path)
38:             dataset = dataset.map(
39:                 lambda sample: {
40:                     # Case w/ instruction: use this line
41:                     "input_str": TASK_DICT[task] + f"\n\nInput:\n\n{sample['input']}\n\nOutput:\n\n",
42:                     # Case w/o instruction: use this line
43:                     # "input_str": sample["input"],
44:                     "target_str": sample["output"],
45:                 }
46:             )
47: 
48:             dataset = dataset.remove_columns(["input", "output"])
49:             dev_dataset = dataset.select(range(len(dataset) - 100, len(dataset)))
50:             dev_datasets.append((task, dev_dataset))
51: # Run evaluation
52: for task, dataset in tqdm(dev_datasets):
53:     mask_weight = (weight_dict[task].sigmoid() >= 0.5).float().numpy()
54:     mask_tensor = torch.tensor(mask_weight).unsqueeze(0).repeat(1, 1).to(model.device)
55: 
56:     correct = 0
57:     for sample in dataset:
58:         input_str, target_str = str(sample["input_str"]), str(sample["target_str"])
59:         combined_str = template.format(src=input_str.strip())
60:         lm_inputs_src = tokenizer(
61:             combined_str, 
62:             max_length=2048, 
63:             truncation=True, 
64:             padding=False, 
65:             add_special_tokens=False,
66:             return_tensors="pt"
67:         ).to(DEVICE)
68: 
69:         with torch.no_grad():
70:             # Case w/o mask: use this line
71:             generate_ids = model.generate(**lm_inputs_src, max_new_tokens=10, weight_tensor=None, do_sample=False)
72:             # Case w/ mask: use this line
73:             # generate_ids = model.generate(**lm_inputs_src, max_new_tokens=10, weight_tensor=mask_tensor, do_sample=False)
74:             pred_str = tokenizer.decode(generate_ids[0][lm_inputs_src.input_ids.size(1):], skip_special_tokens=True)
75:         if task in [
76:             "capitalize_first_letter", "capitalize_last_letter", "capitalize_second_letter", "capitalize", 
77:             "lowercase_first_letter", "lowercase_last_letter", "next_capital_letter", "next_item", "prev_item", "commonsense_qa",
78:             "conll2003_organization", "conll2003_person", "conll2003_location", 
79:             "adjective_v_verb_3", "object_v_concept_3", "verb_v_adjective_3", "fruit_v_animal_3",
80:         ]:
81:             if pred_str.strip().startswith(target_str.strip()):
82:                 correct += 1
83:         else:
84:             if target_str.strip() in pred_str.strip():
85:                 correct += 1
86:     score = correct / len(dataset)
87:     print(f"{task}: {score}")

CELL 9
1: import pandas as pd
2: import numpy as np
3: import matplotlib.pyplot as plt
4: plt.rcParams['font.sans-serif'] = ["WenQuanYi Zen Hei"]
5: plt.rcParams['axes.unicode_minus'] = False
6: import seaborn as sns
7: from tqdm.notebook import tqdm
8: import pandas as pd
9: from IPython.display import display
10: LLAMA_TEMPLATE = "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n{src}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n"
11: LLAMA_PLM_TEMPLATE = "<|begin_of_text|>{src}\n\n"
12: 
13: dev_datasets = []
14: for root, dirs, files in os.walk("./dataset/function_vectors/abstractive"):
15:     for file in files:
16:         if file.endswith(".json"):
17:             task = os.path.basename(file).split(".")[0]
18:             if "_v_" not in task: continue
19:             data_path = os.path.join(root, file)
20:             dataset = datasets.Dataset.from_json(data_path)
21:             dataset = dataset.map(
22:                 lambda sample: {
23:                     "input_str": sample["input"],
24:                     "target_str": sample["output"],
25:                 }
26:             )
27:             dataset = dataset.remove_columns(["input", "output"])
28:             dev_dataset = dataset.select(range(len(dataset) - 100, len(dataset)))
29:             dev_datasets.append((task, dev_dataset))
30: 
31: def find_segments_(l):
32:     indices_271 = [i for i, x in enumerate(l) if x == 271]
33:     start, end = indices_271[0], indices_271[1]
34:     segment = l[start + 1:end]
35: 
36:     segments = []
37:     current_segment = []
38:     for idx, value in enumerate(segment, start=start + 1):
39:         if value == 11:
40:             if current_segment:
41:                 segments.append(current_segment)
42:                 current_segment = []
43:         else:
44:             current_segment.append(idx)
45:     if current_segment:
46:         segments.append(current_segment)
47:     
48:     return segments
49: 
50: task_attentions = {}
51: for task, dataset in tqdm(dev_datasets):
52:     mask_weight = (weight_dict[task].sigmoid() >= 0.5).float().numpy()
53:     mask_tensor = torch.tensor(mask_weight).unsqueeze(0).repeat(1, 1).to(model.device)
54:     choose_the, choose_from = task.split("_v_")[0], task.split("_v_")[1][:-2]
55:     instructed_attn, used_attn, unused_attn = [], [], []
56:     for sample in dataset:
57:         target_choice_idx = sample["input_str"].split(", ").index(sample["target_str"])
58:         input_inst_str = f"{sample['input_str']}\n\nChoose the {choose_the} out of {choose_from}s:"
59:         input_str = f"{sample['input_str']}"
60:         lm_inputs_inst_src = tokenizer([LLAMA_TEMPLATE.format(src=input_inst_str)], add_special_tokens=False, return_tensors="pt").to(DEVICE)
61:         lm_inputs_inst_src_choice_idx = find_segments_(lm_inputs_inst_src.input_ids[0].tolist())
62:         assert len(lm_inputs_inst_src_choice_idx) == 3
63:         lm_inputs_src = tokenizer([LLAMA_TEMPLATE.format(src=input_str)], add_special_tokens=False, return_tensors="pt").to(DEVICE)
64:         lm_inputs_src_choice_idx = lm_inputs_inst_src_choice_idx
65: 
66:         with torch.no_grad():
67:             original_output = model(**lm_inputs_inst_src, weight_tensor=None, output_attentions=True)
68:             original_attention = torch.stack(original_output.attentions)  # (n_layers, bsz, n_heads, seq_len, seq_len)
69:             last_token_attn = original_attention[:, -1, :, -1]
70:             original_token_attention = last_token_attn.mean(dim=(0,1)).float().cpu().numpy()
71:             original_choice_attentions = [original_token_attention[lm_inputs_inst_src_choice_idx[i]].sum() for i in range(3)]
72:             original_choice_attentions = np.array(original_choice_attentions) / sum(original_choice_attentions)
73:             instructed_attn.append(original_choice_attentions[target_choice_idx])
74: 
75:             weighted_output = model(**lm_inputs_src, weight_tensor=mask_tensor, output_attentions=True)
76:             weighted_attention = torch.stack(weighted_output.attentions)  # (n_layers, bsz, n_heads, seq_len, seq_len)
77:             last_token_attn = weighted_attention[:, -1, :, -1]
78:             last_token_attn[mask_tensor.view(32,33)[:, :-1] == 0] = 0
79:             layer_head_num = (mask_tensor.view(32,33)[:, :-1] != 0).sum(dim=1)
80:             weighted_token_attention = (last_token_attn.sum(dim=(0,1)) / (mask_tensor.sum() - 32)).float().cpu().numpy()
81:             weighted_choice_attentions = [weighted_token_attention[lm_inputs_src_choice_idx[i]].sum() for i in range(3)]
82:             weighted_choice_attentions = np.array(weighted_choice_attentions) / sum(weighted_choice_attentions)
83:             used_attn.append(weighted_choice_attentions[target_choice_idx])
84: 
85:             weighted_output = model(**lm_inputs_src, weight_tensor=mask_tensor, output_attentions=True)
86:             weighted_attention = torch.stack(weighted_output.attentions)  # (n_layers, bsz, n_heads, seq_len, seq_len)
87:             last_token_unused_attn = weighted_attention[:, -1, :, -1]
88:             last_token_unused_attn[mask_tensor.view(32,33)[:, :-1] == 1] = 0
89:             weighted_token_unused_attention = (last_token_unused_attn.sum(dim=(0,1)) / (1056 - mask_tensor.sum())).float().cpu().numpy()
90:             weighted_choice_unused_attentions = [weighted_token_unused_attention[lm_inputs_src_choice_idx[i]].sum() for i in range(3)]
91:             weighted_choice_unused_attentions = np.array(weighted_choice_unused_attentions) / sum(weighted_choice_unused_attentions)
92:             unused_attn.append(weighted_choice_unused_attentions[target_choice_idx])
93:     task_attentions[task] = {
94:         "Instructed" : np.mean(instructed_attn),
95:         "Used": np.mean(used_attn),
96:         "Ununsed": np.mean(unused_attn)
97:     }
98: df = pd.DataFrame.from_dict(task_attentions, orient="index")
99: display(df)

CELL 12
1: import datasets
2: import pandas as pd
3: import copy
4: import numpy as np
5: import itertools
6: from tqdm.notebook import tqdm
7: from IPython.display import display
8: 
9: LLAMA_TEMPLATE = "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n{src}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n"
10: LLAMA_PLM_TEMPLATE = "<|begin_of_text|>{src}\n\n"
11: QWEN2_TEMPLATE = "<|im_start|>user\n{src}<|im_end|>\n<|im_start|>assistant\n"
12: QWEN2_PLM_TEMPLATE = "{src}\n\n"
13: PHI3_TEMPLATE = "<|user|>\n{src}<|end|>\n<|assistant|>\n"
14: MISTRAL_TEMPLATE = "<s>[INST] {src}[/INST]"
15: 
16: LANG_LIST = ["en", "zh", "fr", "es", "de", "ru", "ar"]
17: LANG_DICT = {"ar": "Arabic", "fr": "French", "es": "Spanish", "de": "German", "en": "English", "ru": "Russian", "zh": "Chinese"}
18: dataset = datasets.Dataset.from_csv("./dataset/XNLI-15way/xnli.15way.orig.tsv", sep='\t').select_columns(LANG_LIST)
19: dataset = dataset.select(range(len(dataset) - 100, len(dataset)))
20: 
21: langs_original_ppl, langs_weighted_ppl = {}, {}
22: for src_lang, tgt_lang in tqdm(list(itertools.permutations(LANG_LIST, 2))):
23:     mask_weight = (weight_dict[f"{src_lang}_{tgt_lang}"].sigmoid() >= 0.5).float().numpy()
24:     # Uncomment the following lines to get a random mask:
25:     # mask = np.zeros_like(mask_weight, dtype=bool)
26:     # mask[np.arange(n_heads, (n_heads + 1) * n_layers, n_heads + 1)] = True
27:     # random_weight = mask_weight[~mask]
28:     # np.random.shuffle(random_weight)
29:     # mask_weight[~mask] = random_weight
30: 
31:     dev_dataset = dataset.map(
32:         lambda sample: {
33:             # Case w/ instruction: use this line
34:             "input_str": sample[src_lang] + f"\n\nTranslate into {LANG_DICT[tgt_lang]}:",
35:             # Case w/o instruction: use this line
36:             # "input_str": sample[src_lang],
37:             "target_str": sample[tgt_lang],
38:         }
39:     ).select_columns(["input_str", "target_str"])
40: 
41:     if src_lang not in langs_original_ppl:
42:         langs_original_ppl[src_lang] = {src_lang: 0}
43:     if src_lang not in langs_weighted_ppl:
44:         langs_weighted_ppl[src_lang] = {src_lang: 0}
45:     original_ppl, weighted_ppl = [], []
46:     for input_str, target_str in zip(*dev_dataset[:100].values()):
47:         # Change the template and EOT according to your model type
48:         combined_str = LLAMA_TEMPLATE.format(src=input_str.strip()) + f"{target_str.strip()}<|eot_id|>"
49:         lm_inputs = tokenizer(
50:             combined_str, 
51:             max_length=2048, 
52:             truncation=True, 
53:             padding=False, 
54:             add_special_tokens=False,
55:             return_tensors="pt"
56:         ).to(DEVICE)
57:         input_str_len = tokenizer(LLAMA_TEMPLATE.format(src=input_str.strip()), add_special_tokens=False, return_tensors="pt")["input_ids"].size(-1)
58:         labels = copy.deepcopy(lm_inputs["input_ids"]).to(DEVICE)
59:         labels[:, :input_str_len] = -100
60: 
61:         with torch.no_grad():
62:             # w/o mask
63:             original_output = model(**lm_inputs, labels=labels)
64:             original_ppl.append(original_output.loss.item())
65:             # w/ mask
66:             mask_tensor = torch.tensor(mask_weight).unsqueeze(0).repeat(1, 1).to(model.device)
67:             weighted_output = model(**lm_inputs, labels=labels, weight_tensor=mask_tensor)
68:             weighted_ppl.append(weighted_output.loss.item())
69:     langs_original_ppl[src_lang][tgt_lang] = np.nanmean(original_ppl)
70:     langs_weighted_ppl[src_lang][tgt_lang] = np.nanmean(weighted_ppl)
71: original_df = pd.DataFrame.from_dict(langs_original_ppl, orient="index")
72: print("w/o head mask:")
73: display(original_df)
74: weighted_df = pd.DataFrame.from_dict(langs_weighted_ppl, orient="index")
75: print("w/ head mask:")
76: display(weighted_df)

CELL 14
1: import datasets
2: import pandas as pd
3: import copy
4: import numpy as np
5: import itertools
6: from tqdm.notebook import tqdm
7: from rouge_score import rouge_scorer
8: 
9: LLAMA_TEMPLATE = "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n{src}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n"
10: LLAMA_PLM_TEMPLATE = "<|begin_of_text|>{src}\n\n"
11: QWEN2_TEMPLATE = "<|im_start|>user\n{src}<|im_end|>\n<|im_start|>assistant\n"
12: QWEN2_PLM_TEMPLATE = "{src}\n\n"
13: MISTRAL_TEMPLATE = "<s>[INST] {src}[/INST]"
14: PHI3_TEMPLATE = "<|user|>\n{src}<|end|>\n<|assistant|>\n"
15: LANG_LIST = ["en", "zh", "fr", "es", "de", "ru", "ar"]
16: LANG_DICT = {"ar": "Arabic", "fr": "French", "es": "Spanish", "de": "German", "en": "English", "ru": "Russian", "zh": "Chinese"}
17: dataset = datasets.Dataset.from_csv("./dataset/XNLI-15way/xnli.15way.orig.tsv", sep='\t').select_columns(LANG_LIST)
18: dataset = dataset.select(range(len(dataset) - 100, len(dataset)))
19: 
20: # You might use your own tokenizer here
21: sentence_tokenizer = AutoTokenizer.from_pretrained("~/PretrainedModels/bge-m3", use_fast=True)
22: rouge_scorer_instance = rouge_scorer.RougeScorer(["rougeL"], use_stemmer=True, tokenizer=sentence_tokenizer)
23: langs_original_rouge, langs_weighted_rouge = {}, {}
24: for src_lang, tgt_lang in tqdm(list(itertools.permutations(LANG_LIST, 2))[:12]):    # en- and zh-
25:     mask_weight = (weight_dict[f"{src_lang}_{tgt_lang}"].sigmoid() >= 0.5).float().numpy()
26: 
27:     dev_dataset = dataset.map(
28:         lambda sample: {
29:             # Case w/ instruction: use this line
30:             "input_str": sample[src_lang] + f"\n\nTranslate into {LANG_DICT[tgt_lang]}:",
31:             # Case w/o instruction: use this line
32:             # "input_str": sample[src_lang],
33:             "target_str": sample[tgt_lang],
34:         }
35:     ).select_columns(["input_str", "target_str"])
36: 
37:     if src_lang not in langs_original_rouge:
38:         langs_original_rouge[src_lang] = {src_lang: 0}
39:     if src_lang not in langs_weighted_rouge:
40:         langs_weighted_rouge[src_lang] = {src_lang: 0}
41:     original_rouge, weighted_rouge = [], []
42:     for input_str, target_str in zip(*dev_dataset[:100].values()):
43:         combined_str = LLAMA_TEMPLATE.format(src=input_str.strip())
44:         lm_inputs_src = tokenizer(
45:             combined_str, 
46:             max_length=2048, 
47:             truncation=True, 
48:             padding=False, 
49:             add_special_tokens=False,
50:             return_tensors="pt"
51:         ).to(DEVICE)
52: 
53:         with torch.no_grad():
54:             # w/o mask
55:             original_generate_ids = model.generate(**lm_inputs_src, max_new_tokens=50, weight_tensor=None, do_sample=False)
56:             original_pred_str = tokenizer.decode(original_generate_ids[0][lm_inputs_src.input_ids.size(1):], skip_special_tokens=True)
57:             original_rouge_scores = rouge_scorer_instance.score(original_pred_str, target_str)
58:             original_rouge_l = original_rouge_scores["rougeL"].fmeasure
59:             original_rouge.append(original_rouge_l)
60:             # w/ mask
61:             mask_tensor = torch.tensor(mask_weight).unsqueeze(0).repeat(1, 1).to(model.device)
62:             weighted_generate_ids = model.generate(**lm_inputs_src, max_new_tokens=50, weight_tensor=mask_tensor, do_sample=False)
63:             weighted_pred_str = tokenizer.decode(weighted_generate_ids[0][lm_inputs_src.input_ids.size(1):], skip_special_tokens=True)
64:             weighted_rouge_scores = rouge_scorer_instance.score(weighted_pred_str, target_str)
65:             weighted_rouge_l = weighted_rouge_scores["rougeL"].fmeasure
66:             weighted_rouge.append(weighted_rouge_l)
67: 
68:     langs_original_rouge[src_lang][tgt_lang] = np.nanmean(original_rouge)
69:     langs_weighted_rouge[src_lang][tgt_lang] = np.nanmean(weighted_rouge)
70: original_df = pd.DataFrame.from_dict(langs_original_rouge, orient="index")
71: display(original_df)
72: weighted_df = pd.DataFrame.from_dict(langs_weighted_rouge, orient="index")
73: display(weighted_df)

CELL 16
1: import datasets
2: import pandas as pd
3: import copy
4: import numpy as np
5: import itertools
6: from tqdm.notebook import tqdm
7: 
8: LLAMA_TEMPLATE = "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n{src}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n"
9: LLAMA_PLM_TEMPLATE = "<|begin_of_text|>{src}\n\n"
10: QWEN2_TEMPLATE = "<|im_start|>user\n{src}<|im_end|>\n<|im_start|>assistant\n"
11: QWEN2_PLM_TEMPLATE = "{src}\n\n"
12: MISTRAL_TEMPLATE = "<s>[INST] {src}[/INST]"
13: PHI3_TEMPLATE = "<|user|>\n{src}<|end|>\n<|assistant|>\n"
14: LANG_LIST = ["en", "zh", "fr", "es", "de", "ru", "ar"]
15: LANG_DICT = {"ar": "Arabic", "fr": "French", "es": "Spanish", "de": "German", "en": "English", "ru": "Russian", "zh": "Chinese"}
16: dataset = datasets.Dataset.from_csv("./dataset/XNLI-15way/xnli.15way.orig.tsv", sep='\t').select_columns(LANG_LIST)
17: dataset = dataset.select(range(len(dataset) - 100, len(dataset)))
18: 
19: langs_weighted_ppl = {}
20: lang_pairs = [("en", "zh"), ("zh", "en"), ("en", "fr"), ("fr", "en"), ("en", "de"), ("de", "en")]
21: for src_lang, tgt_lang in tqdm(lang_pairs):
22:     dev_dataset = dataset.map(
23:         lambda sample: {
24:             "input_str": sample[src_lang] + f"\n\nTranslate into {LANG_DICT[tgt_lang]}:",
25:             "target_str": sample[tgt_lang],
26:         }
27:     ).select_columns(["input_str", "target_str"])
28: 
29:     weighted_ppl = {v: [] for v in np.arange(0, 1.1, 0.1)}
30:     for input_str, target_str in tqdm(zip(*dev_dataset[:100].values()), total=100):
31:         combined_str = LLAMA_TEMPLATE.format(src=input_str.strip()) + f"{target_str.strip()}<|eot_id|>"
32:         lm_inputs = tokenizer(
33:             combined_str, 
34:             max_length=2048, 
35:             truncation=True, 
36:             padding=False, 
37:             add_special_tokens=False,
38:             return_tensors="pt"
39:         ).to(DEVICE)
40:         input_str_len = tokenizer(LLAMA_TEMPLATE.format(src=input_str.strip()), add_special_tokens=False, return_tensors="pt")["input_ids"].size(-1)
41:         labels = copy.deepcopy(lm_inputs["input_ids"]).to(DEVICE)
42:         labels[:, :input_str_len] = -100
43: 
44:         with torch.no_grad():
45:             for min_weight in np.arange(0, 1.1, 0.1):
46:                 mask_weight = (weight_dict[f"{src_lang}_{tgt_lang}"].sigmoid() >= 0.5).float().numpy().clip(min=min_weight)
47:                 mask_tensor = torch.tensor(mask_weight).unsqueeze(0).repeat(1, 1).to(model.device)
48:                 weighted_output = model(**lm_inputs, labels=labels, weight_tensor=mask_tensor)
49:                 weighted_ppl[min_weight].append(weighted_output.loss.item())
50:     weighted_ppl = {k: np.nanmean(weighted_ppl[k]) for k in weighted_ppl}
51:     langs_weighted_ppl[f"{src_lang}_{tgt_lang}"] = weighted_ppl
52: df = pd.DataFrame.from_dict(langs_weighted_ppl, orient="index")
53: display(df)

CELL 17
1: import numpy as np
2: import matplotlib.pyplot as plt
3: plt.rcParams['font.sans-serif'] = ["WenQuanYi Zen Hei"]
4: plt.rcParams['axes.unicode_minus'] = False
5: import seaborn as sns
6: colors = sns.color_palette(n_colors=6)
7: 
8: plt.figure(figsize=(6, 8))
9: plt.ylim(0.48, 1.1)
10: plt.xticks(np.arange(0, 1.1, 0.1), fontsize=12)
11: plt.xlabel(r"Scaling factor $\alpha$", fontsize=18)
12: plt.ylabel(r"PPL with respective $\mathcal{M}$", fontsize=18)
13: # plt.yticks(fontsize=12)
14: maskonly_ppl = {
15:     "en_fr": 0.551806, "en_de": 0.580341, "en_zh": 1.016755,
16:     "fr_en": 0.734948, "de_en": 0.638766, "zh_en": 0.997446
17: }
18: for i, (lang_pair, values) in enumerate(df.iterrows()):
19:     plt.plot(np.arange(0, 1.1, 0.1), values, linestyle='-', label=lang_pair, c=colors[i])
20:     plt.plot(0, maskonly_ppl[lang_pair], marker="x", c=colors[i])
21: plt.grid(alpha=0.3)
22: plt.legend(ncol=3, fontsize=12, loc="lower right")
23: plt.tight_layout()
24: plt.show()

CELL 19
1: import datasets
2: import pandas as pd
3: import copy
4: import jieba
5: import re
6: import numpy as np
7: import itertools
8: from tqdm.notebook import tqdm
9: from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction
10: 
11: LLAMA_TEMPLATE = "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n{src}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n"
12: LANG_DICT = {"fr": "French", "de": "German", "en": "English", "zh": "Chinese"}
13: LANGPAIR_MIN = {"en_de": 0.3, "en_fr": 0.2, "en_zh": 0.1, "zh_en": 0.3, "fr_en": 0.2, "de_en": 0.4}
14: 
15: langs_original_bleu, langs_weighted_bleu = {}, {}
16: smoothing = SmoothingFunction().method1
17: # from OpenCompass
18: def general_postprocess(text: str) -> str:
19:     # Remove instructions
20:     answer_text = text.split("\n\n")
21:     if len(answer_text) > 2:
22:         answer_text = answer_text[1:2]
23:     elif len(answer_text) > 1:
24:         answer_text = answer_text[1:]
25:     answer_text = "\n\n".join(answer_text)
26:     # Cut off the first newline, period, or comma
27:     # truncated_text = re.split(r'[\n.,]', answer_text, 1)[0]
28:     # Remove punctuation
29:     no_punctuation = re.sub(r'[^\w\s]', '', answer_text)
30:     # Remove article
31:     # no_articles = re.sub(r'\b(a|an|the)\b',
32:     #                      '',
33:     #                      no_punctuation,
34:     #                      flags=re.IGNORECASE)
35:     # Remove duplicated blank spaces
36:     cleaned_text = re.sub(r'\s+', ' ', no_punctuation).strip()
37:     cleaned_text = " ".join(jieba.cut(cleaned_text))
38: 
39:     return cleaned_text
40: 
41: def postprocess_and_score(text: str, target_str: str):
42:     # Remove instructions
43:     answer_text = text.split("\n\n")
44:     cleaned_texts = [" ".join(jieba.cut(re.sub(r'\s+', ' ', re.sub(r'[^\w\s]', '', t)).strip())) for t in answer_text]
45:     scores = [sentence_bleu([target_str], t, smoothing_function=smoothing) for t in cleaned_texts]
46:     return max(zip(cleaned_texts, scores), key=lambda x: x[1])
47: 
48: for src_lang, tgt_lang in [("en", "de"), ("en", "fr"), ("de", "en"), ("fr", "en"), ("en", "zh"), ("zh", "en")]:
49:     if tgt_lang != "en":
50:         dev_dataset = datasets.Dataset.from_parquet(f"./dataset/iwslt2017/{src_lang}-{tgt_lang}-test.parquet")
51:     else:
52:         dev_dataset = datasets.Dataset.from_parquet(f"./dataset/iwslt2017/{tgt_lang}-{src_lang}-test.parquet")
53:     dev_dataset = dev_dataset.map(
54:         lambda sample: {
55:             "input_str": f"{sample['translation'][src_lang]}\n\nTranslate into {tgt_lang}:",
56:             "target_str": sample['translation'][tgt_lang],
57:         }
58:     ).select_columns(["input_str", "target_str"])
59: 
60:     mask_weight = (weight_dict[f"{src_lang}_{tgt_lang}"].sigmoid() >= 0.5).float().numpy().clip(min=LANGPAIR_MIN[f"{src_lang}_{tgt_lang}"])
61:     original_bleu, weighted_bleu = [], []
62:     for sample in tqdm(dev_dataset):
63:         input_str, target_str = sample["input_str"], sample["target_str"]
64:         target_str = general_postprocess(target_str)
65:         combined_str = LLAMA_TEMPLATE.format(src=input_str.strip())
66:         lm_inputs_src = tokenizer(
67:             combined_str, 
68:             max_length=2048, 
69:             truncation=True, 
70:             padding=False, 
71:             add_special_tokens=False,
72:             return_tensors="pt"
73:         ).to(DEVICE)
74: 
75:         with torch.no_grad():
76:             # w/o mask
77:             original_generate_ids = model.generate(**lm_inputs_src, max_new_tokens=50, weight_tensor=None, do_sample=False)
78:             original_pred_str = tokenizer.decode(original_generate_ids[0][lm_inputs_src.input_ids.size(1):], skip_special_tokens=True)
79:             original_pred_str, original_bleu4 = postprocess_and_score(original_pred_str, target_str)
80:             original_bleu.append(original_bleu4)
81:             # w/ (scaled) mask
82:             mask_tensor = torch.tensor(mask_weight).unsqueeze(0).repeat(1, 1).to(model.device)
83:             weighted_generate_ids = model.generate(**lm_inputs_src, max_new_tokens=50, weight_tensor=mask_tensor, do_sample=False)
84:             weighted_pred_str = tokenizer.decode(weighted_generate_ids[0][lm_inputs_src.input_ids.size(1):], skip_special_tokens=True)
85:             weighted_pred_str, weighted_bleu4 = postprocess_and_score(weighted_pred_str, target_str)
86:             weighted_bleu.append(weighted_bleu4)
87:             pass
88: 
89:     langs_original_bleu[f"{src_lang}_{tgt_lang}"] = np.nanmean(original_bleu)
90:     langs_weighted_bleu[f"{src_lang}_{tgt_lang}"] = np.nanmean(weighted_bleu)
91:     print(f"{src_lang}_{tgt_lang}: {np.nanmean(original_bleu)} {np.nanmean(weighted_bleu)}")
92: original_df = pd.DataFrame.from_dict(langs_original_bleu, orient="index")
93: display(original_df)
94: weighted_df = pd.DataFrame.from_dict(langs_weighted_bleu, orient="index")
95: display(weighted_df)