File size: 22,350 Bytes
0ce8172 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 | 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())
|