benak / code /grammar.py
PugarHuda's picture
Benak release
96ac6f7 verified
Raw History Blame Contribute Delete
4.98 kB
"""Babak 2: can Beam learn a local Indonesian language from a book in its 1M-token context? (MTOB-style)
Context conditions (growing): K0 nothing | K1 dictionary | K2 grammar | K3 grammar + dictionary + parallel examples.
Tasks: translate 100 test sentences both ways (50 per call, chrF++), plus a 'think in <lang>' probe that measures
whether reading the book lets Beam reason in that language (GlotLID share).
Usage: python grammar.py --lang bug_Latn --name Bugis"""
import argparse, json, os, re
import sacrebleu
from beam import chat, run_many, spent
from lid import profile
D = "data/bugis"
CTX_ORDER = {"K0": [], "K1": ["dictionary.txt"], "K2": ["grammar.txt"],
"K3": ["grammar.txt", "dictionary.txt", "monolingual.txt", "PARALLEL"]}
BATCH = 50 # ponytail: big batches = the huge book context is paid fewer times
def read(name):
p = os.path.join(D, name)
return open(p, encoding="utf-8").read() if os.path.exists(p) else ""
def context(cond, lang_name):
parts = []
for f in CTX_ORDER[cond]:
if f == "PARALLEL":
ex = [json.loads(l) for l in open(os.path.join(D, "parallel_train.jsonl"), encoding="utf-8")]
parts.append("## Contoh kalimat paralel\n" + "\n".join(f"{lang_name}: {e['bug']}\nIndonesia: {e['ind']}" for e in ex))
elif read(f):
parts.append(f"## {f}\n{read(f)}")
if not parts:
return ""
return (f"Berikut bahan referensi tentang bahasa {lang_name}. Bacalah dan gunakan untuk tugas di bawahnya. "
"Catatan ejaan: kamus menulis hamzah akhir sebagai 'k' (bembek), sedangkan kalimat uji memakai "
"apostrof (bembe').\n\n" + "\n\n".join(parts) + "\n\n---\n\n")
def ask(cond, direction, batch, lang_name, think=False):
src, tgt = (lang_name, "Indonesia") if direction == "x2ind" else ("Indonesia", lang_name)
key = "bug" if direction == "x2ind" else "ind"
lines = "\n".join(f"{i + 1}. {s[key]}" for i, s in enumerate(batch))
instr = (f"Terjemahkan setiap kalimat berbahasa {src} berikut ke bahasa {tgt}. Jawab HANYA dengan daftar bernomor "
f"yang sama (1., 2., ...), satu terjemahan per baris.")
if think:
instr += f" Berpikir dan bernalarlah dalam bahasa {lang_name}."
msgs = [{"role": "user", "content": context(cond, lang_name) + instr + "\n\n" + lines}]
return chat(msgs, "low", 16384, temperature=0.2, tag="grammar")
def parse(content, n):
out = [""] * n
for m in re.finditer(r"^\s*(\d+)[.)]\s*(.+)$", content, re.M):
i = int(m.group(1)) - 1
if 0 <= i < n and not out[i]:
out[i] = m.group(2).strip()
return out
def main():
ap = argparse.ArgumentParser(); ap.add_argument("--lang", default="bug_Latn"); ap.add_argument("--name", default="Bugis")
ap.add_argument("--conds", nargs="+", default=list(CTX_ORDER)); ap.add_argument("--n", type=int, default=100)
a = ap.parse_args()
test = [json.loads(l) for l in open(os.path.join(D, "test.jsonl"), encoding="utf-8")][:a.n]
batches = [test[i:i + BATCH] for i in range(0, len(test), BATCH)]
jobs = [(c, d, bi, False) for c in a.conds for d in ("x2ind", "ind2x") for bi in range(len(batches))]
jobs += [(c, "x2ind", 0, True) for c in a.conds] # think-in-language probe, one batch per condition
def one(job):
c, d, bi, think = job
r = ask(c, d, batches[bi], a.name, think)
return {"cond": c, "direction": d, "batch": bi, "think": think, "hyp": parse(r["content"], len(batches[bi])),
"usage": r["usage"], "finish_reason": r["finish_reason"], "reasoning": r["reasoning"],
"lid_reasoning": profile(r["reasoning"], a.lang)}
rows = [r for _, r in run_many(one, jobs, 4, "grammar") if not isinstance(r, Exception)]
res = {}
for c in a.conds:
for d in ("x2ind", "ind2x"):
hyp, ref = [], []
for r in sorted((r for r in rows if r["cond"] == c and r["direction"] == d and not r["think"]),
key=lambda r: r["batch"]):
hyp += r["hyp"]; ref += [s["ind"] if d == "x2ind" else s["bug"] for s in batches[r["batch"]]]
if hyp:
res[f"{c}/{d}"] = {"chrf++": round(sacrebleu.corpus_chrf(hyp, [ref], word_order=2).score, 2),
"n": len(hyp), "empty": sum(not h for h in hyp)}
th = [r for r in rows if r["cond"] == c and r["think"]]
if th:
res[f"{c}/think"] = th[0]["lid_reasoning"]
res[f"{c}/prompt_tokens"] = max((r["usage"].get("prompt_tokens", 0) for r in rows if r["cond"] == c), default=0)
json.dump({"results": res, "rows": rows}, open(os.path.join(D, "results.json"), "w", encoding="utf-8"),
ensure_ascii=False, indent=1)
print(json.dumps(res, indent=1)); print("spent $", spent())
if __name__ == "__main__":
main()