Buckets:
| """Train System-1-RLCD: multilingual + Azerbaijani typed-decision model. | |
| Base: the mmBERT-base decision checkpoint. Objective: the strictly proper RLCD reward | |
| (log + 0.5 * spherical - RPS on ordinal questions), maximised by direct gradient ascent. | |
| Data (all label-first or human-labelled): | |
| * synthetic routing / decisions / guard in 16 languages (LLM teacher + independent LLM judge filter), | |
| split by schema group: 90% train, 5% val, 5% test (test schemas are never seen) | |
| * MASSIVE (14 languages): scenario, intent with 5..60 options, intent yes/no | |
| * Azerbaijani app-review sentiment | |
| Held out entirely (zero-shot evals): SIB-200, AG News, DAIR Emotion, Banking77, SMS spam, hand-written routing set. | |
| """ | |
| import hashlib, json, math, os, random, shutil, sys, time | |
| import numpy as np, torch | |
| ROOT = "." | |
| sys.path.insert(0, f"{ROOT}/pkg"); sys.path.insert(0, f"{ROOT}/bench") | |
| import thx01 as systemone, tasks | |
| from thx01.common import QTYPES, build_sequence, collate_items, proper_reward, render_options, temp_bucket | |
| from safetensors.torch import save_file | |
| import bitsandbytes as bnb | |
| SEED, EPOCHS, TOK_BUDGET, LR_ENC, LR_HEAD = 0, 2, 12000, 3e-5, 1e-4 | |
| OUT = f"{ROOT}/ckpt/system1_v3" | |
| CURVE = f"{ROOT}/results/train_curve.jsonl" | |
| rng = random.Random(SEED); torch.manual_seed(SEED) | |
| SYN = f"{ROOT}/data/synth" | |
| def split_of(group): | |
| h = int(hashlib.md5(group.encode()).hexdigest(), 16) % 20 | |
| return "test" if h == 0 else "val" if h == 1 else "train" | |
| def split_synth(): | |
| for kind in ("routing", "decisions", "guard", "taxonomy", "emotion"): | |
| rows = [json.loads(l) for l in open(f"{SYN}/{kind}.jsonl")] | |
| fh = {s: open(f"{SYN}/{kind}_{s}.jsonl", "w") for s in ("train", "val", "test")} | |
| for r in rows: | |
| fh[split_of(r["meta"]["group"])].write(json.dumps(r, ensure_ascii=False) + "\n") | |
| for f in fh.values(): | |
| f.close() | |
| print(kind, len(rows)) | |
| def _garbled(q): | |
| """Option keys whose non-ASCII letters were stripped by an early slug() (e.g. 'acil_v_ziyy_tdirmi').""" | |
| import re | |
| return bool(re.search(r"[^\x00-\x7f]", q["instructions"])) and any( | |
| len(k.split("_")) >= 2 and any(len(s) == 1 for s in k.split("_")) for k in q["criteria"]) | |
| def synth_items(split): | |
| out = [] | |
| for kind in ("routing", "decisions", "guard", "taxonomy", "emotion"): | |
| for l in open(f"{SYN}/{kind}_{split}.jsonl"): | |
| r = json.loads(l) | |
| for qid, g in r["gold"].items(): | |
| q = dict(r["questions"][qid]) | |
| if q["type"] == "choice" and _garbled(q): | |
| continue | |
| if q["type"] == "choice": # random option order | |
| it = list(q["criteria"].items()); rng.shuffle(it); q["criteria"] = dict(it) | |
| out.append((r["state"], {qid: q}, {qid: g})) | |
| return out | |
| def reshuffle(state, q, gold, min_k=3, max_k=None): | |
| (qid, qd), = q.items() | |
| if qd["type"] != "choice": | |
| return state, q, gold | |
| items = list(qd["criteria"].items()); g = gold[qid] | |
| hi = min(len(items), max_k or len(items)) | |
| k = rng.randint(min(min_k, hi), hi) | |
| others = [it for it in items if it[0] != g] | |
| sel = rng.sample(others, k - 1) + [it for it in items if it[0] == g] | |
| rng.shuffle(sel) | |
| return state, {qid: {**qd, "criteria": dict(sel)}}, gold | |
| def massive(lang, n_scen, n_int, n_noul, seed): | |
| d = [reshuffle(*x) for x in tasks.massive_scenario(lang, "train", n_scen, seed=seed)] | |
| d += [reshuffle(*x, min_k=5) for x in tasks.massive_intent(lang, "train", n_int, k=60, seed=seed + 1)] | |
| d += list(tasks.intent_noul(lang, "train", n_noul, seed=seed + 2)) | |
| return d | |
| def build_train(): | |
| d = synth_items("train") | |
| print("synthetic items", len(d)) | |
| d += massive("az", 4000, 5000, 3000, 10) | |
| d += massive("en", 2000, 2500, 1500, 20) | |
| for i, l in enumerate(["ru", "tr", "de", "fr", "es", "ar", "hi", "zh-CN", "fa", "ka", "ja", "ko"]): | |
| d += massive(l, 600, 800, 400, 100 + 10 * i) | |
| d += list(tasks.az_sentiment("train", 3000, seed=4)) + list(tasks.az_sentiment("train", 2000, seed=5, as_noul=True)) | |
| rng.shuffle(d) | |
| return d | |
| def encode(ag, st, q, gold): | |
| (qid, qd), = q.items() | |
| qi = ag._to_internal(qd) | |
| seq, markers = build_sequence(ag.tok, st, qi, ag.cfg["max_len"], ag._head_budget(qi)) | |
| if len(markers) != len(render_options(qi)): | |
| return None | |
| g = gold[qid] | |
| if qi["t"] == "noul": | |
| label = int(bool(g)) | |
| elif qi["t"] == "score": | |
| label = int(g) | |
| else: | |
| label = list(qi["crit"].keys()).index(g) | |
| k = len(markers) | |
| if not 0 <= label < k: | |
| return None | |
| tgt = [0.0] * k; tgt[label] = 1.0 | |
| return {"ids": seq, "markers": markers, "qtype": QTYPES[qi["t"]], "label": label, "target": tgt} | |
| def batches(data): | |
| """Length-bucketed batches under a token budget.""" | |
| idx = sorted(range(len(data)), key=lambda i: len(data[i]["ids"])) | |
| out, cur, mx = [], [], 0 | |
| for i in idx: | |
| L = len(data[i]["ids"]) | |
| if cur and max(mx, L) * (len(cur) + 1) > TOK_BUDGET: | |
| out.append(cur); cur, mx = [], 0 | |
| cur.append(i); mx = max(mx, L) | |
| if cur: | |
| out.append(cur) | |
| return out | |
| def forward(model, b): | |
| with torch.autocast("cuda", dtype=torch.bfloat16): | |
| return model(b["input_ids"].cuda(), b["attention_mask"].cuda(), b["marker_pos"].cuda(), | |
| b["marker_mask"].cuda(), b["qtype"].cuda()) | |
| def main(): | |
| split_synth() | |
| ag = systemone.load(os.environ.get("BASE_CKPT", "base"), subfolder=None, device="cuda", half=False) | |
| model = ag.model; model.train() | |
| emb = model.encoder.embeddings.tok_embeddings | |
| emb.weight.requires_grad_(False); emb.to(torch.bfloat16) | |
| enc_p = [p for n, p in model.named_parameters() if p.requires_grad and n.startswith("encoder.")] | |
| head_p = [p for n, p in model.named_parameters() if p.requires_grad and not n.startswith("encoder.")] | |
| opt = bnb.optim.AdamW8bit([{"params": enc_p, "lr": LR_ENC}, {"params": head_p, "lr": LR_HEAD}], weight_decay=0.01) | |
| data = [e for e in (encode(ag, *x) for x in build_train()) if e] | |
| print("train items", len(data), flush=True) | |
| bl = batches(data) | |
| steps = EPOCHS * len(bl); warm = int(0.04 * steps) | |
| sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: min(1, (s + 1) / warm) * max(0.0, (steps - s) / max(1, steps - warm))) | |
| step, t0 = 0, time.time() | |
| curve = open(CURVE, "w") | |
| run_loss = run_acc = 0.0 | |
| for ep in range(EPOCHS): | |
| rng.shuffle(bl) | |
| for bi in bl: | |
| b = collate_items([[data[i] for i in bi]], ag.tok.pad_token_id) | |
| logits, _ = forward(model, b) | |
| p = torch.softmax(logits.float(), -1) | |
| loss = -proper_reward(p, b["target"].cuda(), b["qtype"].cuda(), b["marker_mask"].cuda().float()).mean() | |
| loss.backward() | |
| torch.nn.utils.clip_grad_norm_(enc_p + head_p, 1.0) | |
| opt.step(); sched.step(); opt.zero_grad(set_to_none=True); step += 1 | |
| run_loss += loss.item(); run_acc += (logits.argmax(-1).cpu() == b["label"]).float().mean().item() | |
| if step % 50 == 0: | |
| curve.write(json.dumps({"step": step, "epoch": ep, "loss": run_loss / 50, "acc": run_acc / 50, | |
| "lr": sched.get_last_lr()[0]}) + "\n"); curve.flush() | |
| run_loss = run_acc = 0.0 | |
| if step % 200 == 0: | |
| acc = (logits.argmax(-1).cpu() == b["label"]).float().mean().item() | |
| print(f"ep {ep} step {step}/{steps} loss {loss.item():.4f} acc {acc:.3f} " | |
| f"mem {torch.cuda.max_memory_allocated() / 1e9:.1f}GB {time.time() - t0:.0f}s", flush=True) | |
| # ---- temperatures per (type, option-count) bucket on validation data | |
| model.eval() | |
| val = synth_items("val") | |
| for l in ("az", "en"): | |
| val += [reshuffle(*x) for x in tasks.massive_scenario(l, "validation", 300, seed=77)] | |
| val += [reshuffle(*x, min_k=5) for x in tasks.massive_intent("az", "validation", 600, k=60, seed=78)] | |
| vit = [e for e in (encode(ag, *x) for x in val) if e] | |
| buckets = {} | |
| with torch.no_grad(): | |
| for bi in batches(vit): | |
| chunk = [vit[i] for i in bi] | |
| b = collate_items([chunk], ag.tok.pad_token_id) | |
| lg, _ = forward(model, b); lg = lg.float().cpu() | |
| for j, it in enumerate(chunk): | |
| k = len(it["markers"]) | |
| buckets.setdefault(temp_bucket(it["qtype"], k), []).append((lg[j, :k], it["label"])) | |
| temps = {} | |
| for bk, xs in buckets.items(): | |
| if len(xs) < 40: | |
| continue | |
| L = torch.nn.utils.rnn.pad_sequence([x for x, _ in xs], batch_first=True, padding_value=-1e4) | |
| y = torch.tensor([t for _, t in xs]) | |
| best = min(np.arange(0.5, 5.01, 0.05), key=lambda T: torch.nn.functional.cross_entropy(L / T, y).item()) | |
| temps[bk] = round(float(best), 3) | |
| print("temperatures", temps, {k: len(v) for k, v in buckets.items()}) | |
| os.makedirs(OUT, exist_ok=True) | |
| save_file({k: v.detach().to(torch.float16).contiguous() for k, v in model.state_dict().items()}, f"{OUT}/model.safetensors") | |
| for sub in ("encoder", "tokenizer"): | |
| shutil.copytree(os.path.join(os.environ.get("BASE_CKPT", "base"), sub), f"{OUT}/{sub}", dirs_exist_ok=True) | |
| cfg = dict(ag.cfg) | |
| cfg.update({"model_name": "THX-01", "temperature_by_options": temps, "auto_head_budget": True, | |
| "training": {"objective": "RLCD strictly proper scoring reward (log + spherical + RPS)", | |
| "steps": steps, "epochs": EPOCHS, "items": len(data), | |
| "minutes": round((time.time() - t0) / 60, 1), | |
| "languages": "az, en, ru, tr, de, fr, es, ar, hi, zh, fa, ka, ja, ko, uk, kk, uz, it", | |
| "held_out": "SIB-200, AG News, DAIR Emotion, Banking77, SMS spam, hand-written routing set"}}) | |
| if "temperature" in cfg: | |
| t = cfg["temperature"] | |
| for qt, name in ((0, "choice"), (1, "score"), (2, "noul")): | |
| vals = [v for k, v in temps.items() if k.startswith(name)] | |
| if vals: | |
| t[qt] = round(float(np.median(vals)), 3) | |
| cfg["temperature"] = t | |
| json.dump(cfg, open(f"{OUT}/rl_agent_config.json", "w"), indent=2) | |
| print("saved", OUT) | |
| if __name__ == "__main__": | |
| main() | |
Xet Storage Details
- Size:
- 10.4 kB
- Xet hash:
- 9cc8f0ff20224bb9381b9d45fa77e1b3d019eb3ff7eb94dc96cba9bab77e2f4e
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.