from __future__ import annotations import argparse import contextlib import importlib.util import json import math import random import time from pathlib import Path from typing import Any import numpy as np import torch from transformers import AutoTokenizer, LlamaForCausalLM from kawk50m.chat import KOREAN_CHAT_TEMPLATE from kawk50m.checkpoint import ( load_training_state, resolve_checkpoint, restore_rng_state, save_checkpoint, ) from kawk50m.cli import configure_utf8_stdio from kawk50m.config import build_llama_config, count_unique_parameters, load_yaml from kawk50m.sft_dataset import SFTPackedDataset from scripts.pretrain import cosine_scheduler, create_optimizer def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser( description="Assistant-only supervised fine-tuning for KAWK50M." ) parser.add_argument("--config", default="configs/sft_ko_80m_5k_5090.yaml") parser.add_argument("--resume", help="Checkpoint path or 'latest'.") parser.add_argument("--init-from", help="Base checkpoint used for fresh SFT.") parser.add_argument("--no-compile", action="store_true") parser.add_argument("--allow-cpu", action="store_true") parser.add_argument("--stop-after-steps", type=int) return parser.parse_args() def set_seed(seed: int) -> None: random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) @torch.no_grad() def evaluate_loss( model: Any, dataset: SFTPackedDataset, *, batches: int, batch_size: int, device: torch.device, use_bf16: bool, ) -> tuple[float, int]: model.eval() weighted_loss = 0.0 supervised_tokens = 0 for batch_index in range(batches): inputs, labels = dataset.evaluation_batch( batch_index=batch_index, batch_size=batch_size, rank=0, world_size=1, device=device, ) token_count = int((labels[:, 1:] != -100).sum().item()) with torch.autocast( device_type=device.type, dtype=torch.bfloat16, enabled=use_bf16, ): loss = model(input_ids=inputs, labels=labels, use_cache=False).loss weighted_loss += float(loss.item()) * token_count supervised_tokens += token_count model.train() if supervised_tokens == 0: raise RuntimeError("SFT validation has no supervised assistant tokens") return weighted_loss / supervised_tokens, supervised_tokens def checkpoint_model_dir(path: Path) -> Path: return path / "model" if (path / "model").is_dir() else path def main() -> None: configure_utf8_stdio() args = parse_args() full_config = load_yaml(args.config) data_config = full_config["data"] training = full_config["training"] if torch.cuda.is_available(): device = torch.device("cuda") elif args.allow_cpu: device = torch.device("cpu") else: raise RuntimeError("CUDA is required; use --allow-cpu only for debugging") requested_precision = str(training.get("precision", "bf16")).casefold() if requested_precision not in {"bf16", "fp32"}: raise ValueError("precision must be bf16 or fp32") use_bf16 = requested_precision == "bf16" and device.type == "cuda" if use_bf16 and not torch.cuda.is_bf16_supported(): raise RuntimeError("This GPU does not support BF16") seed = int(training.get("seed", 42)) set_seed(seed) tokenizer = AutoTokenizer.from_pretrained( full_config["tokenizer_dir"], use_fast=False, legacy=True ) tokenizer.chat_template = KOREAN_CHAT_TEMPLATE model_yaml = load_yaml(full_config["model_config"]) model_config, expected_parameters = build_llama_config( model_yaml, tokenizer_vocab_size=len(tokenizer) ) output_dir = Path(training["output_dir"]) resume_path = ( resolve_checkpoint(args.resume, output_dir) if args.resume else None ) if resume_path is None: if ( (output_dir / "latest_checkpoint.txt").exists() or (output_dir / "run_config.json").exists() or list(output_dir.glob("checkpoint-*")) ): raise FileExistsError( f"{output_dir} contains SFT artifacts; use --resume latest" ) init_path = Path(args.init_from).resolve() if args.init_from else None if resume_path is None and init_path is None: raise ValueError("Fresh SFT requires --init-from") if resume_path is not None: raw_model = LlamaForCausalLM.from_pretrained(resume_path / "model") else: assert init_path is not None if not init_path.exists(): raise FileNotFoundError(init_path) source_model = LlamaForCausalLM.from_pretrained( checkpoint_model_dir(init_path) ) raw_model = LlamaForCausalLM(model_config) raw_model.load_state_dict(source_model.state_dict(), strict=True) del source_model for attribute in ( "vocab_size", "hidden_size", "intermediate_size", "num_hidden_layers", "num_attention_heads", "num_key_value_heads", "max_position_embeddings", ): if getattr(raw_model.config, attribute) != getattr(model_config, attribute): raise ValueError(f"Checkpoint mismatch for {attribute}") parameter_count = count_unique_parameters(raw_model) if expected_parameters is not None and parameter_count != expected_parameters: raise RuntimeError( f"Expected {expected_parameters} parameters, got {parameter_count}" ) raw_model.config.use_cache = False raw_model.to(device) sequence_length = int(data_config["sequence_length"]) if sequence_length > model_config.max_position_embeddings: raise ValueError("SFT sequence length exceeds model context length") train_dataset = SFTPackedDataset( data_config["train_prefixes"], sequence_length ) validation_dataset = SFTPackedDataset( data_config["validation_prefixes"], sequence_length ) batch_size = int(training["per_device_batch_size"]) gradient_accumulation = int(training["gradient_accumulation_steps"]) if batch_size <= 0 or gradient_accumulation <= 0: raise ValueError("Batch size and gradient accumulation must be positive") sequences_per_step = batch_size * gradient_accumulation epochs = float(training.get("epochs", 1.0)) if epochs <= 0: raise ValueError("training.epochs must be positive") configured_steps = training.get("max_steps") max_steps = ( int(configured_steps) if configured_steps is not None else math.ceil(len(train_dataset) * epochs / sequences_per_step) ) if max_steps <= 0: raise ValueError("SFT max_steps must be positive") if args.stop_after_steps is not None and args.stop_after_steps <= 0: raise ValueError("--stop-after-steps must be positive") compile_enabled = bool(training.get("torch_compile", True)) and not args.no_compile if ( compile_enabled and device.type == "cuda" and importlib.util.find_spec("triton") is None ): print("torch.compile disabled because Triton is unavailable") compile_enabled = False train_model: Any = raw_model if compile_enabled: train_model = torch.compile( train_model, mode=str(training.get("compile_mode", "default")) ) optimizer = create_optimizer( train_model.parameters(), training, use_fused=device.type == "cuda" ) learning_rate = float(training["learning_rate"]) minimum_learning_rate = float(training.get("min_learning_rate", 0.0)) scheduler = cosine_scheduler( optimizer, max_steps=max_steps, warmup_ratio=float(training.get("warmup_ratio", 0.03)), min_lr_ratio=minimum_learning_rate / learning_rate, ) start_step = 0 if resume_path is not None: state = load_training_state(resume_path / "trainer_state.pt") optimizer.load_state_dict(state["optimizer"]) scheduler.load_state_dict(state["scheduler"]) restore_rng_state(state["rng"]) start_step = int(state["step"]) if start_step >= max_steps: raise ValueError("SFT checkpoint already reached max_steps") output_dir.mkdir(parents=True, exist_ok=True) tokens_per_step = sequence_length * sequences_per_step summary = { "parameters": parameter_count, "device": str(device), "sequence_length": sequence_length, "train_sequences": len(train_dataset), "validation_sequences": len(validation_dataset), "epochs": epochs, "sequences_per_optimizer_step": sequences_per_step, "tokens_per_optimizer_step": tokens_per_step, "max_steps": max_steps, "planned_capacity_tokens": max_steps * tokens_per_step, "start_step": start_step, "initialized_from": str(init_path) if init_path else None, "assistant_only_loss": True, "precision": "bf16" if use_bf16 else "fp32", "compile": compile_enabled, } print(json.dumps(summary, ensure_ascii=False, indent=2)) run_config_path = output_dir / "run_config.json" if not run_config_path.exists(): run_config_path.write_text( json.dumps( {"summary": summary, "config": full_config}, ensure_ascii=False, indent=2, ) + "\n", encoding="utf-8", ) train_model.train() optimizer.zero_grad(set_to_none=True) step = start_step log_every = int(training.get("log_every", 10)) eval_every = int(training.get("eval_every", 0)) save_every = int(training.get("save_every", 0)) max_grad_norm = float(training.get("max_grad_norm", 1.0)) interval_start = time.perf_counter() interval_step = step run_stop_step = ( min(max_steps, step + args.stop_after_steps) if args.stop_after_steps is not None else max_steps ) while step < run_stop_step: accumulated_loss = torch.zeros((), device=device) supervised_this_step = 0 for micro_index in range(gradient_accumulation): micro_step = step * gradient_accumulation + micro_index inputs, labels = train_dataset.training_batch( micro_step=micro_step, batch_size=batch_size, rank=0, world_size=1, seed=seed, device=device, ) supervised_this_step += int((labels[:, 1:] != -100).sum().item()) with contextlib.nullcontext(): with torch.autocast( device_type=device.type, dtype=torch.bfloat16, enabled=use_bf16, ): loss = train_model( input_ids=inputs, labels=labels, use_cache=False, ).loss (loss / gradient_accumulation).backward() accumulated_loss += loss.detach() grad_norm = torch.nn.utils.clip_grad_norm_( train_model.parameters(), max_grad_norm ) optimizer.step() scheduler.step() optimizer.zero_grad(set_to_none=True) step += 1 accumulated_loss /= gradient_accumulation if log_every > 0 and (step % log_every == 0 or step == 1): if device.type == "cuda": torch.cuda.synchronize(device) elapsed = time.perf_counter() - interval_start processed_tokens = (step - interval_step) * tokens_per_step print( json.dumps( { "step": step, "max_steps": max_steps, "train_loss": round(float(accumulated_loss.item()), 6), "learning_rate": scheduler.get_last_lr()[0], "grad_norm": float(grad_norm), "supervised_tokens_in_step": supervised_this_step, "tokens_per_second": round(processed_tokens / max(elapsed, 1e-9)), }, ensure_ascii=False, ) ) interval_start = time.perf_counter() interval_step = step if eval_every > 0 and step % eval_every == 0: validation_loss, supervised_tokens = evaluate_loss( train_model, validation_dataset, batches=int(training.get("eval_batches", 20)), batch_size=batch_size, device=device, use_bf16=use_bf16, ) print( json.dumps( { "step": step, "validation_loss": round(validation_loss, 6), "validation_perplexity": round( math.exp(min(validation_loss, 20.0)), 4 ), "validation_supervised_tokens": supervised_tokens, }, ensure_ascii=False, ) ) if save_every > 0 and step % save_every == 0: checkpoint_path = save_checkpoint( output_dir=output_dir, step=step, model=raw_model, tokenizer=tokenizer, optimizer=optimizer, scheduler=scheduler, training_config=full_config, world_size=1, ) print(f"Saved checkpoint: {checkpoint_path}") stopped_early = step < max_steps if bool(training.get("save_final", True)) or stopped_early: checkpoint_path = save_checkpoint( output_dir=output_dir, step=step, model=raw_model, tokenizer=tokenizer, optimizer=optimizer, scheduler=scheduler, training_config=full_config, world_size=1, ) label = "Stop checkpoint" if stopped_early else "Final checkpoint" print(f"{label}: {checkpoint_path}") if __name__ == "__main__": main()