File size: 19,880 Bytes
91ac3cc | 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 | 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()
|