aien-train
AIEN training programme: language-model history, GB10 constraints and the route to training on the project engine. Plans and runnable checks are distinguished.
Brought by drakestapleton
aien-train / streams / math-training / common.py
| 1 | # Shared pieces for the L283 math-training experiments: data, frozen model, feature extraction, receipts. |
| 2 | # PyTorch here is an oracle (feature extraction and baselines), never the product path. |
| 3 | import hashlib, json, os, platform, subprocess, sys, time |
| 4 | import numpy as np |
| 5 | import torch |
| 6 | |
| 7 | ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 8 | SCRATCH = os.path.join(ROOT, ".scratch") |
| 9 | EVID = os.path.join(ROOT, "evidence", "math-training") |
| 10 | MODEL_DIR = os.path.expanduser("~/models/SmolLM2-1.7B-Instruct-31b70e2e869a") |
| 11 | MODEL_SHA = "f55217be716b6a997b97b9d8d7eb6fad02e00858f5010ec24f64603c3a98a0e8" # PROVENANCE.md, model.safetensors |
| 12 | SEQ = 256 |
| 13 | DEV = "cuda" |
| 14 | |
| 15 | |
| 16 | def code_sha(): |
| 17 | return subprocess.run(["git", "-C", ROOT, "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip() |
| 18 | |
| 19 | |
| 20 | def code_dirty(): |
| 21 | out = subprocess.run(["git", "-C", ROOT, "status", "--porcelain", "streams"], capture_output=True, text=True).stdout |
| 22 | return bool(out.strip()) |
| 23 | |
| 24 | |
| 25 | def receipt(name, payload): |
| 26 | """Write evidence/math-training/<name>.json with chip, model sha, code sha and command.""" |
| 27 | os.makedirs(EVID, exist_ok=True) |
| 28 | gpu = torch.cuda.get_device_name(0) if torch.cuda.is_available() else "none" |
| 29 | body = { |
| 30 | "chip": "GB10 (DGX Spark)", "torch_device": gpu, "host": platform.node(), |
| 31 | "model": MODEL_DIR, "model_sha256": MODEL_SHA, |
| 32 | "code_sha": code_sha(), "code_dirty": code_dirty(), |
| 33 | "command": " ".join([os.path.relpath(sys.executable, os.path.expanduser("~")) if sys.executable.startswith(os.path.expanduser("~")) else sys.executable] + sys.argv), |
| 34 | "utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), |
| 35 | "torch": torch.__version__, "numpy": np.__version__, |
| 36 | **payload, |
| 37 | } |
| 38 | path = os.path.join(EVID, name + ".json") |
| 39 | with open(path, "w") as f: |
| 40 | json.dump(body, f, indent=1, default=float) |
| 41 | print("receipt", path) |
| 42 | return path |
| 43 | |
| 44 | |
| 45 | def load_split(split): |
| 46 | with open(os.path.join(SCRATCH, f"gsm8k-{split}.jsonl")) as f: |
| 47 | return [json.loads(l) for l in f] |
| 48 | |
| 49 | |
| 50 | def text_of(ex): |
| 51 | return "Question: " + ex["question"] + "\nAnswer: " + ex["answer"] |
| 52 | |
| 53 | |
| 54 | def load_model(dtype=torch.bfloat16): |
| 55 | from transformers import AutoModelForCausalLM, AutoTokenizer |
| 56 | tok = AutoTokenizer.from_pretrained(MODEL_DIR) |
| 57 | model = AutoModelForCausalLM.from_pretrained(MODEL_DIR, dtype=dtype).to(DEV) |
| 58 | model.eval() |
| 59 | return tok, model |
| 60 | |
| 61 | |
| 62 | def encode(tok, exs, seq=SEQ): |
| 63 | """Token id lists, one per example, truncated to seq.""" |
| 64 | return [tok(text_of(e), add_special_tokens=False)["input_ids"][:seq] for e in exs] |
| 65 | |
| 66 | |
| 67 | def batches(ids, bs): |
| 68 | for i in range(0, len(ids), bs): |
| 69 | chunk = ids[i:i + bs] |
| 70 | L = max(len(c) for c in chunk) |
| 71 | x = torch.full((len(chunk), L), 2, dtype=torch.long) |
| 72 | m = torch.zeros((len(chunk), L), dtype=torch.bool) |
| 73 | for j, c in enumerate(chunk): |
| 74 | x[j, :len(c)] = torch.tensor(c) |
| 75 | m[j, :len(c)] = True |
| 76 | yield x, m |
| 77 | |
| 78 | |
| 79 | @torch.no_grad() |
| 80 | def extract_final(model, ids, cap_tokens, bs=16): |
| 81 | """Final-norm hidden state h_t (fp32) and next token y_t for positions t with a next token, up to cap_tokens.""" |
| 82 | feats, ys, n = [], [], 0 |
| 83 | for x, m in batches(ids, bs): |
| 84 | x, m = x.to(DEV), m.to(DEV) |
| 85 | out = model.model(input_ids=x, attention_mask=m.long()) |
| 86 | h = out.last_hidden_state # after the final RMSNorm |
| 87 | valid = m[:, 1:] & m[:, :-1] |
| 88 | feats.append(h[:, :-1][valid].float().cpu()) |
| 89 | ys.append(x[:, 1:][valid].cpu()) |
| 90 | n += int(valid.sum()) |
| 91 | if n >= cap_tokens: |
| 92 | break |
| 93 | X = torch.cat(feats)[:cap_tokens] |
| 94 | Y = torch.cat(ys)[:cap_tokens] |
| 95 | return X, Y |
| 96 | |
| 97 | |
| 98 | def sha_of_tensor(t): |
| 99 | return hashlib.sha256(t.contiguous().numpy().tobytes()).hexdigest() |