Download train.py from rororova/poemformer: direct link, hf CLI and curl.
- Browser
- Download file 22.3 kB
-
https://huggingface.co/rororova/poemformer/resolve/main/train.py
- Command line
-
hf download hf://rororova/poemformer/train.py
-
curl -L -o train.py https://huggingface.co/rororova/poemformer/resolve/main/train.py
22.3 kB
| """ | |
| PoemFormer β Kaggle training script | |
| ===================================== | |
| Designed for a single T4 / P100 GPU (16 GB VRAM). | |
| Run on Kaggle | |
| ------------- | |
| 1. Upload poemformer.py, tokenizer.py, train.py as dataset or notebook files. | |
| 2. Enable GPU accelerator (T4 x1). | |
| 3. Enable Internet (needed for HuggingFace dataset download on first run). | |
| 4. !pip install sentencepiece datasets (first cell) | |
| 5. !python train.py | |
| Outputs (written to /kaggle/working/) | |
| -------------------------------------- | |
| poem_tok.model sentencepiece tokenizer | |
| poem_tok.vocab | |
| checkpoints/ | |
| step_{N}.pt model + optimizer state every SAVE_EVERY steps | |
| best.pt lowest val-loss checkpoint | |
| training_log.csv step, train_loss, val_loss, lr | |
| """ | |
| from __future__ import annotations | |
| import csv | |
| import math | |
| import os | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import torch | |
| import torch.nn as nn | |
| from torch.amp import GradScaler, autocast | |
| from torch.utils.data import DataLoader, Dataset, random_split | |
| # βββ Import local modules βββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # When run from Kaggle, add the script's directory to sys.path so the | |
| # sibling modules (poemformer.py, tokenizer.py) are importable. | |
| sys.path.insert(0, str(Path(__file__).parent)) | |
| from poemformer import PoemFormer, PoemFormerConfig, build_rhyme_memory_inputs | |
| from tokenizer import PoemTokenizer | |
| # βββ Hyperparameters ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| CFG = dict( | |
| # Data β list of (hf_dataset_id, column_candidates) tuples; first that | |
| # exists & is non-empty wins per row. Add Kaggle inputs separately if | |
| # internet is off (see _load_local_kaggle below). | |
| # All verified to exist on HuggingFace Hub (downloads > 0, downloadable | |
| # without auth). Order matters β earlier = higher quality, later = bulk. | |
| sources = [ | |
| ("merve/poetry", ["content"]), | |
| ("suayptalha/Poetry-Foundation-Poems", ["Poem", "poem", "content", "text"]), | |
| ("biglam/gutenberg-poetry-corpus", ["line", "text"]), # 3M lines of poetry | |
| ("Dr3dre/Genius-song-lyrics-cleaned", ["lyrics", "text"]), # cleaned ~5M | |
| ("sebastiandizon/genius-song-lyrics", ["lyrics", "text"]), # raw ~5M | |
| ("amishshah/song_lyrics", ["lyrics", "text"]), | |
| ("ThatOneShortGuy/SongLyrics", ["lyrics", "text"]), | |
| ], | |
| # gutenberg-poetry-corpus is line-level β group consecutive lines into poems | |
| group_gutenberg_lines = 32, # β one poem-sized chunk | |
| max_poems = 200_000, # corpus ceiling (β 60β80M tokens) | |
| vocab_size = 16_000, | |
| max_seq_len = 256, # reduce from 512 to fit T4 VRAM | |
| # Model β slightly leaner than the full 100M to fit T4 comfortably in fp16 | |
| d_model = 768, | |
| n_heads = 12, | |
| n_layers = 10, | |
| d_ff = 2048, | |
| dropout = 0.10, | |
| # Training | |
| epochs = 4, # β one Kaggle session at ~80M tokens | |
| batch_size = 8, | |
| grad_accum_steps = 4, # effective batch = 32 | |
| lr = 3e-4, | |
| weight_decay = 0.1, | |
| grad_clip = 1.0, | |
| warmup_steps = 300, | |
| val_split = 0.05, | |
| # I/O | |
| out_dir = "/kaggle/working", | |
| save_every = 500, # save checkpoint every N steps | |
| log_every = 50, | |
| seed = 42, | |
| ) | |
| DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| print(f"Device: {DEVICE}") | |
| # βββ Dataset ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class PoemDataset(Dataset): | |
| """ | |
| Each item is one poem, tokenized to max_seq_len tokens. | |
| Returns (input_ids, line_ids, stanza_ids, line_pos, labels). | |
| Labels = input_ids shifted left by 1 (next-token prediction). | |
| """ | |
| def __init__( | |
| self, | |
| encodings: list, | |
| pad_id: int, | |
| max_len: int, | |
| ): | |
| self.encodings = encodings | |
| self.pad_id = pad_id | |
| self.max_len = max_len | |
| def __len__(self) -> int: | |
| return len(self.encodings) | |
| def __getitem__(self, idx: int): | |
| enc = self.encodings[idx] | |
| T = enc.input_ids.size(0) | |
| def _pad(t: torch.Tensor) -> torch.Tensor: | |
| if T < self.max_len: | |
| pad = torch.full((self.max_len - T,), 0, dtype=t.dtype) | |
| return torch.cat([t, pad]) | |
| return t[: self.max_len] | |
| ids = _pad(enc.input_ids) | |
| li = _pad(enc.line_ids) | |
| si = _pad(enc.stanza_ids) | |
| lp = _pad(enc.line_pos) | |
| # Labels: shift left β next-token prediction | |
| labels = ids.clone() | |
| labels[:-1] = ids[1:] | |
| labels[-1] = -100 | |
| labels[labels == self.pad_id] = -100 # mask positions whose next token is pad | |
| return ids, li, si, lp, labels | |
| # βββ LR schedule β cosine with linear warmup βββββββββββββββββββββββββββββββββ | |
| def get_lr(step: int, total_steps: int, cfg: dict) -> float: | |
| warmup = cfg["warmup_steps"] | |
| if step < warmup: | |
| return cfg["lr"] * step / max(1, warmup) | |
| progress = (step - warmup) / max(1, total_steps - warmup) | |
| progress = min(max(progress, 0.0), 1.0) # clamp β prevents negative LR | |
| min_lr = cfg["lr"] * 0.1 # floor at 10% of peak | |
| return min_lr + (cfg["lr"] - min_lr) * 0.5 * (1.0 + math.cos(math.pi * progress)) | |
| # βββ Multi-source poem loader ββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _load_corpus(cfg: dict) -> list[str]: | |
| """Pull poems + lyrics from every source in cfg['sources']; tolerate failures.""" | |
| from datasets import load_dataset | |
| poems: list[str] = [] | |
| seen: set[int] = set() # rough dedup by hash | |
| cap = cfg["max_poems"] | |
| group_n = cfg["group_gutenberg_lines"] | |
| for name, cols in cfg["sources"]: | |
| if len(poems) >= cap: | |
| break | |
| try: | |
| ds = load_dataset(name, split="train") | |
| count_before = len(poems) | |
| # Special-case the line-level Gutenberg corpus | |
| if "gutenberg-poetry-corpus" in name: | |
| buf: list[str] = [] | |
| for row in ds: | |
| if len(poems) >= cap: | |
| break | |
| line = None | |
| for c in cols: | |
| v = row.get(c) if isinstance(row, dict) else None | |
| if v and isinstance(v, str): | |
| line = v.strip() | |
| break | |
| if not line: | |
| continue | |
| buf.append(line) | |
| if len(buf) >= group_n: | |
| chunk = "\n".join(buf) | |
| h = hash(chunk[:200]) | |
| if h not in seen and len(chunk) > 100: | |
| seen.add(h) | |
| poems.append(chunk) | |
| buf = [] | |
| else: | |
| for row in ds: | |
| if len(poems) >= cap: | |
| break | |
| txt = None | |
| for c in cols: | |
| val = row.get(c) if isinstance(row, dict) else None | |
| if val and isinstance(val, str) and len(val.strip()) > 50: | |
| txt = val.strip() | |
| break | |
| if txt is None: | |
| continue | |
| h = hash(txt[:200]) | |
| if h in seen: | |
| continue | |
| seen.add(h) | |
| poems.append(txt) | |
| print(f" + {name:<42s} added {len(poems)-count_before:>6,} total {len(poems):>7,}") | |
| except Exception as e: | |
| print(f" - {name:<42s} skipped ({type(e).__name__}: {str(e)[:80]})") | |
| if not poems: | |
| print("All sources failed β falling back to toy corpus.") | |
| poems = _toy_poems() | |
| return poems | |
| # βββ Training loop ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def train(): | |
| torch.manual_seed(CFG["seed"]) | |
| out_dir = Path(CFG["out_dir"]) | |
| ckpt_dir = out_dir / "checkpoints" | |
| ckpt_dir.mkdir(parents=True, exist_ok=True) | |
| # ββ 1. Load data ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print("Loading datasetsβ¦") | |
| poems = _load_corpus(CFG) | |
| print(f" {len(poems):,} poems/lyrics loaded total.") | |
| # ββ 2. Train tokenizer ββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| tok_model = str(out_dir / "poem_tok") | |
| tok = PoemTokenizer() | |
| if Path(tok_model + ".model").exists(): | |
| print("Tokenizer found β loading.") | |
| tok.load(tok_model + ".model") | |
| else: | |
| print(f"Training tokenizer (vocab={CFG['vocab_size']})β¦") | |
| tok.train(poems, vocab_size=CFG["vocab_size"], model_prefix=tok_model) | |
| print(f" Vocab size: {tok.vocab_size}") | |
| # ββ 3. Encode all poems βββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print("Encoding poemsβ¦") | |
| encodings = [] | |
| for poem in poems: | |
| enc = tok.encode(poem, max_length=CFG["max_seq_len"]) | |
| if enc.input_ids.size(0) >= 8: # skip micro-fragments | |
| encodings.append(enc) | |
| print(f" {len(encodings):,} usable encodings.") | |
| # ββ 4. Train / val split ββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| n_val = max(1, int(len(encodings) * CFG["val_split"])) | |
| n_train = len(encodings) - n_val | |
| train_enc, val_enc = random_split(encodings, [n_train, n_val], | |
| generator=torch.Generator().manual_seed(CFG["seed"])) | |
| train_ds = PoemDataset(list(train_enc), tok.pad_id, CFG["max_seq_len"]) | |
| val_ds = PoemDataset(list(val_enc), tok.pad_id, CFG["max_seq_len"]) | |
| train_dl = DataLoader(train_ds, batch_size=CFG["batch_size"], shuffle=True, | |
| num_workers=2, pin_memory=True) | |
| val_dl = DataLoader(val_ds, batch_size=CFG["batch_size"], shuffle=False, | |
| num_workers=2, pin_memory=True) | |
| print(f" Train: {len(train_ds):,} Val: {len(val_ds):,}") | |
| # ββ 5. Build model ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| model_cfg = PoemFormerConfig( | |
| vocab_size = tok.vocab_size, | |
| d_model = CFG["d_model"], | |
| n_heads = CFG["n_heads"], | |
| n_layers = CFG["n_layers"], | |
| d_ff = CFG["d_ff"], | |
| max_seq_len = CFG["max_seq_len"], | |
| dropout = CFG["dropout"], | |
| ) | |
| model = PoemFormer(model_cfg).to(DEVICE) | |
| n_params = sum(p.numel() for p in model.parameters()) / 1e6 | |
| print(f"Model: {n_params:.1f}M parameters") | |
| # ββ 6. Optimizer + scaler βββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Weight decay on weight matrices only β not biases or layernorm | |
| decay_params = [p for n, p in model.named_parameters() | |
| if p.dim() >= 2 and p.requires_grad] | |
| no_decay_params = [p for n, p in model.named_parameters() | |
| if p.dim() < 2 and p.requires_grad] | |
| optimizer = torch.optim.AdamW([ | |
| {"params": decay_params, "weight_decay": CFG["weight_decay"]}, | |
| {"params": no_decay_params, "weight_decay": 0.0}, | |
| ], lr=CFG["lr"], betas=(0.9, 0.95), eps=1e-8) | |
| use_amp = DEVICE.type == "cuda" | |
| scaler = GradScaler("cuda", enabled=use_amp) | |
| # ββ 7. Training βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| total_steps = (len(train_dl) // CFG["grad_accum_steps"]) * CFG["epochs"] | |
| print(f"\nTraining for {CFG['epochs']} epochs / {total_steps:,} optimizer steps\n") | |
| log_path = out_dir / "training_log.csv" | |
| with open(log_path, "w", newline="") as f: | |
| csv.writer(f).writerow(["step", "train_loss", "val_loss", "lr"]) | |
| global_step = 0 | |
| start_epoch = 1 | |
| best_val_loss = float("inf") | |
| log_loss_sum = 0.0 | |
| log_loss_count = 0 | |
| optimizer.zero_grad() | |
| # ββ Auto-resume βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # If a previous Kaggle session left a checkpoint behind (passed in as | |
| # /kaggle/input/<dataset>/last.pt or already in /kaggle/working), pick up. | |
| resume_paths = [ | |
| Path("/kaggle/input/poemformer-ckpt/last.pt"), | |
| ckpt_dir / "last.pt", | |
| ] | |
| for rp in resume_paths: | |
| if rp.exists(): | |
| print(f"Resuming from {rp}") | |
| ck = torch.load(rp, map_location=DEVICE) | |
| model.load_state_dict(ck["model"]) | |
| optimizer.load_state_dict(ck["optimizer"]) | |
| global_step = ck.get("step", 0) | |
| start_epoch = ck.get("epoch", 0) + 1 | |
| best_val_loss = ck.get("best_val_loss", float("inf")) | |
| print(f" step={global_step} epoch_start={start_epoch} best_val={best_val_loss:.4f}") | |
| break | |
| newline_id = tok.newline_id | |
| rhyme_mem_size = model.cfg.rhyme_memory_size | |
| for epoch in range(start_epoch, CFG["epochs"] + 1): | |
| model.train() | |
| epoch_loss = 0.0 | |
| t0 = time.time() | |
| for micro_step, batch in enumerate(train_dl): | |
| ids, li, si, lp, labels = [b.to(DEVICE) for b in batch] | |
| # Build causal rhyme memory inputs from this batch | |
| rhyme_mem, rhyme_mask = build_rhyme_memory_inputs( | |
| ids, newline_id, rhyme_mem_size, model.embed.token_emb, | |
| ) | |
| with autocast("cuda", enabled=use_amp): | |
| _, loss = model(ids, li, si, lp, | |
| rhyme_memory=rhyme_mem, | |
| rhyme_mask=rhyme_mask, | |
| labels=labels) | |
| loss = loss / CFG["grad_accum_steps"] | |
| scaler.scale(loss).backward() | |
| unscaled = loss.item() * CFG["grad_accum_steps"] | |
| log_loss_sum += unscaled | |
| log_loss_count += 1 | |
| epoch_loss += unscaled | |
| # Optimizer step every grad_accum_steps micro-batches | |
| if (micro_step + 1) % CFG["grad_accum_steps"] == 0: | |
| global_step += 1 | |
| current_lr = get_lr(global_step, total_steps, CFG) | |
| for g in optimizer.param_groups: | |
| g["lr"] = current_lr | |
| scaler.unscale_(optimizer) | |
| nn.utils.clip_grad_norm_(model.parameters(), CFG["grad_clip"]) | |
| scaler.step(optimizer) | |
| scaler.update() | |
| optimizer.zero_grad() | |
| if global_step % CFG["log_every"] == 0: | |
| elapsed = time.time() - t0 | |
| avg = log_loss_sum / max(1, log_loss_count) | |
| print(f" epoch {epoch:>3} step {global_step:>6} " | |
| f"loss {avg:.4f} " | |
| f"lr {current_lr:.2e} " | |
| f"{elapsed:.0f}s") | |
| log_loss_sum = 0.0 | |
| log_loss_count = 0 | |
| t0 = time.time() | |
| # Rolling mid-epoch checkpoint β overwrites previous so disk | |
| # stays bounded and a session timeout never loses more than | |
| # `save_every` steps of progress. | |
| if global_step % CFG["save_every"] == 0: | |
| _save_checkpoint(model, optimizer, global_step, ckpt_dir, | |
| name="last.pt", epoch=epoch - 1, | |
| best_val_loss=best_val_loss) | |
| _save_weights(model, ckpt_dir, name="weights.pt") | |
| # ββ Val loss ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| val_loss = _evaluate(model, val_dl, use_amp, newline_id, rhyme_mem_size) | |
| avg_train = epoch_loss / max(1, len(train_dl)) | |
| current_lr = get_lr(global_step, total_steps, CFG) | |
| print(f"\nEpoch {epoch:>3}/{CFG['epochs']} " | |
| f"train_loss={avg_train:.4f} val_loss={val_loss:.4f} " | |
| f"lr={current_lr:.2e}\n") | |
| with open(log_path, "a", newline="") as f: | |
| csv.writer(f).writerow([global_step, f"{avg_train:.4f}", | |
| f"{val_loss:.4f}", f"{current_lr:.2e}"]) | |
| if val_loss < best_val_loss: | |
| best_val_loss = val_loss | |
| _save_checkpoint(model, optimizer, global_step, ckpt_dir, | |
| name="best.pt", epoch=epoch, best_val_loss=best_val_loss) | |
| _save_weights(model, ckpt_dir, name="weights_best.pt") | |
| print(f" β New best val_loss={best_val_loss:.4f} β saved best.pt + weights_best.pt") | |
| # End-of-epoch resumable checkpoint + slim weights export | |
| _save_checkpoint(model, optimizer, global_step, ckpt_dir, | |
| name="last.pt", epoch=epoch, best_val_loss=best_val_loss) | |
| _save_weights(model, ckpt_dir, name="weights.pt") | |
| print(f"\nTraining complete. Best val_loss: {best_val_loss:.4f}") | |
| print(f"Checkpoints in: {ckpt_dir}") | |
| # βββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _evaluate(model: nn.Module, dl: DataLoader, use_amp: bool, | |
| newline_id: int, rhyme_mem_size: int) -> float: | |
| model.eval() | |
| total_loss = 0.0 | |
| for batch in dl: | |
| ids, li, si, lp, labels = [b.to(DEVICE) for b in batch] | |
| rhyme_mem, rhyme_mask = build_rhyme_memory_inputs( | |
| ids, newline_id, rhyme_mem_size, model.embed.token_emb, | |
| ) | |
| with autocast("cuda", enabled=use_amp): | |
| _, loss = model(ids, li, si, lp, | |
| rhyme_memory=rhyme_mem, | |
| rhyme_mask=rhyme_mask, | |
| labels=labels) | |
| total_loss += loss.item() | |
| model.train() | |
| return total_loss / max(1, len(dl)) | |
| def _save_checkpoint(model, optimizer, step, ckpt_dir, name, | |
| epoch: int = 0, best_val_loss: float = float("inf")): | |
| path = ckpt_dir / name | |
| torch.save({ | |
| "step": step, | |
| "epoch": epoch, | |
| "best_val_loss": best_val_loss, | |
| "model": model.state_dict(), | |
| "optimizer": optimizer.state_dict(), | |
| "config": CFG, | |
| }, path) | |
| print(f" Saved {path}") | |
| def _save_weights(model, ckpt_dir, name: str): | |
| """ | |
| Slim export: just the model weights (no optimizer, no scaler, no LR state). | |
| Use this for inference / sharing β about 1/3 the size of a full checkpoint. | |
| """ | |
| path = ckpt_dir / name | |
| torch.save(model.state_dict(), path) | |
| # Drop a sibling JSON describing the architecture so a loader can rebuild | |
| # the model without train.py present. | |
| cfg_path = ckpt_dir / "model_config.json" | |
| if not cfg_path.exists(): | |
| import json | |
| with open(cfg_path, "w") as f: | |
| json.dump({ | |
| "vocab_size": model.cfg.vocab_size, | |
| "d_model": model.cfg.d_model, | |
| "n_heads": model.cfg.n_heads, | |
| "n_layers": model.cfg.n_layers, | |
| "d_ff": model.cfg.d_ff, | |
| "max_seq_len": model.cfg.max_seq_len, | |
| "max_lines": model.cfg.max_lines, | |
| "max_stanzas": model.cfg.max_stanzas, | |
| "rhyme_memory_size": model.cfg.rhyme_memory_size, | |
| "max_line_len": model.cfg.max_line_len, | |
| "dropout": model.cfg.dropout, | |
| "rope_base": model.cfg.rope_base, | |
| }, f, indent=2) | |
| def _toy_poems() -> list[str]: | |
| """Tiny fallback corpus so the script runs even without internet.""" | |
| return [ | |
| "Shall I compare thee to a summer's day?\nThou art more lovely and more temperate.", | |
| "Two roads diverged in a yellow wood,\nAnd sorry I could not travel both.", | |
| "Hope is the thing with feathers\nThat perches in the soul.", | |
| "Because I could not stop for Death,\nHe kindly stopped for me.", | |
| "I wandered lonely as a cloud\nThat floats on high o'er vales and hills.", | |
| ] * 200 # repeat to have enough data for tokenizer training | |
| # βββ Entry point ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| if __name__ == "__main__": | |
| train() | |