Repository navigation
Expand file tree
/
Copy pathplot_figures.py
More file actions
436 lines (382 loc) · 17.4 KB
/
Copy pathplot_figures.py
File metadata and controls
436 lines (382 loc) · 17.4 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
"""Publication figures for the cross-lingual NIAH study.
Produces four figures saved to figures/:
fig1_crosslingual.png — RQ2: avg factual F1 by model × language (all 8 langs)
fig2_needle_ablation.png — RQ3: needle-type × language, 3 representative model panels
fig3_fine_grid.png — RQ1: depth × length heatmaps, Llama base vs tuned (English)
fig4_sft_gain.png — RQ2 supplement: per-language SFT gain (base→tuned delta)
Usage: .venv/bin/python plot_figures.py
"""
import json
from pathlib import Path
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
import pandas as pd
import seaborn as sns
OUT = Path("figures")
OUT.mkdir(exist_ok=True)
LANG_ORDER = ["en", "de", "es", "ru", "ar", "zh", "hi", "th"]
LANG_LABELS = {"en": "EN", "de": "DE", "es": "ES", "ru": "RU",
"ar": "AR", "zh": "ZH", "hi": "HI", "th": "TH"}
NEEDLE_ORDER = ["factual", "named_entity", "temporal", "numeric", "code"]
NEEDLE_LABELS = {"factual": "Factual", "named_entity": "Named\nEntity",
"temporal": "Temporal", "numeric": "Numeric", "code": "Code"}
MODEL_ORDER = [
"Llama-3.1-8B base", "Llama-3.1-8B tuned",
"Mistral-7B-v0.1 base", "Mistral-7B-v0.1 tuned",
"gemma-7b base", "gemma-7b tuned",
"aya-expanse-8b", "Qwen2.5-32B-Instruct",
]
MODEL_COLORS = {
"Llama-3.1-8B base": "#aec6e8",
"Llama-3.1-8B tuned": "#1f77b4",
"Mistral-7B-v0.1 base": "#ffbb78",
"Mistral-7B-v0.1 tuned": "#ff7f0e",
"gemma-7b base": "#98df8a",
"gemma-7b tuned": "#2ca02c",
"aya-expanse-8b": "#9467bd",
"Qwen2.5-32B-Instruct": "#d62728",
}
def load_results(path):
with open(path) as f:
data = json.load(f)
return pd.DataFrame(data["results"])
def avg_by_lang(df, needle_type="factual"):
sub = df[df["needle_type"] == needle_type]
return sub.groupby("lang")["F1 Score"].mean()
# ---------------------------------------------------------------------------
# Load all Phase B (cross-lingual factual) data
# ---------------------------------------------------------------------------
phaseB = {
"Llama-3.1-8B base": load_results("metrics/Llama-3.1-8B_base_phaseB.json"),
"Llama-3.1-8B tuned": load_results("metrics/Llama-3.1-8B_tuned_phaseB.json"),
"Mistral-7B-v0.1 base": load_results("metrics/Mistral-7B-v0.1_base_phaseB.json"),
"Mistral-7B-v0.1 tuned": load_results("metrics/Mistral-7B-v0.1_tuned_phaseB.json"),
"gemma-7b base": load_results("metrics/gemma-7b_base_phaseB.json"),
"gemma-7b tuned": load_results("metrics/gemma-7b_tuned_phaseB.json"),
"aya-expanse-8b": load_results("metrics/aya-expanse-8b_base_phaseB_chat.json"),
"Qwen2.5-32B-Instruct": load_results("metrics/Qwen2.5-32B-Instruct_base_phaseB.json"),
}
phaseC = {
"Llama base": load_results("metrics/Llama-3.1-8B_base_phaseC.json"),
"Llama tuned": load_results("metrics/Llama-3.1-8B_tuned_phaseC.json"),
"aya (chat)": load_results("metrics/aya-expanse-8b_base_phaseC.json"),
"Qwen (chat)": load_results("metrics/Qwen2.5-32B-Instruct_base_phaseC.json"),
}
phaseA = {
"Llama base": load_results("metrics/Llama-3.1-8B_base_phaseA.json"),
"Llama tuned": load_results("metrics/Llama-3.1-8B_tuned_phaseA.json"),
}
# ---------------------------------------------------------------------------
# Figure 1: Cross-lingual factual F1 by model × language (RQ2)
# ---------------------------------------------------------------------------
def fig1_crosslingual():
langs = [l for l in LANG_ORDER if l != "th" or
any("th" in df["lang"].values for df in phaseB.values())]
n_langs = len(langs)
n_models = len(MODEL_ORDER)
x = np.arange(n_langs)
width = 0.85 / n_models
# figsize matches \textwidth display (~6.8in); dpi=220 so text renders at ~10pt
fig, ax = plt.subplots(figsize=(6.8, 3.6))
for i, model in enumerate(MODEL_ORDER):
df = phaseB[model]
scores = avg_by_lang(df, "factual")
vals = [scores.get(l, np.nan) for l in langs]
offset = (i - n_models / 2 + 0.5) * width
ax.bar(x + offset, vals, width=width * 0.9,
color=MODEL_COLORS[model], label=model, zorder=3)
ax.set_xticks(x)
ax.set_xticklabels([LANG_LABELS[l] for l in langs], fontsize=10)
ax.set_ylabel("Avg F1", fontsize=10)
ax.set_ylim(0, 108)
ax.set_title("RQ2: Cross-lingual factual retrieval — avg F1 by model and language",
fontsize=10)
ax.axvline(x=2.5, color="gray", linestyle="--", linewidth=0.8, zorder=2)
ax.axvline(x=3.5, color="gray", linestyle=":", linewidth=0.8, zorder=2)
ax.text(1.0, 104, "Latin-script IE", ha="center", fontsize=8.5, color="gray")
ax.text(3.0, 104, "Cyrillic", ha="center", fontsize=8.5, color="gray")
ax.text(5.5, 104, "Non-Latin script", ha="center", fontsize=8.5, color="gray")
ax.legend(loc="upper right", fontsize=8.5, ncol=2, framealpha=0.9)
ax.yaxis.grid(True, alpha=0.3, zorder=0)
ax.set_axisbelow(True)
ax.spines[["top", "right"]].set_visible(False)
ax.set_xlabel("Haystack language (English question)", fontsize=10)
plt.tight_layout()
path = OUT / "fig1_crosslingual.png"
plt.savefig(path, dpi=220, bbox_inches="tight")
plt.close(fig)
print(f"Saved {path}")
# ---------------------------------------------------------------------------
# Figure 2: Needle-type ablation (RQ3) — 4 panels
# ---------------------------------------------------------------------------
def fig2_needle_ablation():
panels = [
("Llama base", "Llama-3.1-8B\n(base, raw)"),
("Llama tuned", "Llama-3.1-8B\n(tuned, raw)"),
("aya (chat)", "aya-expanse-8b\n(base, chat)"),
("Qwen (chat)", "Qwen2.5-32B\n(base, chat)"),
]
lang_sub = ["en", "zh", "ar", "de"]
n_needles = len(NEEDLE_ORDER)
n_langs = len(lang_sub)
x = np.arange(n_needles)
width = 0.18
lang_colors = {"en": "#4c72b0", "de": "#55a868", "ar": "#c44e52", "zh": "#dd8452"}
fig, axes = plt.subplots(1, len(panels), figsize=(6.8, 3.4), sharey=True)
for ax, (key, title) in zip(axes, panels):
df = phaseC[key]
for j, lang in enumerate(lang_sub):
sub = df[df["lang"] == lang]
scores = sub.groupby("needle_type")["F1 Score"].mean()
vals = [scores.get(nt, np.nan) for nt in NEEDLE_ORDER]
offset = (j - n_langs / 2 + 0.5) * width
ax.bar(x + offset, vals, width=width * 0.9,
color=lang_colors[lang], label=lang.upper(), zorder=3)
ax.set_xticks(x)
ax.set_xticklabels([NEEDLE_LABELS[nt] for nt in NEEDLE_ORDER], fontsize=8.5)
ax.set_title(title, fontsize=9)
ax.set_ylim(0, 110)
ax.yaxis.grid(True, alpha=0.3, zorder=0)
ax.set_axisbelow(True)
ax.spines[["top", "right"]].set_visible(False)
ax.axvline(x=0.5, color="red", linestyle="--", linewidth=1, alpha=0.5)
if ax == axes[0]:
ax.set_ylabel("Avg F1", fontsize=9)
axes[0].legend(title="Haystack lang", fontsize=8, title_fontsize=8, loc="lower right")
fig.suptitle(
"RQ3: Needle-type ablation — factual needles are in the target language; "
"all others are English",
fontsize=9.5, y=1.01,
)
plt.tight_layout()
path = OUT / "fig2_needle_ablation.png"
plt.savefig(path, dpi=220, bbox_inches="tight")
plt.close(fig)
print(f"Saved {path}")
# ---------------------------------------------------------------------------
# Figure 3: Fine-grid heatmaps — Llama base vs tuned, English (RQ1)
# ---------------------------------------------------------------------------
def _heatmap(ax, df, title, cbar=False):
pivot = df.pivot_table(index="Depth (%)", columns="Context Length",
values="F1 Score", aggfunc="mean")
pivot = pivot.sort_index(ascending=False)
sns.heatmap(pivot, annot=True, fmt=".0f", cmap="RdYlGn",
vmin=0, vmax=100, ax=ax, cbar=cbar,
annot_kws={"size": 8.5}, linewidths=0.3)
ax.set_title(title, fontsize=9.5)
ax.set_xlabel("Context length (tokens)", fontsize=9)
ax.set_ylabel("Needle depth (%)", fontsize=9)
ax.tick_params(labelsize=8.5)
def fig3_fine_grid():
fig, axes = plt.subplots(1, 2, figsize=(6.8, 4.2))
_heatmap(axes[0], phaseA["Llama base"], "Llama-3.1-8B base (English, fine grid)")
_heatmap(axes[1], phaseA["Llama tuned"], "Llama-3.1-8B tuned (English, fine grid)", cbar=True)
fig.suptitle("RQ1: Retrieval F1 across context length × needle depth (English SQuAD)",
fontsize=10)
plt.tight_layout()
path = OUT / "fig3_fine_grid.png"
plt.savefig(path, dpi=220, bbox_inches="tight")
plt.close(fig)
print(f"Saved {path}")
# ---------------------------------------------------------------------------
# Figure 4: SFT gain per language (RQ2 supplement)
# ---------------------------------------------------------------------------
def fig4_sft_gain():
pairs = [
("Llama-3.1-8B", "Llama-3.1-8B base", "Llama-3.1-8B tuned", "#1f77b4"),
("Mistral-7B-v0.1", "Mistral-7B-v0.1 base", "Mistral-7B-v0.1 tuned","#ff7f0e"),
("gemma-7b", "gemma-7b base", "gemma-7b tuned", "#2ca02c"),
]
langs = [l for l in LANG_ORDER]
x = np.arange(len(langs))
width = 0.25
fig, ax = plt.subplots(figsize=(6.8, 3.2))
for i, (label, base_key, tuned_key, color) in enumerate(pairs):
base_scores = avg_by_lang(phaseB[base_key], "factual")
tuned_scores = avg_by_lang(phaseB[tuned_key], "factual")
gains = [tuned_scores.get(l, 0) - base_scores.get(l, 0) for l in langs]
offset = (i - 1) * width
ax.bar(x + offset, gains, width=width * 0.9, color=color, label=label, zorder=3)
ax.set_xticks(x)
ax.set_xticklabels([LANG_LABELS[l] for l in langs], fontsize=10)
ax.set_ylabel("ΔF1 (tuned − base)", fontsize=10)
ax.set_title("RQ2 supplement: SFT gain (English SQuAD LoRA) per language", fontsize=10)
ax.axhline(0, color="black", linewidth=0.8)
ax.axvline(x=2.5, color="gray", linestyle="--", linewidth=0.8)
ax.axvline(x=3.5, color="gray", linestyle=":", linewidth=0.8)
ax.legend(fontsize=9)
ax.yaxis.grid(True, alpha=0.3, zorder=0)
ax.set_axisbelow(True)
ax.spines[["top", "right"]].set_visible(False)
ax.set_xlabel("Haystack language", fontsize=10)
plt.tight_layout()
path = OUT / "fig4_sft_gain.png"
plt.savefig(path, dpi=220, bbox_inches="tight")
plt.close(fig)
print(f"Saved {path}")
# ---------------------------------------------------------------------------
# Figure 5: Translation pipeline comparison (RQ5)
# ---------------------------------------------------------------------------
def fig5_pipelines():
# Blue family = extract-then-translate, orange family = translate-then-extract
# Light = base, dark = tuned
CONDITIONS = [
("Base + extract-then-translate", 26.3, 18.6, "#aec6e8"),
("Tuned + extract-then-translate", 39.8, 40.1, "#1f77b4"),
("Base + translate-then-extract", 16.3, 11.9, "#ffbb78"),
("Tuned + translate-then-extract", 25.8, 22.5, "#ff7f0e"),
]
langs = ["Arabic (ar)", "Chinese (zh)"]
x = np.arange(len(langs))
n = len(CONDITIONS)
width = 0.18
fig, ax = plt.subplots(figsize=(7, 4))
for i, (label, ar_val, zh_val, color) in enumerate(CONDITIONS):
vals = [ar_val, zh_val]
offset = (i - n / 2 + 0.5) * width
bars = ax.bar(x + offset, vals, width=width * 0.9, color=color,
label=label, zorder=3)
for bar, v in zip(bars, vals):
ax.text(bar.get_x() + bar.get_width() / 2, v + 0.8,
f"{v:.0f}", ha="center", va="bottom", fontsize=7)
ax.set_xticks(x)
ax.set_xticklabels(langs, fontsize=11)
ax.set_ylabel("Avg F1 (coarse grid)", fontsize=10)
ax.set_ylim(0, 55)
ax.set_title("RQ5: Translation pipeline comparison\n(Llama-3.1-8B, factual needle)",
fontsize=10)
ax.legend(fontsize=7.5, loc="upper right")
ax.grid(axis="y", alpha=0.3, zorder=0)
plt.tight_layout()
path = OUT / "fig5_pipelines.png"
plt.savefig(path, dpi=150, bbox_inches="tight")
plt.close(fig)
print(f"Saved {path}")
# ---------------------------------------------------------------------------
# Figure 6: Cross-lingual SFT mitigation comparison (RQ6)
# ---------------------------------------------------------------------------
def fig6_xling_sft():
CONDITIONS = [
("English SFT", 18.6, 33.5, "#aec6e8"),
("xling SFT", 41.8, 57.6, "#1f77b4"),
("xling SFT + e2t", 50.3, 59.6, "#2ca02c"),
("Wrong-language SFT", 42.5, 44.3, "#ff7f0e"),
]
AYA = {"ar": 54.6, "zh": 59.2}
langs = ["Arabic (ar)", "Chinese (zh)"]
aya_vals = [AYA["ar"], AYA["zh"]]
x = np.arange(len(langs))
n = len(CONDITIONS)
width = 0.18
fig, ax = plt.subplots(figsize=(7, 4))
for i, (label, ar_val, zh_val, color) in enumerate(CONDITIONS):
vals = [ar_val, zh_val]
offset = (i - n / 2 + 0.5) * width
bars = ax.bar(x + offset, vals, width=width * 0.9, color=color,
label=label, zorder=3)
for bar, v in zip(bars, vals):
ax.text(bar.get_x() + bar.get_width() / 2, v + 0.8,
f"{v:.0f}", ha="center", va="bottom", fontsize=7)
# aya reference as dashed horizontal segments per language
seg_half = 0.38
for xi, av in zip(x, aya_vals):
ax.plot([xi - seg_half, xi + seg_half], [av, av],
color="#9467bd", linewidth=2, linestyle="--", zorder=4)
ax.plot([], [], color="#9467bd", linewidth=2, linestyle="--",
label="aya-expanse-8B (ref)")
ax.set_xticks(x)
ax.set_xticklabels(langs, fontsize=11)
ax.set_ylabel("Avg F1 (coarse grid)", fontsize=10)
ax.set_ylim(0, 72)
ax.set_title("RQ6: Cross-lingual SFT — mitigation comparison\n(Llama-3.1-8B, factual needle)",
fontsize=10)
ax.legend(fontsize=7.5, loc="upper left")
ax.grid(axis="y", alpha=0.3, zorder=0)
plt.tight_layout()
path = OUT / "fig6_xling_sft.png"
plt.savefig(path, dpi=150, bbox_inches="tight")
plt.close(fig)
print(f"Saved {path}")
def fig7_transfer_matrix():
"""RQ6 Phase H: script-general transfer matrix across all 4 non-Latin-script languages.
Validated categorical palette (#eda100, #2a78d6, #1baf7a) — all 6 checks pass
in light mode; contrast WARN on amber/teal mitigated by direct value labels.
Matched (in-language) bars carry a thick border to add secondary encoding.
"""
# --- data ---
langs = ["Arabic", "Chinese", "Hindi", "Thai"]
adapters = ["English SFT", "ar-SFT", "zh-SFT"]
scores = {
"English SFT": [18.6, 33.5, 27.6, 28.1],
"ar-SFT": [41.8, 44.3, 42.4, 41.4],
"zh-SFT": [42.5, 57.6, 40.9, 55.5],
}
# which (adapter_idx, lang_idx) is the matched (in-language) cell
matched = {(1, 0), (2, 1)} # ar-SFT→ar, zh-SFT→zh
colors = {"English SFT": "#eda100", "ar-SFT": "#2a78d6", "zh-SFT": "#1baf7a"}
n_langs = len(langs)
n_adapters = len(adapters)
x = np.arange(n_langs)
total_w = 0.72
bar_w = total_w / n_adapters
offsets = np.linspace(-(total_w - bar_w) / 2, (total_w - bar_w) / 2, n_adapters)
fig, ax = plt.subplots(figsize=(6.5, 3.4))
for ai, adapter in enumerate(adapters):
for li in range(n_langs):
is_matched = (ai, li) in matched
val = scores[adapter][li]
ax.bar(
x[li] + offsets[ai], val,
width=bar_w - 0.03,
color=colors[adapter],
edgecolor="black" if is_matched else "none",
linewidth=1.8 if is_matched else 0,
label=adapter if li == 0 else None,
zorder=3,
)
# direct value label (required: mitigates contrast WARN)
ax.text(
x[li] + offsets[ai], val + 0.8,
f"{val:.1f}",
ha="center", va="bottom", fontsize=6.5, color="#333333",
)
ax.set_xticks(x)
ax.set_xticklabels(
["Arabic\n(Abjad)", "Chinese\n(Logographic)", "Hindi\n(Devanagari)", "Thai\n(Abugida)"],
fontsize=8,
)
ax.set_ylabel("Avg F1 (factual, coarse grid)", fontsize=8)
ax.set_ylim(0, 68)
ax.set_xlim(-0.55, n_langs - 0.45)
ax.yaxis.grid(True, color="#e0e0e0", linewidth=0.6, zorder=0)
ax.set_axisbelow(True)
ax.spines[["top", "right"]].set_visible(False)
ax.tick_params(axis="both", labelsize=8)
# legend + matched-cell note
handles, labels = ax.get_legend_handles_labels()
matched_patch = mpatches.Patch(
facecolor="white", edgecolor="black", linewidth=1.8,
label="bold border = in-language (matched)"
)
handles.append(matched_patch)
ax.legend(handles=handles, fontsize=7.5, frameon=False,
loc="upper left", ncol=2)
ax.set_title(
"Script-general transfer: adapters trained on Arabic or Chinese\nimprove unseen scripts (Hindi, Thai)",
fontsize=8.5, pad=6,
)
fig.tight_layout()
path = OUT / "fig7_transfer_matrix.png"
fig.savefig(path, dpi=200, bbox_inches="tight")
plt.close(fig)
print(f"Saved {path}")
if __name__ == "__main__":
fig1_crosslingual()
fig2_needle_ablation()
fig3_fine_grid()
fig4_sft_gain()
fig5_pipelines()
fig6_xling_sft()
fig7_transfer_matrix()
print("\nAll figures written to figures/")