pear15-stage3-checkpoints / scripts /train_agnostic.py
coderofpears's picture
Upload scripts/train_agnostic.py with huggingface_hub
0423e20 verified
Raw History Blame Contribute Delete
16.1 kB
#!/usr/bin/env python3
"""Hardware-agnostic Pear1.5 training script.
Auto-detects hardware (CUDA/TPU/CPU), configures optimal settings,
and runs training. Can resume from ANY checkpoint regardless of origin hardware.
Usage:
python train_agnostic.py --data-path /path/to/data --output-dir /path/to/checkpoints
python train_agnostic.py --data-path /path/to/data --output-dir /path/to/checkpoints --resume-from step_88587
python train_agnostic.py --data-path /path/to/data --output-dir /path/to/checkpoints --resume-from /path/to/checkpoint.pt
"""
import argparse
import json
import math
import os
import sys
import time
import hashlib
from pathlib import Path
from typing import Optional, Dict, Any
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
# Import hardware detection
sys.path.insert(0, str(Path(__file__).parent))
from hardware import get_hardware_info, get_training_config, HardwareInfo, DeviceType
# Constants
PARENT_STEP = 18666
PARENT_TOKENS = 1_739_227_136
TOKENS_PER_STEP = 16_384
TARGET = 50_000_000_000
DATA_FP = '03b6dc7f4e70ae679d84da9407dafaaf6b9e0abb79634ef9b95a34044397a553'
IMPLEMENTATION_FP = 'ef9af3b58d70b42a123ba689f4d88de267cbac4c2ba1eae2838bdb57d2b8a36d'
# Model constants (for reference)
VOCAB = 49152
HIDDEN = 576
LAYERS = 30
HEADS = 9
KV_HEADS = 3
def build_model(config: Dict[str, Any]) -> nn.Module:
"""Build Llama model from config dict."""
from transformers import LlamaConfig, LlamaForCausalLM
llama_config = LlamaConfig(
vocab_size=config["vocab_size"],
hidden_size=config["hidden_size"],
num_hidden_layers=config["num_hidden_layers"],
num_attention_heads=config["num_attention_heads"],
num_key_value_heads=config["num_key_value_heads"],
max_position_embeddings=config["max_position_embeddings"],
rope_theta=config.get("rope_theta", 10000.0),
tie_word_embeddings=config.get("tie_word_embeddings", True),
hidden_act="silu",
initializer_range=0.02,
rms_norm_eps=1e-5,
use_cache=False, # Required for gradient checkpointing
)
model = LlamaForCausalLM(llama_config)
return model
def load_checkpoint(model: nn.Module, optimizer, scheduler, ckpt_path: Path, device) -> Dict:
"""Load checkpoint from any hardware origin. Returns training state."""
print(f"Loading checkpoint from {ckpt_path}")
payload = torch.load(ckpt_path, map_location="cpu", weights_only=True)
# Load model weights
model.load_state_dict(payload["model"], strict=True)
# Load optimizer/scheduler if present
if optimizer and "optimizer" in payload:
optimizer.load_state_dict(payload["optimizer"])
if scheduler and "scheduler" in payload and payload["scheduler"]:
scheduler.load_state_dict(payload["scheduler"])
# Move model to device
model.to(device)
# Extract training state
state = {
"step": payload.get("step", 0),
"token_count": payload.get("token_count", 0),
"data_cursor": payload.get("data_cursor", {"epoch": 0, "offset_tokens": 0}),
}
print(f"Resumed from step {state['step']}, tokens {state['token_count']:,}")
return state
def save_checkpoint(model, optimizer, scheduler, step: int, token_count: int,
data_cursor: Dict, config: Dict, output_dir: Path,
is_final: bool = False, hw: HardwareInfo = None) -> Path:
"""Save checkpoint in hardware-agnostic format."""
output_dir.mkdir(parents=True, exist_ok=True)
payload = {
"model": model.state_dict(),
"optimizer": optimizer.state_dict() if optimizer else None,
"scheduler": scheduler.state_dict() if scheduler else None,
"step": step,
"token_count": token_count,
"data_cursor": data_cursor,
"model_config": {
"model_type": config["model_type"],
"vocab_size": config["vocab_size"],
"hidden_size": config["hidden_size"],
"num_hidden_layers": config["num_hidden_layers"],
"num_attention_heads": config["num_attention_heads"],
"num_key_value_heads": config["num_key_value_heads"],
"max_position_embeddings": config["max_position_embeddings"],
"tie_word_embeddings": config.get("tie_word_embeddings", True),
},
"training_config": {k: v for k, v in config.items()
if k not in ["model_type", "vocab_size", "hidden_size",
"num_hidden_layers", "num_attention_heads",
"num_key_value_heads", "max_position_embeddings",
"tie_word_embeddings"]},
"hardware_origin": {
"device_type": hw.device_type.value if hw else "unknown",
"variant": hw.variant if hw else "unknown",
"num_devices": hw.num_devices if hw else 1,
} if hw else {},
"identity": {
"implementation_fingerprint": IMPLEMENTATION_FP,
"dataset_fingerprint": DATA_FP,
"model_fingerprint": "", # TODO: compute
},
"rng": {
"torch": torch.get_rng_state(),
"cuda": torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None,
},
}
step_str = f"step_{step:012d}"
ckpt_dir = output_dir / step_str
ckpt_dir.mkdir(parents=True, exist_ok=True)
ckpt_path = ckpt_dir / "checkpoint.pt"
torch.save(payload, ckpt_path)
# Manifest
manifest = {
"format": "pear15.cloud_checkpoint.v1",
"file": "checkpoint.pt",
"sha256": hashlib.sha256(ckpt_path.read_bytes()).hexdigest(),
"bytes": ckpt_path.stat().st_size,
"step": step,
"created_ns": time.time_ns(),
"id": hashlib.sha256(f"{step}{time.time_ns()}".encode()).hexdigest()[:32],
}
(ckpt_dir / "manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True))
# READY marker
ready = b"pear15.cloud_checkpoint.v1\n" + manifest["sha256"].encode() + b"\n"
(ckpt_dir / "READY").write_bytes(ready)
print(f"Saved checkpoint: {ckpt_dir}")
return ckpt_dir
def get_dataloader(data_path: Path, config: Dict, device, hw: HardwareInfo):
"""Get DataLoader for the detected hardware.
REPLACE THIS with your actual data loader from pear15.scratch_data
"""
# For now, use a dummy loader - REPLACE WITH REAL DATA
from torch.utils.data import DataLoader, TensorDataset, IterableDataset
class DummyIterableDataset(IterableDataset):
def __iter__(self):
while True:
input_ids = torch.randint(0, VOCAB, (config["batch_size"], config["sequence_length"]), dtype=torch.long)
labels = input_ids.clone()
yield input_ids, labels
dataset = DummyIterableDataset()
loader = DataLoader(dataset, batch_size=None, num_workers=0)
if hw.device_type == DeviceType.TPU:
import torch_xla.distributed.parallel_loader as pl
return pl.MpDeviceLoader(loader, device)
elif hw.device_type == DeviceType.CUDA and hw.num_devices > 1:
# DDP handled separately
return loader
return loader
def train_loop(model, optimizer, scheduler, dataloader, device, config,
start_state, output_dir, hw, max_steps=None):
"""Main training loop."""
model.train()
step = start_state["step"]
token_count = start_state["token_count"]
data_cursor = start_state["data_cursor"]
total_steps = config["total_steps"] if max_steps is None else min(config["total_steps"], start_state["step"] + max_steps)
grad_accum = config["gradient_accumulation_steps"]
log_interval = config["log_interval_steps"]
ckpt_interval = config["checkpoint_interval_steps"]
ckpt_interval_sec = config["checkpoint_interval_seconds"]
optimizer.zero_grad()
accumulated_loss = 0.0
last_ckpt_time = time.time()
print(f"Starting training from step {step} to {total_steps}")
print(f"Device: {device}, Hardware: {hw.variant}, Effective batch: {hw.effective_batch}")
# For TPU
is_tpu = hw.device_type == DeviceType.TPU
if is_tpu:
import torch_xla.core.xla_model as xm
for epoch in range(10000): # Large number, controlled by total_steps
for batch_idx, (input_ids, labels) in enumerate(dataloader):
if step >= total_steps:
break
input_ids = input_ids.to(device, non_blocking=True)
labels = labels.to(device, non_blocking=True)
# Forward
outputs = model(input_ids=input_ids, labels=labels)
loss = outputs.loss / grad_accum
# Backward
loss.backward()
accumulated_loss += loss.item()
# Optimizer step
if (batch_idx + 1) % grad_accum == 0:
# Gradient clipping
torch.nn.utils.clip_grad_norm_(model.parameters(), config["max_grad_norm"])
if is_tpu:
import torch_xla.core.xla_model as xm
xm.optimizer_step(optimizer)
else:
optimizer.step()
scheduler.step()
optimizer.zero_grad()
step += 1
token_count += TOKENS_PER_STEP
# Logging
if step % log_interval == 0:
avg_loss = accumulated_loss / log_interval
lr = scheduler.get_last_lr()[0]
print(f"step {step:,} | tokens {token_count:,} | loss {avg_loss:.4f} | lr {lr:.2e}")
accumulated_loss = 0.0
# Checkpoint (step-based)
if step % ckpt_interval == 0:
data_cursor = {"epoch": epoch, "offset_tokens": token_count % 997_885_340}
save_checkpoint(model, optimizer, scheduler, step, token_count,
data_cursor, config, output_dir, hw=hw)
last_ckpt_time = time.time()
# Checkpoint (time-based)
if time.time() - last_ckpt_time >= ckpt_interval_sec:
data_cursor = {"epoch": epoch, "offset_tokens": token_count % 997_885_340}
save_checkpoint(model, optimizer, scheduler, step, token_count,
data_cursor, config, output_dir, hw=hw)
last_ckpt_time = time.time()
if step >= total_steps:
break
# Final checkpoint
data_cursor = {"epoch": epoch, "offset_tokens": token_count % 997_885_340}
save_checkpoint(model, optimizer, scheduler, step, token_count,
data_cursor, config, output_dir, is_final=True, hw=hw)
if is_tpu:
import torch_xla.core.xla_model as xm
xm.wait_device_ops()
return step, token_count
def setup_device(hw: HardwareInfo):
"""Setup device for training."""
if hw.device_type == DeviceType.CUDA:
if hw.num_devices > 1:
# DDP setup
import torch.distributed as dist
dist.init_process_group(backend="nccl")
local_rank = int(os.environ.get("LOCAL_RANK", 0))
device = torch.device(f"cuda:{local_rank}")
torch.cuda.set_device(device)
else:
device = torch.device("cuda:0")
# Enable TF32 for Ampere+
if hw.supports_bf16:
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
elif hw.device_type == DeviceType.TPU:
import torch_xla.core.xla_model as xm
device = xm.xla_device()
os.environ["PJRT_DEVICE"] = "TPU"
os.environ["XLA_USE_BF16"] = "1"
else:
device = torch.device("cpu")
return device
def setup_optimizer(model, config):
"""Setup optimizer and scheduler."""
optimizer = torch.optim.AdamW(
model.parameters(),
lr=config["learning_rate"],
betas=(config["adam_beta1"], config["adam_beta2"]),
eps=config["adam_epsilon"],
weight_decay=config["weight_decay"],
)
total_steps = config["total_steps"]
warmup_steps = config["warmup_steps"]
min_lr_ratio = config["min_lr_ratio"]
def lr_lambda(current_step):
if current_step < warmup_steps:
return float(current_step + 1) / float(max(1, warmup_steps))
progress = float(current_step - warmup_steps) / float(max(1, total_steps - warmup_steps))
return max(min_lr_ratio, 1.0 - progress * (1.0 - min_lr_ratio))
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
return optimizer, scheduler
def main():
parser = argparse.ArgumentParser(description="Hardware-agnostic Pear1.5 training")
parser.add_argument("--data-path", type=Path, required=True, help="Path to expanded dataset")
parser.add_argument("--output-dir", type=Path, required=True, help="Checkpoint output directory")
parser.add_argument("--resume-from", type=str, default=None,
help="Resume from checkpoint (step number, 'latest', or path)")
parser.add_argument("--max-steps", type=int, default=None, help="Max steps to run")
parser.add_argument("--hf-model-path", type=Path, default=None,
help="HF model path for fresh init (if not resuming)")
parser.add_argument("--seed", type=int, default=0)
args = parser.parse_args()
torch.manual_seed(args.seed)
# Detect hardware
hw = get_hardware_info()
config = get_training_config(hw)
# Setup device
device = setup_device(hw)
# Build or load model
if args.resume_from:
# Resume from checkpoint
model = build_model(config)
optimizer, scheduler = setup_optimizer(model, config)
if args.resume_from == "latest":
# Find latest checkpoint in output_dir
ckpts = sorted(args.output_dir.glob("step_*/checkpoint.pt"))
if not ckpts:
raise ValueError("No checkpoints found to resume from")
ckpt_path = ckpts[-1]
elif args.resume_from.isdigit():
# Step number
step = int(args.resume_from)
ckpt_path = args.output_dir / f"step_{step:012d}" / "checkpoint.pt"
else:
ckpt_path = Path(args.resume_from)
start_state = load_checkpoint(model, optimizer, scheduler, ckpt_path, device)
else:
# Fresh init from HF model or scratch
if args.hf_model_path:
from transformers import AutoModelForCausalLM
print(f"Loading from HF model: {args.hf_model_path}")
model = AutoModelForCausalLM.from_pretrained(
args.hf_model_path, torch_dtype=torch.bfloat16 if hw.supports_bf16 else torch.float32, use_cache=False
)
else:
model = build_model(config)
model.gradient_checkpointing_enable()
model.to(device)
optimizer, scheduler = setup_optimizer(model, config)
start_state = {"step": 0, "token_count": 0, "data_cursor": {"epoch": 0, "offset_tokens": 0}}
# DDP wrap for multi-GPU
if hw.device_type == DeviceType.CUDA and hw.num_devices > 1:
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[device.index])
# Data loader
dataloader = get_dataloader(args.data_path, config, device, hw)
# Train
final_step, final_tokens = train_loop(
model, optimizer, scheduler, dataloader, device, config,
start_state, args.output_dir, hw, max_steps=args.max_steps
)
print(f"Training complete: step {final_step}, tokens {final_tokens:,}")
if __name__ == "__main__":
main()