Repository navigation
Expand file tree
/
Copy pathevaluate.py
More file actions
304 lines (271 loc) · 15.5 KB
/
Copy pathevaluate.py
File metadata and controls
304 lines (271 loc) · 15.5 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
"""Cross-lingual needle-in-a-haystack evaluation (decoupled from training).
Loops over (context_length, depth, language, needle_type) for one model (base or
base+adapter) and writes a JSON of per-condition F1 scores.
Examples
--------
# Smoke test: zh, 2x2 grid, factual needle, 5 examples
python evaluate.py --model_id meta-llama/Llama-3.1-8B \
--adapter_path models/llama3.1_finetuned \
--langs zh --needle_types factual --grid smoke --n_examples 5
# Phase A: fine grid, English, base model
python evaluate.py --model_id google/gemma-7b --langs en --grid fine
"""
import os
import json
import random
import argparse
import torch
from qa_utils import (
best_f1,
get_model_response,
load_model_and_tokenizer,
MODEL_CONTEXT_WINDOW,
)
from haystack import (
generate_haystack,
build_needle,
load_lang_split,
build_factual_item,
factual_distractor_pool,
SYNTHETIC_TYPES,
)
from translate import translate_text, translate_batch
# --------------------------------------------------------------------------- #
# Grids
# --------------------------------------------------------------------------- #
GRIDS = {
"smoke": {"lengths": [2000, 4000],
"depths": [0, 100]},
"coarse": {"lengths": [2000, 4000, 8000],
"depths": [0, 50, 100]}, # original 3x3
"fine": {"lengths": [1000, 2000, 4000, 8000, 16000, 32000],
"depths": [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]},
}
PROMPT_HEADROOM = 200 # tokens reserved for prompt template + question + generation
def eval_condition(model, tokenizer, length, depth, needle_text, question, answers,
distractor_pool, n_examples, rng, use_chat_template=False):
"""Average F1 over n_examples haystacks for a single (length, depth) cell."""
scores = []
for _ in range(n_examples):
haystack = generate_haystack(needle_text, distractor_pool, length, depth, tokenizer)
pred = get_model_response(
model, tokenizer, haystack, question, max_input_tokens=length + PROMPT_HEADROOM,
use_chat_template=use_chat_template,
)
scores.append(best_f1(pred, answers))
return sum(scores) / len(scores)
def cue_paragraph(haystack_ds, idx, answers):
"""A same-article paragraph (haystack language) that is not the needle and contains no answer.
XQuAD has 48 articles of 5 paragraphs each, stored in order (checked against the official
xquad.en.json: 238 of 240 paragraphs identical at the same position, article blocks of 5), so
the article of an item is the position of its paragraph among unique contexts, divided by 5.
The map is rebuilt per call because contexts differ by language."""
article = {c: k // 5 for k, c in enumerate(dict.fromkeys(haystack_ds["context"]))}
needle = haystack_ds[idx]["context"]
ans = [a.lower() for a in answers]
cands = [c for c, art in article.items() if art == article[needle] and c != needle
and not any(a in c.lower() for a in ans)]
# None when every other paragraph of the article contains the answer (only item 123, "Tesla");
# the run then falls back to the needle-absent haystack and the analysis excludes that item
return random.Random(f"cue-{idx}").choice(cands) if cands else None
def run(args):
rng = random.Random(42)
torch.manual_seed(42)
window = MODEL_CONTEXT_WINDOW.get(args.model_id, 8192)
lengths = [L for L in GRIDS[args.grid]["lengths"] if L + PROMPT_HEADROOM <= window]
depths = GRIDS[args.grid]["depths"]
model, tokenizer = load_model_and_tokenizer(args.model_id, args.adapter_path,
quantize=not args.no_quant)
tuned = args.adapter_path is not None
results = []
for lang in args.langs:
haystack_ds = load_lang_split(lang)
# 'same': ask in the haystack's own language (parallel XQuAD question)
question_ds = haystack_ds if args.question_lang == "same" else load_lang_split(args.question_lang)
# parallel splits are aligned by id/order; sanity-check
n = min(len(haystack_ds), len(question_ds), 200)
for needle_type in args.needle_types:
print(f"\n=== lang={lang} needle={needle_type} "
f"(q_lang={args.question_lang}, tuned={tuned}) ===")
if needle_type == "factual":
# one (needle, question) per example index; distractors shared
pool = factual_distractor_pool(haystack_ds)
prefix = args.instruction
extra_tokens = 0
if args.demo_idx is not None:
# one-shot demonstration in the haystack language, English question
d_ctx, d_q, d_ans = build_factual_item(haystack_ds, question_ds, args.demo_idx)
demo = f"Context: {d_ctx}\n\nQuestion: {d_q}\nAnswer: {d_ans[0]}"
prefix = f"{prefix}\n\n{demo}" if prefix else demo
if prefix:
extra_tokens = len(tokenizer(prefix, add_special_tokens=False)["input_ids"])
# translate_then_extract: pre-translate the entire distractor pool + needles
translated_pool = None
if args.pipeline == "translate_then_extract" and lang != "en":
print(f" [pipeline] translating distractor pool ({lang}->en)...")
translated_pool = translate_batch(pool, lang, "eng_Latn")
for length in lengths:
for depth in depths:
cell_scores = []
if args.seed_per_cell:
# global `random` drives distractor sampling in generate_haystack
random.seed(f"{lang}-{length}-{depth}")
idxs = random.Random(f"idx-{lang}-{length}-{depth}").sample(
range(n), min(args.n_examples, n))
else:
idxs = rng.sample(range(n), min(args.n_examples, n))
for idx in idxs:
needle_text, question, answers = build_factual_item(
haystack_ds, question_ds, idx
)
if args.cue_needle:
# topic-cue control: another paragraph from the needle's article that
# contains no answer string takes the needle's place
cue = cue_paragraph(haystack_ds, idx, answers) or ""
cell_pool = [c for c in pool if c != needle_text
and not any(a in c for a in answers)]
haystack = generate_haystack(cue, cell_pool, length, depth, tokenizer)
pred = get_model_response(
model, tokenizer, haystack, question,
max_input_tokens=length + PROMPT_HEADROOM + extra_tokens,
use_chat_template=args.chat, instruction=prefix,
)
f1_ex = best_f1(pred, answers)
elif args.needle_absent:
# drop the needle passage and any passage containing a gold answer
cell_pool = [c for c in pool if c != needle_text
and not any(a in c for a in answers)]
haystack = generate_haystack("", cell_pool, length, depth, tokenizer)
pred = get_model_response(
model, tokenizer, haystack, question,
max_input_tokens=length + PROMPT_HEADROOM + extra_tokens,
use_chat_template=args.chat, instruction=prefix,
)
f1_ex = best_f1(pred, answers)
elif args.pipeline == "translate_then_extract" and lang != "en":
t_needle = translate_text(needle_text, lang, "eng_Latn")
haystack = generate_haystack(
t_needle, translated_pool, length, depth, tokenizer
)
# answers are still in the haystack language; translate them too
t_answers = [translate_text(a, lang, "eng_Latn") for a in answers]
pred = get_model_response(
model, tokenizer, haystack, question,
max_input_tokens=length + PROMPT_HEADROOM,
use_chat_template=args.chat,
)
f1_ex = best_f1(pred, t_answers)
else:
haystack = generate_haystack(
needle_text, pool, length, depth, tokenizer
)
pred = get_model_response(
model, tokenizer, haystack, question,
max_input_tokens=length + PROMPT_HEADROOM + extra_tokens,
use_chat_template=args.chat, instruction=prefix,
)
if args.pipeline == "extract_then_translate" and lang != "en":
pred = translate_text(pred, lang, "eng_Latn")
t_answers = [translate_text(a, lang, "eng_Latn") for a in answers]
f1_ex = best_f1(pred, t_answers)
else:
f1_ex = best_f1(pred, answers)
cell_scores.append(f1_ex)
if args.save_preds:
results.append(_row(args, lang, needle_type, tuned,
length, depth, f1_ex,
pred=pred, answer=answers[0], idx=idx))
f1 = sum(cell_scores) / len(cell_scores)
if not args.save_preds:
results.append(_row(args, lang, needle_type, tuned, length, depth, f1))
print(f" L={length:>6} D={depth:>3}% F1={f1:5.1f}")
else: # synthetic needle type
pool = factual_distractor_pool(haystack_ds) # foreign-script noise
for length in lengths:
for depth in depths:
cell_scores = []
for _ in range(args.n_examples):
needle_text, question, ans = build_needle(
needle_type,
carrier_lang=lang,
question_lang=args.question_lang,
rng=rng,
)
haystack = generate_haystack(
needle_text, pool, length, depth, tokenizer
)
pred = get_model_response(
model, tokenizer, haystack, question,
max_input_tokens=length + PROMPT_HEADROOM,
use_chat_template=args.chat,
)
f1_ex = best_f1(pred, [ans])
cell_scores.append(f1_ex)
if args.save_preds:
results.append(_row(args, lang, needle_type, tuned,
length, depth, f1_ex,
pred=pred, answer=ans))
f1 = sum(cell_scores) / len(cell_scores)
if not args.save_preds:
results.append(_row(args, lang, needle_type, tuned, length, depth, f1))
print(f" L={length:>6} D={depth:>3}% F1={f1:5.1f}")
os.makedirs("metrics", exist_ok=True)
safe = args.model_id.split("/")[-1]
suffix = "tuned" if tuned else "base"
out = args.out or f"metrics/{safe}_{suffix}_xling.json"
with open(out, "w") as f:
json.dump({"model_id": args.model_id, "tuned": tuned,
"question_lang": args.question_lang, "grid": args.grid,
"seed_per_cell": args.seed_per_cell, "needle_absent": args.needle_absent,
"cue_needle": args.cue_needle,
"instruction": args.instruction, "demo_idx": args.demo_idx,
"no_quant": args.no_quant,
"results": results}, f, indent=2)
print(f"\nSaved {len(results)} rows -> {out}")
def _row(args, lang, needle_type, tuned, length, depth, f1, pred=None, answer=None, idx=None):
row = {
"model": args.model_id, "tuned": tuned,
"lang": lang, "question_lang": args.question_lang,
"needle_type": needle_type,
"Context Length": length, "Depth (%)": depth, "F1 Score": f1,
}
if pred is not None:
row["pred"] = pred
row["answer"] = answer
if idx is not None:
row["idx"] = idx
return row
def parse_args():
p = argparse.ArgumentParser()
p.add_argument("--model_id", required=True)
p.add_argument("--adapter_path", default=None)
p.add_argument("--langs", nargs="+", default=["en"])
p.add_argument("--question_lang", default="en",
help="Question language for factual needles; 'same' = the haystack language.")
p.add_argument("--needle_types", nargs="+", default=["factual"],
help=f"factual and/or any of {SYNTHETIC_TYPES}")
p.add_argument("--grid", choices=list(GRIDS), default="coarse")
p.add_argument("--n_examples", type=int, default=50)
p.add_argument("--out", default=None)
p.add_argument("--chat", action="store_true",
help="Use tokenizer.apply_chat_template instead of raw completion prompt.")
p.add_argument("--save_preds", action="store_true",
help="Save per-example predictions and gold answers (not just cell-avg F1).")
p.add_argument("--pipeline", default="standard",
choices=["standard", "extract_then_translate", "translate_then_extract"],
help="Translation pipeline for factual needles in non-English haystacks.")
p.add_argument("--seed_per_cell", action="store_true",
help="Seed example and distractor sampling per (lang, length, depth) cell.")
p.add_argument("--needle_absent", action="store_true",
help="Factual control: build haystacks without the needle passage.")
p.add_argument("--instruction", default=None,
help="Optional instruction line prepended to the prompt.")
p.add_argument("--no_quant", action="store_true", help="Load in bf16 instead of 4-bit NF4.")
p.add_argument("--cue_needle", action="store_true",
help="Topic-cue control: replace the needle with another same-article paragraph "
"that lacks the answer; drop the needle and answer-bearing paragraphs from distractors.")
p.add_argument("--demo_idx", type=int, default=None,
help="XQuAD index of a one-shot demonstration (haystack-language context and answer).")
return p.parse_args()
if __name__ == "__main__":
run(parse_args())