# /// script # requires-python = ">=3.11" # dependencies = ["torch", "transformers<5", "sentencepiece", "huggingface_hub", "numpy"] # /// """Fine-tune a sentence encoder with two gesture heads (say / react). python train.py --base --data --out Each example has the gestures the teachers accept ("ok"). The loss rewards probability mass on that set, plus a smaller cross-entropy pull towards the teachers' single best choice, so ambiguous sentences are not forced to one move. """ import os import sys import json import math import time import random import argparse from pathlib import Path import numpy as np import torch from torch import nn from transformers import AutoModel, AutoTokenizer, get_cosine_schedule_with_warmup parser = argparse.ArgumentParser() parser.add_argument("--base", required=True) parser.add_argument("--data", required=True) parser.add_argument("--out", required=True) parser.add_argument("--epochs", type=int, default=5) parser.add_argument("--lr", type=float, default=4e-5) parser.add_argument("--head_lr", type=float, default=2e-3) parser.add_argument("--batch", type=int, default=64) parser.add_argument("--max_len", type=int, default=64) parser.add_argument("--prefix", default="") parser.add_argument("--best_weight", type=float, default=0.3) parser.add_argument("--seed", type=int, default=0) parser.add_argument("--push", action="store_true", help="--out is a Hub repo id to push to") parser.add_argument("--bucket", default="", help="upload the run to hf://buckets/") parser.add_argument("--distill_weight", type=float, default=0.0, help="weight of the KL term towards rows' teacher probs") parser.add_argument("--frac", type=float, default=1.0, help="fraction of the training set to use") parser.add_argument("--distill_temp", type=float, default=1.0, help="soften student and teacher distributions for the KL term") parser.add_argument("--optim", default="adamw", choices=["adamw", "adamw8bit"], help="adamw8bit (bitsandbytes) fits 8B encoders on one GPU") parser.add_argument("--pooling", default="mean", choices=["mean", "last", "first"], help="last = last real token (decoder embedders like Qwen3-Embedding)") parser.add_argument("--save_dtype", default="float16", choices=["float16", "bfloat16", "float32"]) args = parser.parse_args() args.prefix = args.prefix.replace("\\n", "\n") # allow "\n" in prefixes passed through env vars random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu" data = Path(args.data) labels = json.loads((data / "labels.json").read_text()) # {"say": [...moves, "none"], "react": [...]} KINDS = ("say", "react") def load(name: str) -> list[dict]: path = data / f"{name}.jsonl" return [json.loads(line) for line in path.open()] if path.exists() else [] splits = {name: load(name) for name in ("train", "val", "test", "test_real", "hard")} splits["train"] = random.Random(1).sample(splits["train"], int(len(splits["train"]) * args.frac)) print({k: len(v) for k, v in splits.items()}, "device", device, flush=True) tokenizer = AutoTokenizer.from_pretrained(args.base) encoder = AutoModel.from_pretrained(args.base).to(device) dim = encoder.config.hidden_size heads = nn.ModuleDict({k: nn.Linear(dim, len(labels[k])) for k in KINDS}).to(device) def pool(hidden: torch.Tensor, attention_mask: torch.Tensor, pooling: str) -> torch.Tensor: if pooling == "first": # CLS token (bge-m3) return hidden[:, 0] if pooling == "last": # works for left or right padding positions = torch.arange(attention_mask.shape[1], device=attention_mask.device) last = (attention_mask * positions).argmax(1) return hidden[torch.arange(hidden.shape[0], device=hidden.device), last] mask = attention_mask.unsqueeze(-1).to(hidden.dtype) return (hidden * mask).sum(1) / mask.sum(1) def embed(texts: list[str]) -> torch.Tensor: batch = tokenizer([args.prefix + t for t in texts], padding=True, truncation=True, max_length=args.max_len, return_tensors="pt").to(device) hidden = encoder(**batch).last_hidden_state pooled = pool(hidden, batch["attention_mask"], args.pooling) return nn.functional.normalize(pooled, dim=-1) * 10.0 # fixed scale keeps the heads well conditioned def targets(rows: list[dict], kind: str) -> tuple[torch.Tensor, torch.Tensor]: index = {m: i for i, m in enumerate(labels[kind])} ok = torch.zeros(len(rows), len(labels[kind]), device=device) for r, row in enumerate(rows): for move in row["ok"]: ok[r, index[move]] = 1.0 best = torch.tensor([index[row["best"]] for row in rows], device=device) return ok, best def loss_fn(logits: torch.Tensor, ok: torch.Tensor, best: torch.Tensor) -> torch.Tensor: log_probs = logits.log_softmax(-1) set_loss = -(log_probs + torch.log(ok.clamp_min(1e-12))).logsumexp(-1) return (set_loss + args.best_weight * nn.functional.cross_entropy(logits, best, label_smoothing=0.05)).mean() @torch.no_grad() def predict(rows: list[dict]) -> list[tuple[str, float]]: encoder.eval() out: list[tuple[str, float] | None] = [None] * len(rows) for kind in KINDS: idx = [i for i, r in enumerate(rows) if r["kind"] == kind] for start in range(0, len(idx), 256): chunk = idx[start : start + 256] probs = heads[kind](embed([rows[i]["text"] for i in chunk])).softmax(-1).cpu().numpy() for i, p in zip(chunk, probs): j = int(p.argmax()) out[i] = (labels[kind][j], float(p[j])) encoder.train() return out # type: ignore[return-value] def score(rows: list[dict], preds: list[tuple[str, float]], threshold: float) -> dict: right = wrong = missed = 0 for row, (move, prob) in zip(rows, preds): got = move if move != "none" and prob >= threshold else "none" if got in row["ok"]: right += 1 elif got == "none": missed += 1 else: wrong += 1 return {"acc": round(right / max(1, len(rows)), 4), "wrong": wrong, "missed": missed, "n": len(rows)} def report(tag: str) -> dict: result = {} for name in ("val", "test", "test_real", "hard"): rows = splits[name] if not rows: continue preds = predict(rows) best = max((score(rows, preds, t / 20) | {"thr": t / 20} for t in range(0, 20)), key=lambda s: (s["acc"], -s["wrong"])) result[name] = {"thr0": score(rows, preds, 0.0), "best": best} print(tag, json.dumps(result), flush=True) return result params = [{"params": encoder.parameters(), "lr": args.lr}, {"params": heads.parameters(), "lr": args.head_lr}] if args.optim == "adamw8bit": import bitsandbytes as bnb optimizer = bnb.optim.AdamW8bit(params, weight_decay=0.01) else: optimizer = torch.optim.AdamW(params, weight_decay=0.01) train = splits["train"] steps_per_epoch = math.ceil(len(train) / args.batch) scheduler = get_cosine_schedule_with_warmup(optimizer, int(0.06 * steps_per_epoch * args.epochs), steps_per_epoch * args.epochs) use_amp = device == "cuda" history = [report("epoch 0")] best_val, best_state = -1.0, None for epoch in range(1, args.epochs + 1): random.shuffle(train) started, total = time.time(), 0.0 for step in range(steps_per_epoch): batch = train[step * args.batch : (step + 1) * args.batch] loss = torch.zeros((), device=device) with torch.autocast("cuda", dtype=torch.bfloat16, enabled=use_amp): vectors = embed([r["text"] for r in batch]) for kind in KINDS: idx = [i for i, r in enumerate(batch) if r["kind"] == kind] if not idx: continue logits = heads[kind](vectors[idx].float()) labelled = [n for n, i in enumerate(idx) if "ok" in batch[i]] if labelled: ok, best = targets([batch[idx[n]] for n in labelled], kind) loss = loss + loss_fn(logits[labelled], ok, best) * len(labelled) / len(batch) distilled = [n for n, i in enumerate(idx) if "probs" in batch[i]] if distilled and args.distill_weight: teacher = torch.tensor([batch[idx[n]]["probs"] for n in distilled], device=device) temp = args.distill_temp teacher = (teacher.clamp_min(1e-8).log() / temp).softmax(-1) kl = nn.functional.kl_div((logits[distilled] / temp).log_softmax(-1), teacher, reduction="batchmean") * temp * temp loss = loss + args.distill_weight * kl * len(distilled) / len(batch) loss.backward() torch.nn.utils.clip_grad_norm_(list(encoder.parameters()) + list(heads.parameters()), 1.0) optimizer.step() scheduler.step() optimizer.zero_grad() total += loss.item() print(f"epoch {epoch} loss {total / steps_per_epoch:.4f} ({time.time() - started:.0f}s)", flush=True) history.append(report(f"epoch {epoch}")) val = history[-1]["val"]["best"]["acc"] if val > best_val: best_val = val best_state = ({k: v.detach().cpu().clone() for k, v in encoder.state_dict().items()}, {k: v.detach().cpu().clone() for k, v in heads.state_dict().items()}) encoder.load_state_dict(best_state[0]) heads.load_state_dict(best_state[1]) final = report("final (best val epoch)") save = Path("/tmp/out") save.mkdir(parents=True, exist_ok=True) encoder.to(getattr(torch, args.save_dtype)).save_pretrained(save) # fp16 keeps the student small; export casts back tokenizer.save_pretrained(save) np.savez(save / "gesture_heads.npz", **{f"{k}_weight": heads[k].weight.detach().cpu().numpy() for k in KINDS}, **{f"{k}_bias": heads[k].bias.detach().cpu().numpy() for k in KINDS}) (save / "gesture_labels.json").write_text(json.dumps(labels, indent=1)) (save / "training.json").write_text(json.dumps({"args": vars(args), "history": history, "final": final}, indent=1)) if args.push: from huggingface_hub import HfApi api = HfApi() api.create_repo(args.out, private=True, exist_ok=True) api.upload_folder(folder_path=save, repo_id=args.out, commit_message=f"train {args.base}") print("pushed to", args.out, flush=True) elif args.bucket: import subprocess # the job's /data mount does not upload what is written to it, so push explicitly with the hf CLI command = ["uvx", "--from", "huggingface_hub>=1.17", "hf", "buckets", "sync", str(save), f"hf://buckets/{args.bucket}"] result = subprocess.run(command, capture_output=True, text=True) print("bucket upload", result.returncode, result.stdout[-300:], result.stderr[-500:], flush=True) else: Path(args.out).mkdir(parents=True, exist_ok=True) os.system(f"cp -r {save}/. {args.out}")