File size: 8,015 Bytes
7debf49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f3fd8a
 
 
 
 
d9aaa5c
 
7debf49
 
 
 
 
 
 
 
 
 
 
 
28f45ae
7debf49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27f6e9c
 
7debf49
 
 
 
 
 
 
 
9f3fd8a
7debf49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Assemble the release: HF dataset repo (release/dataset) + static Space (release/space).

Usage: python build.py            # build only

       python build.py --push     # build + upload (dataset PugarHuda/benak, space PugarHuda/benak)"""
import argparse, json, os, random, re, shutil
from lid import label, is_target

ap = argparse.ArgumentParser(); ap.add_argument("--push", action="store_true"); a = ap.parse_args()
D, S = "release/dataset", "release/space"
for p in (D, S):
    shutil.rmtree(p, ignore_errors=True)
os.makedirs(f"{D}/data", exist_ok=True); os.makedirs(S, exist_ok=True)
load = lambda p: [json.loads(l) for l in open(p, encoding="utf-8")] if os.path.exists(p) else []
NAMES = json.load(open("data/atlas/templates.json", encoding="utf-8"))

# 1) raw runs (every call, failures included) -------------------------------------------------------------
atlas = load("data/atlas/runs_low.jsonl") + load("data/atlas/runs_high.jsonl")
math_ = load("data/math/runs_low.jsonl") + load("data/math/runs_high.jsonl")
for name, rows in (("atlas_runs", atlas), ("math_runs", math_)):
    with open(f"{D}/data/{name}.jsonl", "w", encoding="utf-8") as f:
        f.writelines(json.dumps(r, ensure_ascii=False) + "\n" for r in rows)
shutil.copy("data/math/problems.json", f"{D}/data/math_problems.json")
shutil.copy("data/math/parallel.json", f"{D}/data/math_parallel.json")
shutil.copy("data/replication/profiled.jsonl", f"{D}/data/replication_profiled.jsonl")
shutil.copy("data/lid_calibration.json", f"{D}/data/lid_calibration.json")
shutil.copy("data/atlas/templates.json", f"{D}/data/prompt_templates.json")
for t in ("baseline", "after"):
    if os.path.exists(f"data/distill/eval_{t}.json"):
        shutil.copy(f"data/distill/eval_{t}.json", f"{D}/data/distill_eval_{t}.json")
if os.path.exists("data/distill/train_log.json"):
    shutil.copy("data/distill/train_log.json", f"{D}/data/distill_train_log.json")
if os.path.exists("data/routecheck/results.json"):
    shutil.copy("data/routecheck/results.json", f"{D}/data/route_check.json")
if os.path.exists("data/bugis/results.json"):  # model outputs + scores only; the CC BY-NC dictionary is NOT redistributed
    shutil.copy("data/bugis/results.json", f"{D}/data/grammar_book_bugis.json")
    shutil.copy("data/bugis/test.jsonl", f"{D}/data/grammar_book_bugis_test.jsonl")

# 2) sea_thinking: Multilingual-Thinking-format traces that are correct AND reasoned in the target language -----
probs = {p["id"]: p for p in json.load(open("data/math/problems.json", encoding="utf-8"))}
par = json.load(open("data/math/parallel.json", encoding="utf-8"))
rew = load("data/thinking/rewritten.jsonl")
think = []
_bel = {}
for r in math_ + atlas + rew:
    ts = (r.get("lid") or {}).get("target_share")
    if r.get("correct") and ts is not None and ts >= 0.8 and r.get("content") and r["lang"] != "eng_Latn":
        lang = r["lang"]
        if "link" in r:  # Belebele item: rebuild the exact prompt Beam saw (C0-C3 share the same user turn)
            from atlas import mc_prompt
            if lang not in _bel:
                from datasets import load_dataset
                _bel[lang] = {(x["link"], x["question_number"]): x for x in load_dataset("facebook/belebele", lang, split="test")}
            user = mc_prompt(_bel[lang][(r["link"], r["qnum"])], NAMES[lang])
        else:
            user = r.get("user") or (par[str(r["id"])][lang]["text"] if str(r.get("id")) in par else "")
        if not user:
            continue
        think.append({"reasoning_language": NAMES.get(lang, {}).get("lang_name_native", lang), "lang": lang,
                      "developer": "", "user": user, "analysis": r["reasoning"], "final": r["content"],
                      "messages": [{"role": "user", "content": user, "thinking": None},
                                   {"role": "assistant", "content": r["content"], "thinking": r["reasoning"]}],
                      "source": r.get("trace_source", "native"), "task": "math" if "answer" in r else "belebele",
                      "effort": r.get("effort"), "target_share": ts})
with open(f"{D}/data/sea_thinking.jsonl", "w", encoding="utf-8") as f:
    f.writelines(json.dumps(t, ensure_ascii=False) + "\n" for t in think)

# 3) results + space ------------------------------------------------------------------------------------------
R = json.load(open("data/results.json", encoding="utf-8"))
R["cost_usd"] = __import__("beam").spent()
R["sea_thinking_rows"] = len(think)
json.dump(R, open(f"{D}/results.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1)
json.dump(R, open(f"{S}/results.json", "w", encoding="utf-8"), ensure_ascii=False)


def segs(text, lang):
    out = []
    for piece in re.split(r"(?<=[.!?。])\s+|\n+", text or ""):
        p = piece.strip()
        if not p:
            continue
        letters = sum(c.isalpha() for c in p)
        if letters >= 12:
            lab = label(p)[0]
            kind = "tgt" if is_target(lab, lang) else "eng" if lab == "eng_Latn" else "oth"
        else:
            kind = "tgt"  # math / short fragments: neutral styling
        out.append([p, kind])
    return out


samples = {}
rng = random.Random(1)
for r in [x for x in atlas if x["effort"] == "low"]:
    samples.setdefault(r["lang"], {}).setdefault(r["cond"], []).append(r)
for l in samples:
    for c in samples[l]:
        pick = rng.sample(samples[l][c], min(4, len(samples[l][c])))
        samples[l][c] = [{"segs": segs(x["reasoning"], l), "correct": x["correct"],
                          "eng_share": x["lid"]["eng_share"], "target_share": x["lid"]["target_share"]} for x in pick]
json.dump(samples, open(f"{S}/samples.json", "w", encoding="utf-8"), ensure_ascii=False)
shutil.copy("space/index.html", f"{S}/index.html")
open(f"{S}/README.md", "w", encoding="utf-8").write(
    "---\ntitle: Benak\nemoji: 🧠\ncolorFrom: blue\ncolorTo: gray\nsdk: static\npinned: false\nlicense: cc-by-sa-4.0\n"
    "short_description: What language does Beam think in? 19 languages, 4 prompts\n"
    "datasets:\n- PugarHuda/benak\nmodels:\n- reflection/Beam-1.0-501B-A23B\n- PugarHuda/benak-qwen3-0.6b-lora\n- Qwen/Qwen3-0.6B\n---\n")

# 4) code + docs ----------------------------------------------------------------------------------------------
for f in ("beam.py", "lid.py", "atlas.py", "mathset.py", "grammar.py", "replication.py", "analyze.py", "build.py",
          "PREREGISTRATION.md"):
    shutil.copy(f, f"{D}/{f}")
os.makedirs(f"{D}/code", exist_ok=True)
for f in ("beam.py", "lid.py", "atlas.py", "mathset.py", "grammar.py", "replication.py", "analyze.py", "build.py"):
    shutil.move(f"{D}/{f}", f"{D}/code/{f}")
for f in ("benak_lang.py", "benak_reward.py", "thinking.py", "relid.py", "routecheck.py", "distill.py"):
    shutil.copy(f, f"{D}/code/{f}")
shutil.copy("data/atlas/templates.json", f"{D}/code/prompt_templates.json")  # benak_lang finds it next to itself
if os.path.exists("CARD.md"):  # live counts so the card never goes stale
    card = open("CARD.md", encoding="utf-8").read()
    card = card.replace("| `sea_thinking` | see file |", f"| `sea_thinking` | {len(think):,} |")
    card = card.replace("| `atlas_runs` | 3,040 |", f"| `atlas_runs` | {len(atlas):,} |").replace("| `math_runs` | 903 |", f"| `math_runs` | {len(math_):,} |")
    open(f"{D}/README.md", "w", encoding="utf-8").write(card)
print(f"atlas {len(atlas)} · math {len(math_)} · sea_thinking {len(think)} · cost ${R['cost_usd']}")

if a.push:
    from huggingface_hub import HfApi
    api = HfApi()
    api.upload_folder(folder_path=D, repo_id="PugarHuda/benak", repo_type="dataset", commit_message="Benak release")
    api.create_repo("PugarHuda/benak", repo_type="space", space_sdk="static", exist_ok=True, private=True)
    api.upload_folder(folder_path=S, repo_id="PugarHuda/benak", repo_type="space", commit_message="Benak space")
    print("pushed")