"""Attach a trained teacher's probabilities to the labelled rows and to an unlabelled pool. python distill_data.py runs/ data_distill gen_train3.jsonl real_big.jsonl Writes data_distill/ with train.jsonl (labelled rows + "probs", unlabelled rows with "probs" only) and copies of the evaluation sets. Pool sentences that appear in any evaluation set are dropped. """ import os import sys import json import shutil from pathlib import Path import numpy as np import torch from transformers import AutoModel, AutoTokenizer teacher_dir, out_dir, pools = Path(sys.argv[1]), Path(sys.argv[2]), sys.argv[3:] data = Path(os.environ.get("DATA", "data")) out_dir.mkdir(exist_ok=True) for name in ("val", "test", "test_real", "hard", "labels"): for suffix in (".jsonl", ".json"): if (data / f"{name}{suffix}").exists(): shutil.copy(data / f"{name}{suffix}", out_dir) held_out = {(r["kind"], r["text"].strip().lower()) for name in ("val", "test", "test_real", "hard") for r in map(json.loads, open(data / f"{name}.jsonl"))} rows = [json.loads(line) for line in open(data / "train.jsonl")] seen = {(r["kind"], r["text"]) for r in rows} for pool in pools: for line in open(pool): request = json.loads(line) for sentence in request["sentences"]: key = (request["kind"], sentence.strip()) if key not in seen and (key[0], key[1].lower()) not in held_out: seen.add(key) rows.append({"kind": key[0], "text": key[1], "source": request.get("source") or request.get("model")}) print(len(rows), "rows,", sum("ok" in r for r in rows), "labelled", flush=True) device = "cuda" if torch.cuda.is_available() else "cpu" tokenizer = AutoTokenizer.from_pretrained(teacher_dir) dtype = torch.bfloat16 if os.environ.get("TEACHER_BF16") else torch.float32 # bf16 for multi-billion teachers model = AutoModel.from_pretrained(teacher_dir, torch_dtype=dtype).to(device).eval() heads = np.load(teacher_dir / "gesture_heads.npz") teacher_args = json.loads((teacher_dir / "training.json").read_text())["args"] prefix, pooling = teacher_args.get("prefix", ""), teacher_args.get("pooling", "mean") with torch.no_grad(): for start in range(0, len(rows), 256): chunk = rows[start : start + 256] batch = tokenizer([prefix + r["text"] for r in chunk], padding=True, truncation=True, max_length=64, return_tensors="pt").to(device) hidden = model(**batch).last_hidden_state if pooling == "first": pooled = hidden[:, 0] elif pooling == "last": last = (batch["attention_mask"] * torch.arange(hidden.shape[1], device=device)).argmax(1) pooled = hidden[torch.arange(hidden.shape[0], device=device), last] else: mask = batch["attention_mask"].unsqueeze(-1).float() pooled = (hidden * mask).sum(1) / mask.sum(1) pooled = torch.nn.functional.normalize(pooled.float(), dim=-1).cpu().numpy() * 10.0 for r, v in zip(chunk, pooled): logits = heads[f"{r['kind']}_weight"] @ v + heads[f"{r['kind']}_bias"] p = np.exp(logits - logits.max()) r["probs"] = [round(float(x), 5) for x in p / p.sum()] if start % 25600 == 0: print(start, flush=True) with open(out_dir / "train.jsonl", "w") as f: f.writelines(json.dumps(r, ensure_ascii=False) + "\n" for r in rows) print("written", out_dir / "train.jsonl")