File size: 13,943 Bytes
9f3fd8a c16a957 9f3fd8a cc4f445 9f3fd8a cc4f445 9f3fd8a cc4f445 9f3fd8a c16a957 9f3fd8a | 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 | """Proof that sea_thinking fixes the problem: LoRA-SFT a small thinking model (Qwen3-0.6B) on Beam's in-language
traces, then measure the language of its <think> block and its accuracy on HELD-OUT math problems (never seen in
training, in any language), before vs after. Runs on a 6 GB consumer GPU.
Usage: python distill.py baseline | train | after (results -> data/distill/)"""
import json, math, os, random, re, sys, time
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
BASE = "Qwen/Qwen3-0.6B"
OUT = "data/distill"; ADAPTER = f"{OUT}/adapter"
EVAL_LANGS = ["ind_Latn", "jav_Latn", "sun_Latn", "tha_Thai"]
N_HELD = 15
os.makedirs(OUT, exist_ok=True)
torch.manual_seed(0)
dev = "cuda"
def held_out_ids():
par = json.load(open("data/math/parallel.json", encoding="utf-8"))
ok = sorted(int(i) for i, v in par.items() if all(v.get(c, {}).get("numbers_ok") for c in EVAL_LANGS))
return sorted(random.Random(42).sample(ok, N_HELD)), par
def load(adapter=False):
tok = AutoTokenizer.from_pretrained(BASE)
tok.padding_side = "left"
m = AutoModelForCausalLM.from_pretrained(BASE, torch_dtype=torch.float16).to(dev)
if adapter:
from peft import PeftModel
m = PeftModel.from_pretrained(m, ADAPTER).merge_and_unload().half().to(dev) # merged: no LoRA overhead at inference
return tok, m.eval()
def evaluate(tag, adapter=False, bs=int(os.environ.get("BS", 12)), max_new=1200):
from lid import profile
from benak_reward import _boxed, _num
ids, par = held_out_ids()
probs = {p["id"]: p for p in json.load(open("data/math/problems.json", encoding="utf-8"))}
tok, m = load(adapter)
jobs = [(i, l) for l in EVAL_LANGS for i in ids]
raw_path = f"{OUT}/raw_{tag}.jsonl" # incremental, so a crash never loses finished batches
done = {}
if os.path.exists(raw_path):
for line in open(raw_path, encoding="utf-8"):
d = json.loads(line); done[(d["id"], d["lang"])] = d
jobs_left = [j for j in jobs if j not in done]
rows = []
for k in range(0, len(jobs_left), bs):
chunk = jobs_left[k:k + bs]
texts = [tok.apply_chat_template([{"role": "user", "content": par[str(i)][l]["text"]}], tokenize=False,
add_generation_prompt=True, enable_thinking=True) for i, l in chunk]
enc = tok(texts, return_tensors="pt", padding=True).to(dev)
with torch.no_grad():
out = m.generate(**enc, max_new_tokens=max_new, do_sample=True, temperature=0.6, top_p=0.95, top_k=20, repetition_penalty=float(os.environ.get("REP_PEN", 1.0)),
pad_token_id=tok.pad_token_id)
with open(raw_path, "a", encoding="utf-8") as f:
for (i, l), seq in zip(chunk, out[:, enc["input_ids"].shape[1]:]):
txt = tok.decode(seq, skip_special_tokens=True)
d = {"id": i, "lang": l, "txt": txt, "think_tokens": int((seq != tok.pad_token_id).sum())}
done[(i, l)] = d
f.write(json.dumps(d, ensure_ascii=False) + chr(10))
print(f"[{tag}] {len(done)}/{len(jobs)}", flush=True)
if os.environ.get("GEN_ONLY"): # low-RAM machines: score in a separate process (GlotLID needs 1.7 GB RAM)
print("generation done; run: python distill.py score", tag); return
del m; import gc; gc.collect(); torch.cuda.empty_cache()
for (i, l) in jobs:
txt = done[(i, l)]["txt"]
think, _, final = txt.partition("</think>")
think = think.replace("<think>", "").strip()
got = _num(_boxed(final) or "") if final else None
ans = probs[i]["answer"]
correct = got is not None and abs(got - ans) <= max(0.011, 1e-4 * abs(ans))
rows.append({"id": i, "lang": l, "tag": tag, "correct": correct, "finished": bool(final),
"think_tokens": done[(i, l)]["think_tokens"], "lid": profile(think, l, exclude=par[str(i)][l]["text"]),
"think": think, "final": final})
json.dump(rows, open(f"{OUT}/eval_{tag}.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1)
summarize(tag, rows)
def summarize(tag, rows):
s = {}
for l in EVAL_LANGS + ["all"]:
rs = [r for r in rows if l == "all" or r["lang"] == l]
t = [r["lid"]["target_share"] for r in rs if r["lid"]["target_share"] is not None]
e = [r["lid"]["eng_share"] for r in rs if r["lid"]["eng_share"] is not None]
s[l] = {"n": len(rs), "acc": round(100 * sum(r["correct"] for r in rs) / len(rs), 1),
"target_share": round(sum(t) / len(t), 3) if t else None, "eng_share": round(sum(e) / len(e), 3) if e else None,
"finished": round(100 * sum(r["finished"] for r in rs) / len(rs), 1)}
json.dump(s, open(f"{OUT}/summary_{tag}.json", "w"), indent=1)
print(tag, json.dumps(s))
def train(epochs=1, max_len=int(os.environ.get("MAXLEN", 768)), lr=2e-4, accum=8, limit=int(os.environ.get("LIMIT", 0))):
from peft import LoraConfig, get_peft_model
ids, _ = held_out_ids()
rows = [json.loads(l) for l in open("release/dataset/data/sea_thinking.jsonl", encoding="utf-8")]
# no leakage: drop every math row whose problem is held out (in any language)
heldp = {json.load(open("data/math/parallel.json", encoding="utf-8"))[str(i)][l]["text"] for i in ids
for l in json.load(open("data/math/parallel.json", encoding="utf-8"))[str(i)]}
rows = [r for r in rows if r["user"] not in heldp]
tok = AutoTokenizer.from_pretrained(BASE)
m = AutoModelForCausalLM.from_pretrained(BASE, torch_dtype=torch.float16).to(dev)
m.gradient_checkpointing_enable(); m.enable_input_require_grads()
m = get_peft_model(m, LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, task_type="CAUSAL_LM",
target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]))
for p in m.parameters():
if p.requires_grad:
p.data = p.data.float() # fp32 adapters, fp16 frozen base
ex = []
for r in rows:
prompt = tok.apply_chat_template([{"role": "user", "content": r["user"]}], tokenize=False,
add_generation_prompt=True, enable_thinking=True)
target = f"<think>\n{r['analysis'].strip()}\n</think>\n\n{r['final'].strip()}<|im_end|>"
p_ids = tok(prompt, add_special_tokens=False)["input_ids"]; t_ids = tok(target, add_special_tokens=False)["input_ids"]
ids_ = (p_ids + t_ids)[:max_len]; lab = ([-100] * len(p_ids) + t_ids)[:max_len]
if any(x != -100 for x in lab):
ex.append((ids_, lab))
random.Random(0).shuffle(ex)
if limit:
ex = ex[:limit]
print(f"train examples {len(ex)}, mean len {sum(len(e[0]) for e in ex) / len(ex):.0f}", flush=True)
opt = torch.optim.AdamW([p for p in m.parameters() if p.requires_grad], lr=lr, weight_decay=0.0)
steps = math.ceil(len(ex) * epochs / accum)
sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: min(1.0, (s + 1) / 10) * max(0.0, 1 - s / steps))
scaler = torch.amp.GradScaler("cuda")
m.train(); log = []; t0 = time.time(); step = 0
for ep in range(epochs):
for k, (ids_, lab) in enumerate(ex):
x = torch.tensor([ids_], device=dev); y = torch.tensor([lab], device=dev)
with torch.autocast("cuda", dtype=torch.float16):
loss = m(input_ids=x, labels=y).loss / accum
scaler.scale(loss).backward()
if (k + 1) % accum == 0 or k == len(ex) - 1:
scaler.unscale_(opt); torch.nn.utils.clip_grad_norm_(m.parameters(), 1.0)
scaler.step(opt); scaler.update(); opt.zero_grad(); sched.step(); step += 1
log.append({"step": step, "loss": round(loss.item() * accum, 4), "s": round(time.time() - t0)})
if step % 2 == 0:
print(f"step {step}/{steps} loss {log[-1]['loss']} {log[-1]['s']}s", flush=True)
m.save_pretrained(ADAPTER)
json.dump({"n_train": len(ex), "held_out_problem_ids": ids, "epochs": epochs, "max_len": max_len, "lr": lr,
"accum": accum, "lora_r": 16, "base": BASE, "log": log}, open(f"{OUT}/train_log.json", "w"), indent=1)
print("saved adapter; train examples", len(ex))
def publish(repo="PugarHuda/benak-qwen3-0.6b-lora"):
from huggingface_hub import HfApi
b = json.load(open(f"{OUT}/summary_baseline.json")); a = json.load(open(f"{OUT}/summary_after.json"))
tl = json.load(open(f"{OUT}/train_log.json"))
names = {"ind_Latn": "Indonesian", "jav_Latn": "Javanese", "sun_Latn": "Sundanese", "tha_Thai": "Thai", "all": "**all**"}
table = "\n".join(f"| {names[l]} | {pct(b[l]['eng_share'])} → **{pct(a[l]['eng_share'])}** | {pct(b[l]['target_share'])} → **{pct(a[l]['target_share'])}** | {b[l]['acc']}% → {a[l]['acc']}% |"
for l in EVAL_LANGS + ["all"])
S = json.load(open(f"{OUT}/stats.json"))
st_, mc, dg = S["eng_share_sign_test"], S["acc_mcnemar"], S["degenerate_think_gt20pct_repeat"]
stats_md = (f"* The English share of thinking fell in **{st_['decreased']} of {st_['pairs']}** paired items and rose in "
f"{st_['increased']} (exact sign test p = {st_['p_exact']:.1e})." + chr(10) +
f"* The accuracy change is **not significant** (McNemar {mc['baseline_only']} vs {mc['after_only']}, p = {mc['p_exact']})." + chr(10) +
f"* **Cost:** {dg['after']}/{S['n']} outputs fall into repetition loops (> 20% of the thinking is one repeated "
f"8-gram), against {dg['baseline']}/{S['n']} before. One epoch of LoRA on about 1k traces makes the model think "
f"in the language but also makes it loop. That is a measured trade-off, not hidden.")
card = f"""---
base_model: {BASE}
library_name: peft
license: apache-2.0
datasets:
- PugarHuda/benak
language: [id, jv, su, th, ms, tl, vi, ceb]
tags: [lora, reasoning, multilingual, southeast-asia, beam, distillation]
---
# benak-qwen3-0.6b-lora: a small model that thinks in your language
A LoRA adapter for **{BASE}**, trained on the [`sea_thinking`](https://huggingface.co/datasets/PugarHuda/benak) traces from
Beam-1.0-501B-A23B. These are correct answers whose reasoning is ≥ 80% in the user's language. It is the proof-of-use for the [Benak](https://huggingface.co/spaces/PugarHuda/benak) dataset,
built for the Build with Beam challenge.
## Before vs after, on **held-out** math problems
The {N_HELD} problems below were never in training, in any language. There is no language instruction in the prompt (Benak condition C0), and each problem is
sampled once (temperature 0.6) per language. Reasoning language is measured by GlotLID on the `<think>` block, after removing sentences that quote the prompt.
| language | English share of thinking | in-language share of thinking | accuracy |
|---|---|---|---|
{table}
## Training
* {tl['n_train']} examples, {tl['epochs']} epoch, LoRA r={tl['lora_r']} on all attention and MLP projections, lr {tl['lr']}, max length {tl['max_len']}, effective batch {tl['accum']}.
* Trained on one GTX 1660 SUPER (6 GB) with fp16 autocast. The final logged loss was {tl['log'][-1]['loss']}, after {tl['log'][-1]['s']} s.
* Code: `distill.py` in the dataset repo. Held-out ids: {tl['held_out_problem_ids']}.
## Statistics
{stats_md}
## Limits
{N_HELD} problems × 4 languages = {N_HELD * 4} generations per side, one sample each. Accuracy at 0.6B is low on these multi-step problems, and the
claim here is about the **language of thinking**, not about math skill. Sundanese moved least (in-language 5% → 19%).
"""
os.makedirs(f"{OUT}/card", exist_ok=True)
open(f"{ADAPTER}/README.md", "w", encoding="utf-8").write(card)
api = HfApi(); api.create_repo(repo, exist_ok=True)
api.upload_folder(folder_path=ADAPTER, repo_id=repo, commit_message="benak LoRA adapter + eval card")
print("published", repo)
def pct(x):
return "–" if x is None else f"{round(100 * x)}%"
if __name__ == "__main__":
if sys.argv[1] == "score": # scoring only: reuse raw generations, never loads the LLM
tag = sys.argv[2]
def evaluate_score(tag=tag):
from lid import profile
from benak_reward import _boxed, _num
ids, par = held_out_ids()
probs = {p["id"]: p for p in json.load(open("data/math/problems.json", encoding="utf-8"))}
done = {(d["id"], d["lang"]): d for d in map(json.loads, open(f"{OUT}/raw_{tag}.jsonl", encoding="utf-8"))}
rows = []
for (i, l) in [(i, l) for l in EVAL_LANGS for i in ids]:
think, _, final = done[(i, l)]["txt"].partition("</think>")
think = think.replace("<think>", "").strip()
got = _num(_boxed(final) or "") if final else None
ans = probs[i]["answer"]
rows.append({"id": i, "lang": l, "tag": tag, "finished": bool(final), "think_tokens": done[(i, l)]["think_tokens"],
"correct": got is not None and abs(got - ans) <= max(0.011, 1e-4 * abs(ans)),
"lid": profile(think, l, exclude=par[str(i)][l]["text"]), "think": think, "final": final})
json.dump(rows, open(f"{OUT}/eval_{tag}.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1)
summarize(tag, rows)
evaluate_score()
else:
{"baseline": lambda: evaluate("baseline"), "train": train, "after": lambda: evaluate("after", adapter=True),
"after_rp": lambda: evaluate("after_rp", adapter=True),
"publish": publish}[sys.argv[1]]()
|