import argparse import json import math import random from dataclasses import asdict from pathlib import Path from typing import Dict, List, Tuple import torch from torch.utils.data import DataLoader, Dataset from tiny_model_core import TinyCausalLM, TinyConfig, WordTokenizer from tiny_model_data import build_curriculum_files, build_dataset_file from tiny_model_eval import evaluate_benchmarks class InstructionDataset(Dataset): def __init__(self, rows: List[dict], tokenizer: WordTokenizer, block_size: int): self.rows = rows self.tokenizer = tokenizer self.block_size = block_size def __len__(self): return len(self.rows) def __getitem__(self, idx): row = self.rows[idx] instruction = row["instruction"].strip() response = row["response"].strip() prompt_text = f"User: {instruction}\nAssistant:" prompt_ids = self.tokenizer.encode(prompt_text, add_bos=True, add_eos=False) response_ids = self.tokenizer.encode(" " + response, add_bos=False, add_eos=True) full = prompt_ids + response_ids if len(full) < 2: full = [self.tokenizer.bos_id, self.tokenizer.eos_id] x = full[:-1][: self.block_size] y = full[1:][: self.block_size] # Ignore user instruction tokens in loss. prompt_target_len = max(0, len(prompt_ids) - 1) for i in range(min(prompt_target_len, len(y))): y[i] = -100 pad_len = self.block_size - len(x) if pad_len > 0: x = x + [self.tokenizer.pad_id] * pad_len y = y + [-100] * pad_len return torch.tensor(x, dtype=torch.long), torch.tensor(y, dtype=torch.long) def read_jsonl(path: str) -> List[dict]: rows = [] with open(path, "r", encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue rows.append(json.loads(line)) return rows def split_rows(rows: List[dict], val_ratio: float = 0.1, seed: int = 42) -> Tuple[List[dict], List[dict]]: rng = random.Random(seed) rows = rows[:] rng.shuffle(rows) n_val = max(1, int(len(rows) * val_ratio)) return rows[n_val:], rows[:n_val] @torch.no_grad() def evaluate_loss(model, loader, device): model.eval() losses = [] for x, y in loader: x, y = x.to(device), y.to(device) _, loss = model(x, y) losses.append(loss.item()) model.train() return sum(losses) / max(1, len(losses)) def build_tokenizer(rows: List[dict], vocab_size: int, min_freq: int) -> WordTokenizer: texts = [] for row in rows: instruction = row["instruction"].strip() response = row["response"].strip() texts.append(f"User: {instruction}") texts.append(f"Assistant: {response}") tokenizer = WordTokenizer() tokenizer.fit(texts, vocab_size=vocab_size, min_freq=min_freq) return tokenizer def save_checkpoint( save_path: Path, model: TinyCausalLM, config: TinyConfig, tokenizer: WordTokenizer, args, metrics: Dict, optimizer: torch.optim.Optimizer | None = None, best_metrics: Dict | None = None, ): save_path.parent.mkdir(parents=True, exist_ok=True) payload = { "model_state_dict": model.state_dict(), "config": asdict(config), "tokenizer_state": tokenizer.to_state(), "metrics": metrics, "train_args": vars(args), } if optimizer is not None: payload["optimizer_state_dict"] = optimizer.state_dict() if best_metrics is not None: payload["best_metrics"] = best_metrics torch.save(payload, save_path) def should_update_best( current: Dict, best: Dict, min_val_delta: float, min_benchmark_delta: float, checkpoint_gate: str, ) -> bool: current_val = float(current.get("val_loss", float("inf"))) best_val = float(best.get("val_loss", float("inf"))) current_benchmark = float(current.get("benchmark_weighted_total", current.get("benchmark_total", -1.0))) best_benchmark = float(best.get("benchmark_weighted_total", best.get("benchmark_total", -1.0))) current_prof = float(current.get("professionalism", -1.0)) best_prof = float(best.get("professionalism", -1.0)) benchmark_available = current_benchmark >= 0 and best_benchmark >= 0 if checkpoint_gate == "benchmark_only" and benchmark_available: if current_benchmark > best_benchmark + min_benchmark_delta: return True if abs(current_benchmark - best_benchmark) <= min_benchmark_delta: if current_val < best_val - min_val_delta: return True if abs(current_val - best_val) <= min_val_delta: return current_prof > best_prof return False if checkpoint_gate == "benchmark_then_loss" and benchmark_available: if current_benchmark > best_benchmark + min_benchmark_delta: return True if abs(current_benchmark - best_benchmark) <= min_benchmark_delta: if current_val < best_val - min_val_delta: return True if abs(current_val - best_val) <= min_val_delta: return current_prof > best_prof return False if current_val < best_val - min_val_delta: return True if abs(current_val - best_val) <= min_val_delta: if benchmark_available and current_benchmark > best_benchmark + min_benchmark_delta: return True if benchmark_available and abs(current_benchmark - best_benchmark) <= min_benchmark_delta: return current_prof > best_prof return current_prof > best_prof return False def prepare_datasets(args) -> Tuple[List[dict], List[dict]]: dataset_path = Path(args.dataset_path) stage1_path = Path(args.stage1_dataset_path) if args.curriculum: need_build = args.rebuild_dataset or not dataset_path.exists() or not stage1_path.exists() if need_build: stats = build_curriculum_files( stage1_path=str(stage1_path), stage2_path=str(dataset_path), training_path=args.training_path, kb_path=args.kb_path, max_kb_samples_stage1=args.max_kb_samples_stage1, max_kb_samples_stage2=args.max_kb_samples_stage2, seed=args.seed, ) print("curriculum_dataset_stats", stats) stage1_rows = read_jsonl(str(stage1_path)) full_rows = read_jsonl(str(dataset_path)) return stage1_rows, full_rows if args.rebuild_dataset or not dataset_path.exists(): stats = build_dataset_file( out_path=str(dataset_path), training_path=args.training_path, kb_path=args.kb_path, max_kb_samples=args.max_kb_samples, seed=args.seed, ) print("dataset_stats", stats) full_rows = read_jsonl(str(dataset_path)) return [], full_rows def stage_epoch_plan(total_epochs: int, stage1_ratio: float, use_curriculum: bool) -> List[Tuple[str, int]]: if not use_curriculum: return [("stage2", total_epochs)] if total_epochs <= 1: return [("stage2", total_epochs)] stage1_epochs = max(1, int(round(total_epochs * stage1_ratio))) stage1_epochs = min(stage1_epochs, total_epochs - 1) stage2_epochs = total_epochs - stage1_epochs return [("stage1", stage1_epochs), ("stage2", stage2_epochs)] def remaining_stage_plan(plan: List[Tuple[str, int]], completed_epochs: int) -> List[Tuple[str, int]]: remaining: List[Tuple[str, int]] = [] skip = max(0, int(completed_epochs)) for stage_name, stage_epochs in plan: if skip >= stage_epochs: skip -= stage_epochs continue if skip > 0: stage_epochs -= skip skip = 0 if stage_epochs > 0: remaining.append((stage_name, stage_epochs)) return remaining def train(args): stage1_rows, full_rows = prepare_datasets(args) if len(full_rows) < 20: raise RuntimeError("Dataset is too small. Need at least 20 rows.") train_full, val_full = split_rows(full_rows, val_ratio=args.val_ratio, seed=args.seed) resume_payload = None resume_config = None block_size = args.block_size tokenizer: WordTokenizer if args.resume_from: resume_path = Path(args.resume_from) if not resume_path.exists(): raise FileNotFoundError(f"Resume checkpoint not found: {resume_path}") resume_payload = torch.load(resume_path, map_location=torch.device("cpu")) tokenizer_state = resume_payload.get("tokenizer_state") config_state = resume_payload.get("config") if not tokenizer_state or not config_state or "model_state_dict" not in resume_payload: raise RuntimeError("Resume checkpoint is missing tokenizer/config/model_state_dict.") tokenizer = WordTokenizer.from_state(tokenizer_state) resume_config = TinyConfig(**config_state) block_size = int(resume_config.block_size) resume_metrics = resume_payload.get("metrics", {}) or {} print( f"resume_from={resume_path} " f"resume_epoch={int(resume_metrics.get('epoch', 0) or 0)} " f"resume_step={int(resume_metrics.get('step', 0) or 0)}" ) if block_size != args.block_size: print(f"resume_block_size_override from={args.block_size} to={block_size}") else: tokenizer = build_tokenizer(train_full, vocab_size=args.vocab_size, min_freq=args.min_freq) print("tokenizer_vocab_size", tokenizer.vocab_size) train_full_ds = InstructionDataset(train_full, tokenizer, block_size) val_ds = InstructionDataset(val_full, tokenizer, block_size) train_full_loader = DataLoader(train_full_ds, batch_size=args.batch_size, shuffle=True) val_loader = DataLoader(val_ds, batch_size=args.batch_size, shuffle=False) stage1_loader = None if args.curriculum and stage1_rows: stage1_train, _ = split_rows(stage1_rows, val_ratio=min(args.val_ratio, 0.1), seed=args.seed + 11) if len(stage1_train) >= 10: stage1_ds = InstructionDataset(stage1_train, tokenizer, block_size) stage1_loader = DataLoader(stage1_ds, batch_size=args.batch_size, shuffle=True) print("stage1_train_samples", len(stage1_train)) else: print("stage1_dataset_too_small_fallback_to_stage2_only") config = resume_config or TinyConfig( vocab_size=tokenizer.vocab_size, block_size=block_size, n_layer=args.n_layer, n_head=args.n_head, n_embd=args.n_embd, dropout=args.dropout, ) device = torch.device("cpu") model = TinyCausalLM(config).to(device) if resume_payload is not None: model.load_state_dict(resume_payload["model_state_dict"]) optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=0.01) if resume_payload is not None and args.resume_optimizer: optimizer_state = resume_payload.get("optimizer_state_dict") if optimizer_state: optimizer.load_state_dict(optimizer_state) print("resume_optimizer_state=loaded") else: print("resume_optimizer_state=missing_in_checkpoint") checkpoint_dir = Path(args.checkpoint_dir) if args.save_all_checkpoints: checkpoint_dir.mkdir(parents=True, exist_ok=True) best_metrics = { "epoch": 0, "stage": "", "val_loss": float("inf"), "benchmark_total": -1.0, "benchmark_weighted_total": -1.0, "professionalism": -1.0, } history_path = Path(args.history_path) history = { "epochs": [], "best": None, } if args.resume_from and history_path.exists(): try: with open(history_path, "r", encoding="utf-8") as f: loaded_history = json.load(f) if isinstance(loaded_history, dict): epochs = loaded_history.get("epochs", []) if isinstance(epochs, list): history["epochs"] = epochs print("resume_history_epochs", len(epochs)) except Exception as exc: print(f"resume_history_load_warning={exc}") global_step = 0 global_epoch = 0 if resume_payload is not None: resume_best = resume_payload.get("best_metrics") best_from_payload = False if isinstance(resume_best, dict): candidate_val_loss = float(resume_best.get("val_loss", float("inf"))) if math.isfinite(candidate_val_loss): best_metrics.update( { "epoch": int(resume_best.get("epoch", 0) or 0), "stage": str(resume_best.get("stage", "")), "val_loss": candidate_val_loss, "benchmark_total": float(resume_best.get("benchmark_total", -1.0)), "benchmark_weighted_total": float( resume_best.get( "benchmark_weighted_total", resume_best.get("benchmark_total", -1.0), ) ), "professionalism": float(resume_best.get("professionalism", -1.0)), } ) best_from_payload = True resume_metrics = resume_payload.get("metrics", {}) or {} if (not best_from_payload) and resume_metrics: best_metrics.update( { "epoch": int(resume_metrics.get("epoch", 0) or 0), "stage": str(resume_metrics.get("stage", "")), "val_loss": float(resume_metrics.get("val_loss", float("inf"))), "benchmark_total": float(resume_metrics.get("benchmark_total", -1.0)), "benchmark_weighted_total": float( resume_metrics.get( "benchmark_weighted_total", resume_metrics.get("benchmark_total", -1.0), ) ), "professionalism": float(resume_metrics.get("professionalism", -1.0)), } ) global_step = int(resume_metrics.get("step", 0) or 0) global_epoch = int(resume_metrics.get("epoch", 0) or 0) print("resume_best", best_metrics) base_plan = stage_epoch_plan(args.epochs, args.curriculum_stage1_ratio, args.curriculum and stage1_loader is not None) plan = remaining_stage_plan(base_plan, completed_epochs=global_epoch) print("curriculum_plan", plan) stop_early = False for stage_name, stage_epochs in plan: loader = stage1_loader if stage_name == "stage1" else train_full_loader if loader is None: continue for _ in range(stage_epochs): global_epoch += 1 for x, y in loader: x, y = x.to(device), y.to(device) _, loss = model(x, y) optimizer.zero_grad(set_to_none=True) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) optimizer.step() global_step += 1 if global_step % args.log_every == 0: print(f"step={global_step} stage={stage_name} train_loss={loss.item():.4f}") if args.max_steps > 0 and global_step >= args.max_steps: stop_early = True break val_loss = evaluate_loss(model, val_loader, device) benchmark = None benchmark_total = -1.0 benchmark_weighted_total = -1.0 professionalism = -1.0 if args.run_benchmarks and (global_epoch % args.benchmark_every == 0): benchmark = evaluate_benchmarks(model, tokenizer, max_new_tokens=args.benchmark_max_new_tokens) benchmark_total = float(benchmark["total"]) benchmark_weighted_total = float(benchmark.get("weighted_total", benchmark_total)) professionalism = float(benchmark.get("professionalism", -1.0)) metrics = { "epoch": global_epoch, "stage": stage_name, "step": global_step, "train_loss": float(loss.item()), "val_loss": float(val_loss), "benchmark_total": benchmark_total, "benchmark_weighted_total": benchmark_weighted_total, "professionalism": professionalism, "benchmark": benchmark, } history["epochs"].append(metrics) print( f"epoch={global_epoch} stage={stage_name} val_loss={val_loss:.4f} " f"benchmark_total={(benchmark_total if benchmark_total >= 0 else 'n/a')} " f"benchmark_weighted_total={(benchmark_weighted_total if benchmark_weighted_total >= 0 else 'n/a')} " f"professionalism={(professionalism if professionalism >= 0 else 'n/a')}" ) if should_update_best( metrics, best_metrics, min_val_delta=args.min_val_delta, min_benchmark_delta=args.min_benchmark_delta, checkpoint_gate=args.checkpoint_gate, ): best_metrics = { "epoch": global_epoch, "stage": stage_name, "val_loss": float(val_loss), "benchmark_total": benchmark_total, "benchmark_weighted_total": benchmark_weighted_total, "professionalism": professionalism, } save_checkpoint( Path(args.output_path), model, config, tokenizer, args, metrics, optimizer=optimizer, best_metrics=best_metrics, ) print(f"best_checkpoint_updated={args.output_path}") if args.save_all_checkpoints: epoch_ckpt = checkpoint_dir / f"epoch_{global_epoch:03d}_{stage_name}.pt" save_checkpoint( epoch_ckpt, model, config, tokenizer, args, metrics, optimizer=optimizer, best_metrics=best_metrics, ) if stop_early: break if stop_early: break history["best"] = best_metrics history_path.parent.mkdir(parents=True, exist_ok=True) with open(history_path, "w", encoding="utf-8") as f: json.dump(history, f, indent=2, ensure_ascii=False) print("training_complete_best", best_metrics) print("history_path", str(history_path)) def parse_args(): p = argparse.ArgumentParser(description="Train a tiny local causal model from local system data.") p.add_argument("--training-path", default="training_data.json") p.add_argument("--kb-path", default="knowledge_base.json") p.add_argument("--dataset-path", default="models/tiny_model_stage2.jsonl") p.add_argument("--stage1-dataset-path", default="models/tiny_model_stage1.jsonl") p.add_argument("--output-path", default="models/tiny_local_model.pt") p.add_argument("--checkpoint-dir", default="models/checkpoints") p.add_argument("--history-path", default="models/tiny_training_history.json") p.add_argument("--resume-from", default="", help="Resume training from this checkpoint path.") p.add_argument("--resume-optimizer", dest="resume_optimizer", action="store_true") p.add_argument("--no-resume-optimizer", dest="resume_optimizer", action="store_false") p.set_defaults(resume_optimizer=True) p.add_argument("--rebuild-dataset", action="store_true") p.add_argument("--curriculum", action="store_true", help="Enable stage1->stage2 data curriculum.") p.add_argument("--curriculum-stage1-ratio", type=float, default=0.4) p.add_argument("--max-kb-samples", type=int, default=4000) p.add_argument("--max-kb-samples-stage1", type=int, default=1200) p.add_argument("--max-kb-samples-stage2", type=int, default=4000) p.add_argument("--val-ratio", type=float, default=0.1) p.add_argument("--seed", type=int, default=42) p.add_argument("--epochs", type=int, default=6) p.add_argument("--batch-size", type=int, default=16) p.add_argument("--block-size", type=int, default=256) p.add_argument("--n-layer", type=int, default=4) p.add_argument("--n-head", type=int, default=4) p.add_argument("--n-embd", type=int, default=256) p.add_argument("--dropout", type=float, default=0.1) p.add_argument("--lr", type=float, default=3e-4) p.add_argument("--vocab-size", type=int, default=8000) p.add_argument("--min-freq", type=int, default=2) p.add_argument("--run-benchmarks", dest="run_benchmarks", action="store_true") p.add_argument("--no-benchmarks", dest="run_benchmarks", action="store_false") p.set_defaults(run_benchmarks=True) p.add_argument("--benchmark-every", type=int, default=1) p.add_argument("--benchmark-max-new-tokens", type=int, default=100) p.add_argument("--save-all-checkpoints", dest="save_all_checkpoints", action="store_true") p.add_argument("--no-save-all-checkpoints", dest="save_all_checkpoints", action="store_false") p.set_defaults(save_all_checkpoints=True) p.add_argument("--min-val-delta", type=float, default=1e-4) p.add_argument("--min-benchmark-delta", type=float, default=0.003) p.add_argument( "--checkpoint-gate", choices=["loss_then_benchmark", "benchmark_then_loss", "benchmark_only"], default="benchmark_then_loss", ) p.add_argument("--log-every", type=int, default=25) p.add_argument("--max-steps", type=int, default=0, help="Set >0 for a short smoke run.") return p.parse_args() if __name__ == "__main__": train(parse_args())