File size: 10,921 Bytes
0cc835c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# /// 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 <hf model> --data <dir with train/val/test jsonl + labels.json> --out <hub repo or dir>

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/<this>")
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}")