File size: 8,497 Bytes
96ac6f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Babak 1: reasoning-language atlas on Belebele (parallel reading comprehension, deterministic MC grading).

Conditions: C0 no language instruction | C1 'reason in X' in user turn | C2 same in system prompt |

            C3 C2 + one prior turn whose reasoning_content is written in X.

Usage: python atlas.py --n 40 --conds C0 C1 C2 C3 --effort low

       python atlas.py --n 40 --conds C0 C2 --effort high --langs eng_Latn ind_Latn jav_Latn sun_Latn tha_Thai yor_Latn"""
import argparse, json, os, random, re
from datasets import load_dataset
from beam import chat, run_many, spent
from lid import profile

LANGS = {  # code -> English name. SEA first, then languages covered by other entrants (for cross-linking)
    "eng_Latn": "English", "ind_Latn": "Indonesian", "jav_Latn": "Javanese", "sun_Latn": "Sundanese",
    "zsm_Latn": "Malay", "tgl_Latn": "Tagalog", "ceb_Latn": "Cebuano", "vie_Latn": "Vietnamese",
    "tha_Thai": "Thai", "khm_Khmr": "Khmer", "lao_Laoo": "Lao", "mya_Mymr": "Burmese",
    "hin_Deva": "Hindi", "tam_Taml": "Tamil", "kor_Hang": "Korean", "jpn_Jpan": "Japanese",
    "arb_Arab": "Arabic", "yor_Latn": "Yoruba", "plt_Latn": "Malagasy"}
OUT = "data/atlas"
EX_REASONING = ("The question asks which tip is NOT accurate. The passage says to keep the hand relaxed and to avoid "
                "extra finger motion, so options 2 and 3 are accurate tips. It says that on the accordion extra volume "
                "comes from using the bellows with more pressure or speed, so option 4 is also accurate. It explicitly "
                "says there is no need to hit the keys with a lot of force for extra volume, so option 1 is the "
                "inaccurate tip. The answer is 1.")
FIXED = {
    "eng_Latn": {"lang_name_native": "English", "question_label": "Question",
                 "answer_instruction": "Answer with the number of the correct option (1-4) inside \\boxed{}.",
                 "reason_instruction": "Think and reason step by step in English.",
                 "example_reasoning": EX_REASONING},
    "ind_Latn": {"lang_name_native": "bahasa Indonesia", "question_label": "Pertanyaan",
                 "answer_instruction": "Jawab dengan nomor pilihan yang benar (1-4) di dalam \\boxed{}.",
                 "reason_instruction": "Berpikir dan bernalarlah langkah demi langkah dalam bahasa Indonesia.",
                 "example_reasoning": (
                     "Pertanyaannya menanyakan tips mana yang TIDAK tepat. Bacaan mengatakan tangan harus tetap rileks "
                     "dan jari tidak banyak bergerak, jadi pilihan 2 dan 3 adalah tips yang tepat. Bacaan juga "
                     "mengatakan bahwa pada akordeon volume tambahan didapat dengan menekan atau menggerakkan bellow "
                     "lebih kuat atau lebih cepat, jadi pilihan 4 juga tepat. Bacaan dengan jelas mengatakan tidak "
                     "perlu menekan tuts dengan keras untuk menambah volume, jadi pilihan 1 adalah tips yang tidak "
                     "tepat. Jawabannya 1.")}}

TRANSLATE = """Translate the following UI strings and example text into {name} ({code}). Use natural, fluent {name} \

in its standard script. Keep "\\boxed{{}}" and the digits unchanged. Return ONLY JSON with exactly these keys:

{{"lang_name_native": "<the name of the {name} language, written in {name}>",

  "question_label": "<'Question'>",

  "answer_instruction": "<'Answer with the number of the correct option (1-4) inside \\boxed{{}}.'>",

  "reason_instruction": "<'Think and reason step by step in {name}.' (use the native language name)>",

  "example_reasoning": "<translation of the example text below>"}}



Example text:

{ex}"""


def items(n, seed=7):
    """Parallel Belebele items keyed by (link, question_number), present in every language. Returns (example, tests)."""
    per = {}
    for code in LANGS:
        ds = load_dataset("facebook/belebele", code, split="test")
        per[code] = {(r["link"], r["question_number"]): r for r in ds}
    common = set.intersection(*(set(d) for d in per.values()))
    eng0 = load_dataset("facebook/belebele", "eng_Latn", split="test")[0]
    ex_key = (eng0["link"], eng0["question_number"])
    assert ex_key in common
    keys = sorted(k for k in common if k != ex_key)
    random.Random(seed).shuffle(keys)
    return {c: per[c][ex_key] for c in LANGS}, [(k, {c: per[c][k] for c in LANGS}) for k in keys[:n]]


def templates():
    path = f"{OUT}/templates.json"
    t = json.load(open(path, encoding="utf-8")) if os.path.exists(path) else {}
    todo = [c for c in LANGS if c not in t]
    for c in todo:
        if c in FIXED:
            t[c] = FIXED[c] | {"source": "human"}
            continue
        r = chat([{"role": "user", "content": TRANSLATE.format(name=LANGS[c], code=c, ex=EX_REASONING)}],
                 "low", 4096, temperature=0.2)
        m = re.search(r"\{.*\}", r["content"], re.S)
        t[c] = json.loads(m.group(0)) | {"source": "beam-translated"}
        t[c]["lid_example"] = profile(t[c]["example_reasoning"], c)
    json.dump(t, open(path, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
    return t


def mc_prompt(row, tp):
    opts = "\n".join(f"{i}. {row[f'mc_answer{i}']}" for i in range(1, 5))
    return f"{row['flores_passage']}\n\n{tp['question_label']}: {row['question']}\n{opts}\n\n{tp['answer_instruction']}"


def messages(code, row, ex_row, tp, cond):
    user = mc_prompt(row, tp)
    if cond == "C0":
        return [{"role": "user", "content": user}]
    if cond == "C1":
        return [{"role": "user", "content": f"{user}\n\n{tp['reason_instruction']}"}]
    sys_msg = {"role": "system", "content": tp["reason_instruction"]}
    if cond == "C2":
        return [sys_msg, {"role": "user", "content": user}]
    ex = [{"role": "user", "content": mc_prompt(ex_row, tp)},
          {"role": "assistant", "content": "\\boxed{%s}" % ex_row["correct_answer_num"],
           "reasoning_content": tp["example_reasoning"]}]
    return [sys_msg, *ex, {"role": "user", "content": user}]  # C3


def parse_mc(text):
    m = re.findall(r"\\boxed\{\s*\(?([1-4])", text or "")
    if m:
        return int(m[-1])
    m = re.findall(r"\b([1-4])\b", text or "")
    return int(m[-1]) if m else None


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--n", type=int, default=40); ap.add_argument("--conds", nargs="+", default=["C0", "C1", "C2", "C3"])
    ap.add_argument("--effort", default="low"); ap.add_argument("--langs", nargs="+", default=list(LANGS))
    ap.add_argument("--workers", type=int, default=16)
    a = ap.parse_args()
    os.makedirs(OUT, exist_ok=True)
    tps = templates()
    ex, tests = items(a.n)
    budget = 4096 if a.effort == "low" else 32768  # 'budget trap' guard (Effort Atlas): reasoning eats max_tokens
    jobs = [(c, k, rows[c], cond) for k, rows in tests for c in a.langs for cond in a.conds]

    def run(job):
        c, k, row, cond = job
        r = chat(messages(c, row, ex[c], tps[c], cond), a.effort, budget, tag="atlas")
        pred = parse_mc(r["content"])
        return {"lang": c, "lang_name": LANGS[c], "link": k[0], "qnum": k[1], "cond": cond, "effort": a.effort,
                "gold": int(row["correct_answer_num"]), "pred": pred, "correct": pred == int(row["correct_answer_num"]),
                "finish_reason": r["finish_reason"], "usage": r["usage"], "reasoning": r["reasoning"],
                "content": r["content"], "lid": profile(r["reasoning"], c), "template_source": tps[c]["source"], "route": r.get("route"), "served_model": r.get("model"), "latency_s": r.get("latency_s")}

    out = f"{OUT}/runs_{a.effort}.jsonl"
    old = {}
    if os.path.exists(out):
        for l in open(out, encoding="utf-8"):
            d = json.loads(l); old[(d["lang"], d["link"], d["qnum"], d["cond"])] = d
    fails = 0
    for job, res in run_many(run, jobs, a.workers, f"atlas-{a.effort}"):
        if isinstance(res, Exception):
            fails += 1; print("FAIL", job[0], job[3], str(res)[:200], flush=True); continue
        old[(res["lang"], res["link"], res["qnum"], res["cond"])] = res
    with open(out, "w", encoding="utf-8") as f:
        f.writelines(json.dumps(d, ensure_ascii=False) + "\n" for d in old.values())
    print(f"wrote {len(old)} rows ({fails} failures) -> {out}; spent ${spent()}")


if __name__ == "__main__":
    main()