Repository navigation
Expand file tree
/
Copy pathhaystack.py
More file actions
133 lines (114 loc) · 5.33 KB
/
Copy pathhaystack.py
File metadata and controls
133 lines (114 loc) · 5.33 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
"""Haystack construction for the cross-lingual needle-in-a-haystack experiment.
Provides:
- generate_haystack: token-budget needle insertion (moved verbatim from run_model.py)
- NEEDLE_TEMPLATES + build_needle: synthetic needle types for the RQ3 ablation
- build_factual_item / build_synthetic_item: assemble a (needle, question, answer,
distractor_pool) tuple from parallel XQuAD splits for a given condition.
Condition tuple = (haystack_lang, question_lang, needle_type).
"""
import random
from datasets import load_from_disk
# --------------------------------------------------------------------------- #
# Token-budget needle insertion (verbatim from run_model.py)
# --------------------------------------------------------------------------- #
def generate_haystack(correct_context, distractors, total_tokens, depth_percent, tokenizer):
needle_ids = tokenizer(correct_context, add_special_tokens=False)["input_ids"]
noise_budget = total_tokens - len(needle_ids)
if noise_budget < 0:
noise_budget = 0
current_noise_ids = []
while len(current_noise_ids) < noise_budget:
d = random.choice(distractors)
d_ids = tokenizer(d, add_special_tokens=False)["input_ids"]
current_noise_ids.extend(d_ids)
current_noise_ids = current_noise_ids[:noise_budget]
insert_idx = int(len(current_noise_ids) * (depth_percent / 100))
final_ids = current_noise_ids[:insert_idx] + needle_ids + current_noise_ids[insert_idx:]
return tokenizer.decode(final_ids)
# --------------------------------------------------------------------------- #
# Synthetic needle templates (RQ3)
#
# Each template yields a (needle_text, question, answer) triple. The payload of
# `numeric`/`temporal`/`code` is *script-invariant* (digits / ASCII); `named_entity`
# carries a script-dependent name. `factual` is handled separately (uses native XQuAD).
#
# Carriers are authored per language; `en` is the controlled default. For a haystack
# language without a native carrier we fall back to the English carrier (a documented
# code-switched island) — resolved properly in Phase C. The script-invariant payload is
# unchanged regardless of carrier language, which is the point of the ablation.
# --------------------------------------------------------------------------- #
NEEDLE_TEMPLATES = {
"numeric": {
"answer": lambda r: "-".join(str(r.randint(0, 9)) for _ in range(4)),
"carrier": {
"en": "The secret access code is {ans}.",
},
"question": {
"en": "What is the secret access code?",
},
},
"temporal": {
"answer": lambda r: r.choice(
["March 14, 2026", "July 2, 2027", "November 30, 2025",
"January 9, 2028", "August 21, 2026"]
),
"carrier": {
"en": "The committee meeting is scheduled for {ans}.",
},
"question": {
"en": "On what date is the committee meeting scheduled?",
},
},
"named_entity": {
"answer": lambda r: r.choice(
["Aravind Krishnamurthy", "Beatriz Solano", "Wei Zhang",
"Fatima Al-Rashid", "Niamh O'Sullivan"]
),
"carrier": {
"en": "The courier who delivered the package was named {ans}.",
},
"question": {
"en": "What was the name of the courier who delivered the package?",
},
},
"code": {
"answer": lambda r: str(r.randint(1000, 9999)),
"carrier": {
"en": "def get_secret_key():\n return {ans}",
},
"question": {
"en": "What integer does the function get_secret_key return?",
},
},
}
SYNTHETIC_TYPES = tuple(NEEDLE_TEMPLATES.keys())
def build_needle(needle_type, carrier_lang="en", question_lang="en", rng=None):
"""Construct a synthetic (needle_text, question, answer) triple.
carrier_lang: language of the sentence wrapping the payload (falls back to 'en').
question_lang: language of the probe question (falls back to 'en').
"""
rng = rng or random
spec = NEEDLE_TEMPLATES[needle_type]
ans = spec["answer"](rng)
carrier = spec["carrier"].get(carrier_lang, spec["carrier"]["en"])
question = spec["question"].get(question_lang, spec["question"]["en"])
return carrier.format(ans=ans), question, ans
# --------------------------------------------------------------------------- #
# Item assembly from parallel XQuAD / SQuAD
# --------------------------------------------------------------------------- #
def load_lang_split(lang, base="data/xquad"):
"""Load one XQuAD language split (validation). Returns a datasets.Dataset."""
return load_from_disk(f"{base}/{lang}")
def build_factual_item(haystack_ds, question_ds, idx):
"""Factual needle: native XQuAD context as needle, question in question_lang.
haystack_ds and question_ds are parallel splits (same ids/order). The needle is the
haystack-language context (which contains the answer in-script); the answer set is the
haystack-language answers; the question comes from question_ds.
Returns (needle_text, question, answers_list).
"""
h = haystack_ds[idx]
q = question_ds[idx]
return h["context"], q["question"], h["answers"]["text"]
def factual_distractor_pool(haystack_ds):
"""All contexts in the haystack language, used as distractor noise."""
return haystack_ds["context"]