Download code/train.py from jncarlo/tinymix: direct link, hf CLI and curl.
- Browser
- Download file 10.2 kB
-
https://huggingface.co/datasets/jncarlo/tinymix/resolve/main/code/train.py
- Command line
-
hf download hf://datasets/jncarlo/tinymix/code/train.py
-
curl -L -o train.py https://huggingface.co/datasets/jncarlo/tinymix/resolve/main/code/train.py
10.2 kB
| """Tiny GPT (nanoGPT-style) on one dataset size, with its own BPE. | |
| python train.py 1M [--vocab 4096 --layers 6 --heads 6 --dim 192 --epochs 10] | |
| Reports validation loss per genre as bits per byte, which is comparable across | |
| datasets even though each one has its own tokenizer. | |
| """ | |
| import argparse | |
| import json | |
| import math | |
| import shutil | |
| import time | |
| from pathlib import Path | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from tokenizers import Tokenizer, models, pre_tokenizers, decoders, trainers | |
| ROOT = Path(__file__).resolve().parent.parent | |
| EOT = "<|endoftext|>" | |
| def get_tokenizer(data, vocab, path): | |
| if path.exists(): | |
| return Tokenizer.from_file(str(path)) | |
| tok = Tokenizer(models.BPE()) | |
| tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False) | |
| tok.decoder = decoders.ByteLevel() | |
| tr = trainers.BpeTrainer(vocab_size=vocab, special_tokens=[EOT], | |
| initial_alphabet=pre_tokenizers.ByteLevel.alphabet()) | |
| tok.train_from_iterator((d for d in data.split(EOT) if d.strip()), tr) | |
| tok.save(str(path)) | |
| return tok | |
| def encode(tok, text): | |
| eot = tok.token_to_id(EOT) | |
| docs = [d.strip("\n") for d in text.split(EOT) if d.strip()] | |
| ids = [] | |
| for i in range(0, len(docs), 20000): # batched: much faster than one call per document | |
| for e in tok.encode_batch(docs[i:i + 20000]): | |
| ids += e.ids + [eot] | |
| return torch.tensor(ids, dtype=torch.long) | |
| class Block(nn.Module): | |
| def __init__(self, d, h, p=0.0): | |
| super().__init__() | |
| self.h, self.p, self.drop = h, p, nn.Dropout(p) | |
| self.ln1, self.ln2 = nn.LayerNorm(d), nn.LayerNorm(d) | |
| self.qkv, self.proj = nn.Linear(d, 3 * d, bias=False), nn.Linear(d, d, bias=False) | |
| self.fc, self.out = nn.Linear(d, 4 * d, bias=False), nn.Linear(4 * d, d, bias=False) | |
| def forward(self, x): | |
| B, T, C = x.shape | |
| q, k, v = self.qkv(self.ln1(x)).view(B, T, 3, self.h, C // self.h).permute(2, 0, 3, 1, 4) | |
| att = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=self.p if self.training else 0.0) | |
| x = x + self.drop(self.proj(att.transpose(1, 2).reshape(B, T, C))) | |
| return x + self.drop(self.out(F.gelu(self.fc(self.ln2(x))))) | |
| class GPT(nn.Module): | |
| def __init__(self, vocab, block, layers, heads, dim, p=0.0): | |
| super().__init__() | |
| self.block = block | |
| self.tok, self.pos = nn.Embedding(vocab, dim), nn.Embedding(block, dim) | |
| self.drop = nn.Dropout(p) | |
| self.blocks = nn.ModuleList(Block(dim, heads, p) for _ in range(layers)) | |
| self.ln = nn.LayerNorm(dim) | |
| self.head = nn.Linear(dim, vocab, bias=False) | |
| self.head.weight = self.tok.weight # tied embeddings | |
| self.apply(self._init) | |
| def _init(m): | |
| if isinstance(m, (nn.Linear, nn.Embedding)): | |
| nn.init.normal_(m.weight, std=0.02) | |
| def forward(self, idx, targets=None): | |
| x = self.drop(self.tok(idx) + self.pos(torch.arange(idx.size(1), device=idx.device))) | |
| for b in self.blocks: | |
| x = b(x) | |
| logits = self.head(self.ln(x)) | |
| loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.reshape(-1)) if targets is not None else None | |
| return logits, loss | |
| def generate(self, idx, n, temp=0.8, top_k=40, top_p=1.0, rep=1.0, no_repeat=0, stop=None): | |
| """Batch size 1. rep: CTRL-style penalty on the last 128 tokens; no_repeat: ban any token | |
| that would repeat an n-gram already in the text; stop: token id that ends generation.""" | |
| for _ in range(n): | |
| logits, _ = self(idx[:, -self.block:]) | |
| logits = logits[:, -1] / temp | |
| if rep != 1.0: | |
| recent = idx[0, -128:].unique() | |
| l = logits[0, recent] | |
| logits[0, recent] = torch.where(l > 0, l / rep, l * rep) | |
| if no_repeat and idx.size(1) >= no_repeat: | |
| seq, k = idx[0].tolist(), no_repeat - 1 | |
| prefix = tuple(seq[-k:]) | |
| banned = {seq[i + k] for i in range(len(seq) - k) if tuple(seq[i:i + k]) == prefix} | |
| if banned: | |
| logits[0, list(banned)] = -float("inf") | |
| v, _ = torch.topk(logits, top_k) | |
| logits[logits < v[:, [-1]]] = -float("inf") | |
| if top_p < 1.0: | |
| probs, order = F.softmax(logits, -1).sort(descending=True) | |
| drop = probs.cumsum(-1) - probs > top_p # keep tokens until the mass passes top_p | |
| logits[0, order[0][drop[0]]] = -float("inf") | |
| nxt = torch.multinomial(F.softmax(logits, -1), 1) | |
| if stop is not None and nxt.item() == stop: | |
| break | |
| idx = torch.cat([idx, nxt], 1) | |
| return idx | |
| def eval_bpb(model, ids, nbytes, block, dev, amp): | |
| """Bits per byte over an encoded validation file (non-overlapping windows).""" | |
| model.eval() | |
| total, count = 0.0, 0 | |
| for i in range(0, len(ids) - 1, block): | |
| x = ids[i:i + block].to(dev)[None] | |
| y = ids[i + 1:i + block + 1].to(dev)[None] | |
| x = x[:, :y.size(1)] | |
| with torch.autocast("cuda", dtype=torch.bfloat16, enabled=amp): | |
| _, loss = model(x, y) | |
| total += loss.item() * y.numel() | |
| count += y.numel() | |
| model.train() | |
| # summed nats over all tokens, divided by bytes: independent of the tokenizer | |
| return total / math.log(2) / nbytes | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("size") | |
| ap.add_argument("--vocab", type=int, default=4096) | |
| ap.add_argument("--layers", type=int, default=6) | |
| ap.add_argument("--heads", type=int, default=6) | |
| ap.add_argument("--dim", type=int, default=192) | |
| ap.add_argument("--block", type=int, default=256) | |
| ap.add_argument("--batch", type=int, default=64) | |
| ap.add_argument("--epochs", type=float, default=10) | |
| ap.add_argument("--steps", type=int, default=0, help="fixed step count (overrides --epochs); used to match compute across datasets") | |
| ap.add_argument("--dropout", type=float, default=0.0) | |
| ap.add_argument("--eval-every", type=int, default=0, help="print validation bits per byte every N steps") | |
| ap.add_argument("--lr", type=float, default=1e-3) | |
| ap.add_argument("--tag", default="") | |
| ap.add_argument("--seed", type=int, default=0) | |
| ap.add_argument("--tokenizer", default=None, help="reuse this tokenizer.json instead of training one (same vocabulary across mixes)") | |
| ap.add_argument("--compile", action="store_true", help="torch.compile the model (faster on CUDA)") | |
| ap.add_argument("--data", default=None, help="folder with train.txt (default out/<size>)") | |
| ap.add_argument("--valid", default=None, help="folder with valid_*.txt (default: --data); " | |
| "baselines are scored on OUR validation sets") | |
| a = ap.parse_args() | |
| torch.manual_seed(a.seed) | |
| dev = "cuda" if torch.cuda.is_available() else "cpu" | |
| amp = dev == "cuda" and torch.cuda.is_bf16_supported() | |
| data_dir = Path(a.data) if a.data else ROOT / "out" / a.size | |
| run = ROOT / "runs" / f"{a.size}{a.tag}" | |
| run.mkdir(parents=True, exist_ok=True) | |
| train_text = (data_dir / "train.txt").read_text(encoding="utf-8") | |
| if a.tokenizer: | |
| shutil.copy(a.tokenizer, run / "tokenizer.json") | |
| tok = get_tokenizer(train_text, a.vocab, run / "tokenizer.json") | |
| train = encode(tok, train_text) | |
| valid_dir = Path(a.valid) if a.valid else data_dir | |
| valids = {p.stem.replace("valid_", ""): p.read_text(encoding="utf-8") for p in sorted(valid_dir.glob("valid_*.txt"))} | |
| valids = {g: (encode(tok, t), len(t.replace(EOT, "").encode("utf-8"))) for g, t in valids.items()} | |
| model = GPT(tok.get_vocab_size(), a.block, a.layers, a.heads, a.dim, a.dropout).to(dev) | |
| n_params = sum(p.numel() for p in model.parameters()) | |
| steps = a.steps or int(a.epochs * len(train) / (a.batch * a.block)) | |
| print(f"{a.size}: {len(train)/1e6:.2f}M tokens, {n_params/1e6:.2f}M params, {steps} steps, device {dev}, bf16 {amp}", flush=True) | |
| train = train.to(dev) | |
| offs = torch.arange(a.block + 1, device=dev) | |
| fwd = torch.compile(model) if a.compile and dev == "cuda" else model | |
| opt = torch.optim.AdamW(model.parameters(), lr=a.lr, betas=(0.9, 0.95), weight_decay=0.1) | |
| sched = lambda s: a.lr * min(1, (s + 1) / 100) * (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * s / steps))) | |
| t0 = time.time() | |
| for s in range(steps): | |
| for g in opt.param_groups: | |
| g["lr"] = sched(s) | |
| ix = torch.randint(len(train) - a.block - 1, (a.batch,), device=dev) | |
| win = train[ix[:, None] + offs] | |
| x, y = win[:, :-1], win[:, 1:] | |
| with torch.autocast("cuda", dtype=torch.bfloat16, enabled=amp): | |
| _, loss = fwd(x, y) | |
| opt.zero_grad(set_to_none=True) | |
| loss.backward() | |
| torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) | |
| opt.step() | |
| if s % 100 == 0 or s == steps - 1: | |
| print(f"step {s}/{steps} loss {loss.item():.3f} {time.time()-t0:.0f}s", flush=True) | |
| if a.eval_every and s and s % a.eval_every == 0: | |
| bpb = {g: round(eval_bpb(model, ids, nb, a.block, dev, amp), 3) for g, (ids, nb) in valids.items()} | |
| print(f" eval step {s}: {bpb}", flush=True) | |
| res = {"size": a.size, "params_M": round(n_params / 1e6, 2), "tokens_M": round(len(train) / 1e6, 2), | |
| "steps": steps, "seconds": round(time.time() - t0), | |
| "tokens_per_s": round(steps * a.batch * a.block / (time.time() - t0)), | |
| "config": {k: v for k, v in vars(a).items() if k not in ("data", "valid")}, | |
| "valid_bits_per_byte": {g: round(eval_bpb(model, ids, nb, a.block, dev, amp), 4) for g, (ids, nb) in valids.items()}} | |
| prompt = torch.tensor([[tok.token_to_id(EOT)]], device=dev) | |
| res["sample"] = tok.decode(model.generate(prompt, 150)[0].tolist()) | |
| (run / "results.json").write_text(json.dumps(res, indent=1), encoding="utf-8") | |
| torch.save(model.state_dict(), run / "model.pt") | |
| print(json.dumps(res, indent=1)) | |
| if __name__ == "__main__": | |
| main() | |