benak / code /build.py
PugarHuda's picture
Benak release
27f6e9c verified
Raw History Blame Contribute Delete
8.02 kB
"""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")