Download code/zenith/train/sft.py from Kolgrim/farzenith-small-v1: direct link, hf CLI and curl.
- Browser
- Download file 6.42 kB
-
https://huggingface.co/Kolgrim/farzenith-small-v1/resolve/main/code/zenith/train/sft.py
- Command line
-
hf download hf://Kolgrim/farzenith-small-v1/code/zenith/train/sft.py
-
curl -L -o sft.py https://huggingface.co/Kolgrim/farzenith-small-v1/resolve/main/code/zenith/train/sft.py
6.42 kB
| """Supervised fine-tuning on generated examples; loss only on spec and answer spans. | |
| Usage: python -m zenith.train.sft --config configs/small.yaml --init runs/small/best.pt \ | |
| --data data/sft/train.jsonl --out runs/small-sft | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import contextlib | |
| import json | |
| import random | |
| import time | |
| from pathlib import Path | |
| import torch | |
| from zenith.config import RunConfig, load_run_config | |
| from zenith.format import encode_turns | |
| from zenith.model.model import ZenithLM | |
| from zenith.sft.generate import Example | |
| from zenith.tokenizer.bpe import BPETokenizer | |
| from zenith.train.checkpoint import checkpoint_path, latest_checkpoint, load_checkpoint, prune_checkpoints, save_checkpoint | |
| from zenith.train.pretrain import _optimizer | |
| from zenith.train.schedule import lr_at | |
| DEFAULT_TOKENIZER = Path("zenith/tokenizer/zenith-16k.json") | |
| def collate(examples: list[tuple[list[int], list[int]]], pad_id: int) -> tuple[torch.Tensor, torch.Tensor]: | |
| width = max(len(ids) for ids, _ in examples) | |
| x = torch.full((len(examples), width), pad_id, dtype=torch.long) | |
| y = torch.full((len(examples), width), -100, dtype=torch.long) | |
| for i, (ids, targets) in enumerate(examples): | |
| x[i, : len(ids)] = torch.tensor(ids) | |
| y[i, : len(targets)] = torch.tensor(targets) | |
| return x, y | |
| def load_examples(path: Path, tok: BPETokenizer, context_len: int) -> tuple[list[tuple[list[int], list[int]]], int]: | |
| """Encoded (ids, targets) for every example that fits `context_len`, and how many did not.""" | |
| examples, skipped = [], 0 | |
| with open(path) as f: | |
| for line in f: | |
| if not line.strip(): | |
| continue | |
| ids, targets = encode_turns(tok, Example.from_json(line).turns) | |
| if len(ids) > context_len: | |
| skipped += 1 | |
| else: | |
| examples.append((ids, targets)) | |
| if not examples: | |
| raise ValueError("no training example fits the model context") | |
| return examples, skipped | |
| def _order(n: int, seed: int, epoch: int) -> list[int]: | |
| order = list(range(n)) | |
| random.Random(f"{seed}:{epoch}").shuffle(order) | |
| return order | |
| def sft(cfg: RunConfig, init_ckpt: Path, train_path: Path, out_dir: Path, epochs: int = 2, lr: float = 1e-4, | |
| batch_size: int = 16, tok: BPETokenizer | None = None, device: str = "auto", seed: int = 0, | |
| time_limit_s: float | None = None, max_steps: int | None = None, log_every: int = 20, | |
| checkpoint_every: int = 500) -> Path: | |
| """Train, resuming from the latest checkpoint in `out_dir`; returns the last checkpoint written.""" | |
| out_dir = Path(out_dir) | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| tok = tok or BPETokenizer.load(DEFAULT_TOKENIZER) | |
| if device == "auto": | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| use_fp16 = cfg.train.precision == "fp16" and device == "cuda" | |
| started = time.monotonic() | |
| examples, too_long = load_examples(train_path, tok, cfg.model.context_len) | |
| steps_per_epoch = (len(examples) + batch_size - 1) // batch_size | |
| total = steps_per_epoch * epochs | |
| warmup = max(1, int(0.03 * total)) | |
| pad = tok.special_ids["<|pad|>"] | |
| model = ZenithLM(cfg.model) | |
| optimizer = _optimizer(model, cfg) | |
| scaler = torch.amp.GradScaler("cuda", enabled=use_fp16) | |
| resume = latest_checkpoint(out_dir) | |
| if resume is not None: | |
| step = load_checkpoint(resume, model, optimizer, scaler)["step"] | |
| else: | |
| load_checkpoint(init_ckpt, model) | |
| step = 0 | |
| model.to(device).train() | |
| def checkpoint() -> Path: | |
| path = checkpoint_path(out_dir, step) | |
| save_checkpoint(path, model, optimizer, scaler, step, | |
| {"init": str(init_ckpt), "examples": len(examples), "total_steps": total}) | |
| prune_checkpoints(out_dir, keep_last=2) | |
| return path | |
| with open(out_dir / "sft_log.jsonl", "a") as log: | |
| while step < total: | |
| if (max_steps is not None and step >= max_steps) or ( | |
| time_limit_s is not None and time.monotonic() - started > time_limit_s): | |
| return checkpoint() | |
| epoch, b = divmod(step, steps_per_epoch) | |
| order = _order(len(examples), seed, epoch) | |
| x, y = collate([examples[i] for i in order[b * batch_size : (b + 1) * batch_size]], pad) | |
| for group in optimizer.param_groups: | |
| group["lr"] = lr_at(step, lr, warmup, total) | |
| ctx = torch.autocast("cuda", dtype=torch.float16) if use_fp16 else contextlib.nullcontext() | |
| with ctx: | |
| _, loss = model(x.to(device), y.to(device)) | |
| scaler.scale(loss).backward() | |
| scaler.unscale_(optimizer) | |
| torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.train.grad_clip) | |
| scaler.step(optimizer) | |
| scaler.update() | |
| optimizer.zero_grad(set_to_none=True) | |
| if step % log_every == 0 or step == total - 1: | |
| log.write(json.dumps({"step": step, "epoch": epoch, "loss": loss.item(), | |
| "skipped_too_long": too_long}) + "\n") | |
| log.flush() | |
| step += 1 | |
| if step % checkpoint_every == 0 and step < total: | |
| checkpoint() | |
| return checkpoint() | |
| def main(argv=None) -> None: | |
| ap = argparse.ArgumentParser(prog="python -m zenith.train.sft") | |
| ap.add_argument("--config", required=True, type=Path) | |
| ap.add_argument("--init", required=True, type=Path) | |
| ap.add_argument("--data", required=True, type=Path) | |
| ap.add_argument("--out", required=True, type=Path) | |
| ap.add_argument("--epochs", type=int, default=2) | |
| ap.add_argument("--lr", type=float, default=1e-4) | |
| ap.add_argument("--batch-size", type=int, default=16) | |
| ap.add_argument("--seed", type=int, default=0) | |
| ap.add_argument("--max-steps", type=int) | |
| ap.add_argument("--time-limit", type=float, help="seconds") | |
| ap.add_argument("--tokenizer", type=Path, default=DEFAULT_TOKENIZER) | |
| args = ap.parse_args(argv) | |
| final = sft(load_run_config(args.config), args.init, args.data, args.out, args.epochs, args.lr, args.batch_size, | |
| tok=BPETokenizer.load(args.tokenizer), seed=args.seed, time_limit_s=args.time_limit, | |
| max_steps=args.max_steps) | |
| print(f"wrote {final}") | |
| if __name__ == "__main__": | |
| main() | |