Download code/train/small_sft.py from KeremTT/OPUS-5.5-DATABASE: direct link, hf CLI and curl.
- Browser
- Download file 4.25 kB
-
https://huggingface.co/datasets/KeremTT/OPUS-5.5-DATABASE/resolve/main/code/train/small_sft.py
- Command line
-
hf download hf://datasets/KeremTT/OPUS-5.5-DATABASE/code/train/small_sft.py
-
curl -L -o small_sft.py https://huggingface.co/datasets/KeremTT/OPUS-5.5-DATABASE/resolve/main/code/train/small_sft.py
4.25 kB
| """Minimal dependency-light SFT loop (transformers + torch only) used for the measured | |
| small-model experiment in the dataset card. Loss is computed on assistant tokens only. | |
| python train/small_sft.py --model HuggingFaceTB/SmolLM2-135M-Instruct \ | |
| --data "out/data/sft/train-*.parquet" --examples 6000 --out runs/smollm2-135m-opus | |
| Works on CPU (slow) or a single GPU. For real training runs use train/sft_trl.py. | |
| """ | |
| import argparse | |
| import glob | |
| import math | |
| import random | |
| import time | |
| import pyarrow.parquet as pq | |
| import torch | |
| def load_examples(pattern, n, seed, sources, max_tokens_field=768): | |
| rows = [] | |
| for f in sorted(glob.glob(pattern)): | |
| t = pq.read_table(f, columns=["messages", "source", "num_tokens"]).to_pylist() | |
| rows.extend(r for r in t if (not sources or r["source"] in sources) and r["num_tokens"] <= max_tokens_field) | |
| random.Random(seed).shuffle(rows) | |
| return rows[:n] | |
| def encode(tok, messages, max_len): | |
| """Token ids + labels where only assistant turns are supervised.""" | |
| ids, labels = [], [] | |
| for i, m in enumerate(messages): | |
| prefix = tok.apply_chat_template(messages[:i], tokenize=False) if i else "" | |
| full = tok.apply_chat_template(messages[:i + 1], tokenize=False) | |
| piece = tok(full[len(prefix):], add_special_tokens=False)["input_ids"] | |
| ids.extend(piece) | |
| labels.extend(piece if m["role"] == "assistant" else [-100] * len(piece)) | |
| return ids[:max_len], labels[:max_len] | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--model", required=True) | |
| ap.add_argument("--data", required=True) | |
| ap.add_argument("--out", required=True) | |
| ap.add_argument("--examples", type=int, default=6000) | |
| ap.add_argument("--sources", default="") | |
| ap.add_argument("--epochs", type=int, default=1) | |
| ap.add_argument("--lr", type=float, default=5e-5) | |
| ap.add_argument("--batch", type=int, default=8) | |
| ap.add_argument("--max-len", type=int, default=768) | |
| ap.add_argument("--minutes", type=float, default=0, help="optional wall-clock cap") | |
| a = ap.parse_args() | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| torch.manual_seed(0) | |
| dev = "cuda" if torch.cuda.is_available() else "cpu" | |
| tok = AutoTokenizer.from_pretrained(a.model) | |
| model = AutoModelForCausalLM.from_pretrained(a.model, torch_dtype=torch.float32).to(dev) | |
| model.train() | |
| srcs = set(a.sources.split(",")) if a.sources else None | |
| rows = load_examples(a.data, a.examples, 0, srcs, a.max_len) | |
| data = [encode(tok, r["messages"], a.max_len) for r in rows] | |
| data.sort(key=lambda x: len(x[0])) # length-bucketed batches -> little padding | |
| batches = [data[i:i + a.batch] for i in range(0, len(data), a.batch)] | |
| steps = len(batches) * a.epochs | |
| opt = torch.optim.AdamW(model.parameters(), lr=a.lr, weight_decay=0.0) | |
| sched = torch.optim.lr_scheduler.LambdaLR( | |
| opt, lambda s: min(1, (s + 1) / max(1, steps // 20)) * 0.5 * (1 + math.cos(math.pi * s / steps))) | |
| pad = tok.pad_token_id if tok.pad_token_id is not None else tok.eos_token_id | |
| t0, step = time.time(), 0 | |
| for ep in range(a.epochs): | |
| random.Random(ep).shuffle(batches) | |
| for b in batches: | |
| L = max(len(x[0]) for x in b) | |
| ids = torch.tensor([x[0] + [pad] * (L - len(x[0])) for x in b], device=dev) | |
| lab = torch.tensor([x[1] + [-100] * (L - len(x[1])) for x in b], device=dev) | |
| att = torch.tensor([[1] * len(x[0]) + [0] * (L - len(x[0])) for x in b], device=dev) | |
| loss = model(input_ids=ids, attention_mask=att, labels=lab).loss | |
| loss.backward() | |
| torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) | |
| opt.step() | |
| sched.step() | |
| opt.zero_grad(set_to_none=True) | |
| step += 1 | |
| if step % 20 == 0: | |
| print(f"step {step}/{steps} loss {loss.item():.4f} {time.time() - t0:.0f}s", flush=True) | |
| if a.minutes and time.time() - t0 > a.minutes * 60: | |
| break | |
| model.save_pretrained(a.out) | |
| tok.save_pretrained(a.out) | |
| print(f"saved {a.out}: {len(data)} examples, {step} steps, {time.time() - t0:.0f}s") | |
| if __name__ == "__main__": | |
| main() | |