from __future__ import annotations import argparse import contextlib import importlib.util import json import math import os import random import time from pathlib import Path from typing import Any import numpy as np import torch import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel from transformers import AutoTokenizer, LlamaForCausalLM from kawk50m.binary_dataset import PackedTokenDataset from kawk50m.cli import configure_utf8_stdio from kawk50m.checkpoint import ( load_training_state, resolve_checkpoint, restore_rng_state, save_checkpoint, ) from kawk50m.config import build_llama_config, count_unique_parameters, load_yaml def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser( description="Pretrain KAWK50M with BF16 and resumable checkpoints." ) parser.add_argument("--config", default="configs/pretrain_5b.yaml") parser.add_argument( "--resume", default=None, help="Checkpoint directory or 'latest'.", ) parser.add_argument( "--init-from", default=None, help=( "Initialize model weights from a checkpoint/model directory while " "resetting optimizer, scheduler, RNG, and step. Use this for CPT " "or context-extension stages." ), ) parser.add_argument( "--allow-cpu", action="store_true", help="Allow a slow FP32 CPU run for debugging.", ) parser.add_argument( "--no-compile", action="store_true", help="Disable torch.compile." ) parser.add_argument( "--stop-after-steps", type=int, default=None, help="Stop after this many optimizer steps in the current invocation and save.", ) return parser.parse_args() def setup_distributed(allow_cpu: bool) -> tuple[torch.device, int, int, int]: world_size = int(os.environ.get("WORLD_SIZE", "1")) rank = int(os.environ.get("RANK", "0")) local_rank = int(os.environ.get("LOCAL_RANK", "0")) if torch.cuda.is_available(): device = torch.device("cuda", local_rank) torch.cuda.set_device(device) elif allow_cpu and world_size == 1: device = torch.device("cpu") else: raise RuntimeError( "CUDA is required for BF16 pretraining. Use --allow-cpu only for debugging." ) if world_size > 1: if device.type != "cuda": raise RuntimeError("Distributed CPU training is not supported by this script") backend = "nccl" if dist.is_nccl_available() else "gloo" dist.init_process_group(backend=backend) return device, rank, local_rank, world_size def set_seed(seed: int, rank: int) -> None: local_seed = seed + rank random.seed(local_seed) np.random.seed(local_seed) torch.manual_seed(local_seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(local_seed) def cosine_scheduler( optimizer: torch.optim.Optimizer, *, max_steps: int, warmup_ratio: float, min_lr_ratio: float, ) -> torch.optim.lr_scheduler.LambdaLR: warmup_steps = round(max_steps * warmup_ratio) def multiplier(step: int) -> float: if warmup_steps > 0 and step < warmup_steps: return max(step, 1) / warmup_steps progress = (step - warmup_steps) / max(max_steps - warmup_steps, 1) progress = min(max(progress, 0.0), 1.0) cosine = 0.5 * (1.0 + math.cos(math.pi * progress)) return min_lr_ratio + (1.0 - min_lr_ratio) * cosine return torch.optim.lr_scheduler.LambdaLR(optimizer, multiplier) def create_optimizer( parameters: Any, training: dict[str, Any], *, use_fused: bool, ) -> torch.optim.AdamW: kwargs = { "lr": float(training["learning_rate"]), "betas": ( float(training.get("adam_beta1", 0.9)), float(training.get("adam_beta2", 0.95)), ), "eps": float(training.get("adam_eps", 1.0e-8)), "weight_decay": float(training.get("weight_decay", 0.1)), } if use_fused: try: return torch.optim.AdamW(parameters, fused=True, **kwargs) except (TypeError, RuntimeError): pass return torch.optim.AdamW(parameters, **kwargs) @torch.no_grad() def evaluate_loss( model: Any, dataset: PackedTokenDataset, *, batches: int, batch_size: int, rank: int, world_size: int, device: torch.device, use_bf16: bool, ) -> float: model.eval() total_loss = torch.zeros((), device=device, dtype=torch.float64) total_batches = torch.zeros((), device=device, dtype=torch.float64) for batch_index in range(batches): inputs, labels = dataset.evaluation_batch( batch_index=batch_index, batch_size=batch_size, rank=rank, world_size=world_size, device=device, ) with torch.autocast( device_type=device.type, dtype=torch.bfloat16, enabled=use_bf16, ): loss = model(input_ids=inputs, labels=labels, use_cache=False).loss total_loss += loss.detach().double() total_batches += 1 if world_size > 1: dist.all_reduce(total_loss, op=dist.ReduceOp.SUM) dist.all_reduce(total_batches, op=dist.ReduceOp.SUM) model.train() return (total_loss / total_batches).item() def main() -> None: configure_utf8_stdio() args = parse_args() if args.resume is not None and args.init_from is not None: raise ValueError("--resume and --init-from are mutually exclusive") full_config = load_yaml(args.config) data_config = full_config.get("data") training = full_config.get("training") if not isinstance(data_config, dict) or not isinstance(training, dict): raise ValueError("Training YAML requires 'data' and 'training' mappings") device, rank, local_rank, world_size = setup_distributed(args.allow_cpu) is_main = rank == 0 seed = int(training.get("seed", 42)) set_seed(seed, rank) if device.type == "cuda": torch.set_float32_matmul_precision("high") torch.backends.cuda.matmul.allow_tf32 = True requested_precision = str(training.get("precision", "bf16")).lower() 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 requested_precision == "bf16" and device.type == "cuda": if not torch.cuda.is_bf16_supported(): raise RuntimeError("This GPU does not support BF16") if device.type == "cpu" and requested_precision == "bf16" and is_main: print("CPU debug mode: falling back from BF16 to FP32") tokenizer = AutoTokenizer.from_pretrained( full_config["tokenizer_dir"], use_fast=False, legacy=True ) 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 is not None else None ) if resume_path is None: prior_checkpoints = list(output_dir.glob("checkpoint-*")) prior_markers = ( (output_dir / "latest_checkpoint.txt").exists() or (output_dir / "run_config.json").exists() or bool(prior_checkpoints) ) if prior_markers: raise FileExistsError( f"{output_dir} already contains training artifacts. " "Use --resume latest or choose a new training.output_dir." ) init_path = Path(args.init_from).resolve() if args.init_from else None if init_path is not None and not init_path.exists(): raise FileNotFoundError(init_path) if resume_path is None and init_path is None: raw_model = LlamaForCausalLM(model_config) elif resume_path is not None: raw_model = LlamaForCausalLM.from_pretrained(resume_path / "model") for attribute in ( "vocab_size", "hidden_size", "intermediate_size", "num_hidden_layers", "num_attention_heads", "num_key_value_heads", ): expected_value = getattr(model_config, attribute) actual_value = getattr(raw_model.config, attribute) if expected_value != actual_value: raise ValueError( f"Checkpoint model mismatch for {attribute}: " f"config={expected_value}, checkpoint={actual_value}" ) else: assert init_path is not None source_dir = init_path / "model" if (init_path / "model").is_dir() else init_path source_model = LlamaForCausalLM.from_pretrained(source_dir) raw_model = LlamaForCausalLM(model_config) raw_model.load_state_dict(source_model.state_dict(), strict=True) del source_model 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 if bool(training.get("gradient_checkpointing", False)): raw_model.gradient_checkpointing_enable() raw_model.to(device) sequence_length = int(data_config["sequence_length"]) if sequence_length > model_config.max_position_embeddings: raise ValueError("sequence_length exceeds max_position_embeddings") train_paths = data_config.get("train_bins", data_config.get("train_bin")) if train_paths is None: raise ValueError("data requires train_bin or train_bins") train_dataset = PackedTokenDataset(train_paths, sequence_length) training_sample_offset = int(data_config.get("sample_offset", 0)) if training_sample_offset < 0: raise ValueError("data.sample_offset must be non-negative") validation_dataset = None if int(training.get("eval_every", 0)) > 0: validation_dataset = PackedTokenDataset( data_config["validation_bin"], 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") tokens_per_step = ( sequence_length * batch_size * gradient_accumulation * world_size ) configured_steps = training.get("max_steps") if configured_steps is None: max_tokens = int(training["max_tokens"]) max_steps = math.ceil(max_tokens / tokens_per_step) else: max_steps = int(configured_steps) if max_steps <= 0: raise ValueError("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 ): if is_main: print( "torch.compile disabled: no working Triton installation was found. " "Continuing with eager BF16." ) compile_enabled = False train_model: Any = raw_model if compile_enabled: train_model = torch.compile( train_model, mode=str(training.get("compile_mode", "default")) ) if world_size > 1: train_model = DistributedDataParallel( train_model, device_ids=[local_rank], broadcast_buffers=False, gradient_as_bucket_view=True, ) 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.02)), 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") if int(state["world_size"]) != world_size: raise ValueError( "Resume requires the same world size: " f"checkpoint={state['world_size']}, current={world_size}" ) 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( f"Checkpoint step {start_step} already reached max_steps {max_steps}" ) if is_main: output_dir.mkdir(parents=True, exist_ok=True) run_summary = { "parameters": parameter_count, "device": str(device), "world_size": world_size, "sequence_length": sequence_length, "training_sample_offset": training_sample_offset, "tokens_per_optimizer_step": tokens_per_step, "max_steps": max_steps, "planned_tokens": max_steps * tokens_per_step, "start_step": start_step, "initialized_from": str(init_path) if init_path is not None else None, "precision": "bf16" if use_bf16 else "fp32", "compile": compile_enabled, } print(json.dumps(run_summary, ensure_ascii=False, indent=2)) run_config_path = output_dir / "run_config.json" if not run_config_path.exists(): with run_config_path.open("w", encoding="utf-8") as handle: json.dump( {"summary": run_summary, "config": full_config}, handle, ensure_ascii=False, indent=2, ) handle.write("\n") 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) 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=rank, world_size=world_size, seed=seed, sample_offset=training_sample_offset, device=device, ) should_sync = micro_index == gradient_accumulation - 1 sync_context = ( contextlib.nullcontext() if should_sync or world_size == 1 else train_model.no_sync() ) with sync_context: 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 world_size > 1: dist.all_reduce(accumulated_loss, op=dist.ReduceOp.SUM) accumulated_loss /= world_size 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 if is_main: log_row = { "step": step, "max_steps": max_steps, "train_loss": round(accumulated_loss.item(), 6), "learning_rate": scheduler.get_last_lr()[0], "grad_norm": float(grad_norm), "tokens_seen": step * tokens_per_step, "tokens_per_second": round(processed_tokens / max(elapsed, 1e-9)), } print(json.dumps(log_row, ensure_ascii=False)) interval_start = time.perf_counter() interval_step = step if eval_every > 0 and step % eval_every == 0: assert validation_dataset is not None validation_loss = evaluate_loss( train_model, validation_dataset, batches=int(training.get("eval_batches", 50)), batch_size=batch_size, rank=rank, world_size=world_size, device=device, use_bf16=use_bf16, ) if is_main: print( json.dumps( { "step": step, "validation_loss": round(validation_loss, 6), "validation_perplexity": round( math.exp(min(validation_loss, 20.0)), 4 ), }, ensure_ascii=False, ) ) if save_every > 0 and step % save_every == 0: if world_size > 1: dist.barrier() if is_main: 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=world_size, ) print(f"Saved checkpoint: {checkpoint_path}") if world_size > 1: dist.barrier() stopped_early = step < max_steps if bool(training.get("save_final", True)) or stopped_early: if world_size > 1: dist.barrier() if is_main: 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=world_size, ) label = "Stop checkpoint" if stopped_early else "Final checkpoint" print(f"{label}: {checkpoint_path}") if world_size > 1: dist.barrier() if world_size > 1: dist.destroy_process_group() if __name__ == "__main__": main()