Upload train_sft.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613# ============================================================================# ViuAI 500M — Supervised Fine-Tuning (SFT) Script# ============================================================================# Universal script: works on H200(140GB), 5090(32GB), L4(24GB), T4x2(16GBx2)# Works on: Kaggle, Rental GPU, Any cloud provider## Run commands:# Kaggle T4x2: torchrun --nproc_per_node=2 train_sft.py# Single GPU: torchrun --nproc_per_node=1 train_sft.py# Multi-GPU: torchrun --nproc_per_node=<N> train_sft.py# ============================================================================
import osos.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
import json, math, time, random, sys, contextlib, gcimport numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as Fimport torch.distributed as distfrom torch.nn.parallel import DistributedDataParallel as DDPfrom huggingface_hub import HfApi, hf_hub_download, create_repo, loginfrom datetime import timedelta
# ============================================================================# 1. DDP Setup (works for single GPU too via torchrun --nproc_per_node=1)# ============================================================================def setup_ddp(): dist.init_process_group(backend="nccl", timeout=timedelta(minutes=30)) rank = dist.get_rank() local_rank = int(os.environ.get("LOCAL_RANK", 0)) world_size = dist.get_world_size() torch.cuda.set_device(local_rank) return rank, local_rank, world_size
rank, local_rank, world_size = setup_ddp()DEVICE = f"cuda:{local_rank}"IS_MAIN = rank == 0
def log(msg): if IS_MAIN: print(msg, flush=True)
# ============================================================================# 2. Authentication (Kaggle + Rental GPU dono support)# ============================================================================HF_TOKEN = os.environ.get("HF_TOKEN")if not HF_TOKEN: try: from kaggle_secrets import UserSecretsClient HF_TOKEN = UserSecretsClient().get_secret("HF_TOKEN") os.environ["HF_TOKEN"] = HF_TOKEN except Exception: passif not HF_TOKEN: raise RuntimeError( "HF_TOKEN not found!\n" " Kaggle: Settings → Secrets → Add HF_TOKEN\n" " Rental GPU: export HF_TOKEN='hf_your_token'" )login(token=HF_TOKEN)api = HfApi(token=HF_TOKEN)
# ============================================================================# 3. Repository Configuration# ============================================================================MAIN_REPO = "ViuAI/ViuAI-500M" # Base model + SFT checkpointsSFT_DATA_REPO = "ViuAI/viuai-250m-sft-tokenized" # Pre-tokenized SFT data
if IS_MAIN: create_repo(MAIN_REPO, repo_type="model", token=HF_TOKEN, exist_ok=True, private=True)dist.barrier()
# ============================================================================# 4. Working Directory (auto-detect environment)# ============================================================================if os.path.exists("/kaggle/working"): WORK = "/kaggle/working"elif os.path.exists("/root/working"): WORK = "/root/working"else: WORK = "./working"os.makedirs(WORK, exist_ok=True)os.makedirs(f"{WORK}/code", exist_ok=True)sys.path.insert(0, f"{WORK}/code")
# ============================================================================# 5. Download Model Code from HuggingFace# ============================================================================def with_retry(fn, *args, retries=4, delay=5, **kwargs): for attempt in range(1, retries + 1): try: return fn(*args, **kwargs) except Exception as e: if "404" in str(e) or "EntryNotFoundError" in type(e).__name__: raise if attempt == retries: raise log(f" [retry {attempt}/{retries}] {type(e).__name__}: {e}") time.sleep(delay) delay *= 2
if IS_MAIN: log("📥 Downloading model code...") hf_hub_download(MAIN_REPO, "code/config.py", local_dir=WORK, token=HF_TOKEN) hf_hub_download(MAIN_REPO, "code/model.py", local_dir=WORK, token=HF_TOKEN)dist.barrier()
from config import ViuAIConfigfrom model import ViuAI
# ============================================================================# 6. GPU Auto-Detection & Hyperparameters# ============================================================================mem_gb = torch.cuda.get_device_properties(local_rank).total_mem / 1e9gpu_name = torch.cuda.get_device_name(local_rank)
# Check if GPU supports bfloat16 (Ampere+ architecture, compute capability >= 8.0)compute_cap = torch.cuda.get_device_capability(local_rank)supports_bf16 = compute_cap[0] >= 8 # Ampere (8.0), Hopper (9.0) etc.
if mem_gb >= 70: # H200 (140GB), H100 (80GB), A100 (80GB) MICRO_BATCH = 16 GRAD_ACCUM = 2 CONTEXT_LEN = 2048 AMP_DTYPE = torch.bfloat16 USE_COMPILE = True EMPTY_CACHE_EVERY = 500elif mem_gb >= 28: # RTX 5090 (32GB), A10G (24GB but reported higher) MICRO_BATCH = 8 GRAD_ACCUM = 4 CONTEXT_LEN = 2048 AMP_DTYPE = torch.bfloat16 USE_COMPILE = True EMPTY_CACHE_EVERY = 200elif mem_gb >= 20: # L4 (24GB), RTX 4090 (24GB) MICRO_BATCH = 4 GRAD_ACCUM = 8 CONTEXT_LEN = 2048 AMP_DTYPE = torch.bfloat16 if supports_bf16 else torch.float16 USE_COMPILE = supports_bf16 # Only compile on Ampere+ EMPTY_CACHE_EVERY = 100else: # T4 (16GB), RTX 3060 (12GB) MICRO_BATCH = 2 GRAD_ACCUM = 8 CONTEXT_LEN = 1024 # Reduced to fit in 16GB AMP_DTYPE = torch.float16 # T4 does NOT support bfloat16 USE_COMPILE = False # T4 Turing has poor torch.compile support EMPTY_CACHE_EVERY = 50
# SFT-specific hyperparameters (same for all GPUs)MAX_LR = 1e-5 # Very small LR to preserve base knowledgeMIN_LR = 1e-6WARMUP_STEPS = 50EPOCHS = 3WEIGHT_DECAY = 0.01GRAD_CLIP = 1.0EVAL_EVERY = 200CKPT_EVERY = 500
# Vocab size: SFT data was tokenized with 250M SFT tokenizer (64003 vocab)# Base model was trained with 64000 vocab# We use 64003 to match the SFT data; embedding resize handles the mismatchSFT_VOCAB_SIZE = 64003
effective_batch = MICRO_BATCH * GRAD_ACCUM * world_sizelog(f"{'='*60}")log(f"🖥️ GPU: {gpu_name} | VRAM: {mem_gb:.1f}GB | Compute: {compute_cap[0]}.{compute_cap[1]}")log(f"⚙️ MICRO_BATCH={MICRO_BATCH} | GRAD_ACCUM={GRAD_ACCUM} | CTX={CONTEXT_LEN}")log(f"⚙️ AMP={AMP_DTYPE} | torch.compile={'ON' if USE_COMPILE else 'OFF'}")log(f"⚙️ Effective Batch Size: {effective_batch} | GPUs: {world_size}")log(f"⚙️ LR: {MAX_LR} → {MIN_LR} | Epochs: {EPOCHS}")log(f"{'='*60}")
torch.backends.cudnn.benchmark = Truetorch.backends.cuda.matmul.allow_tf32 = True
# ============================================================================# 7. SFT Dataset (Pre-tokenized .npy with -100 label masking)# ============================================================================# Labels have -100 on user-turn tokens → loss is ONLY on assistant responses.# input_ids and labels are at SAME alignment (no shift in the data files).# The shift is handled in compute_sft_loss() below.class NpySFTDataset: def __init__(self, ids_path, labels_path, offsets_path, ctx_len): self.ids = np.load(ids_path, mmap_mode='r') self.labels = np.load(labels_path, mmap_mode='r') self.offsets = np.load(offsets_path) self.ctx_len = ctx_len
def __len__(self): return len(self.offsets)
def get(self, idx): start = int(self.offsets[idx]) end = int(self.offsets[idx + 1]) if idx + 1 < len(self.offsets) else len(self.ids) length = min(end - start, self.ctx_len)
input_ids = np.zeros(self.ctx_len, dtype=np.int64) labels = np.full(self.ctx_len, -100, dtype=np.int64)
input_ids[:length] = self.ids[start:start + length].astype(np.int64) labels[:length] = self.labels[start:start + length].astype(np.int64) return input_ids, labels
def get_sft_batch(dataset, batch_size, rng): batch_ids, batch_labels = [], [] for _ in range(batch_size): idx = rng.randrange(len(dataset)) ids, labels = dataset.get(idx) batch_ids.append(ids) batch_labels.append(labels) x = torch.from_numpy(np.stack(batch_ids)).pin_memory().to(DEVICE, non_blocking=True) y = torch.from_numpy(np.stack(batch_labels)).pin_memory().to(DEVICE, non_blocking=True) return x, y
# ============================================================================# 8. Checkpoint Key Remapping (handles torch.compile prefix + vocab resize)# ============================================================================def remap_checkpoint_keys(ckpt_state_dict, model_state_dict): """Remap checkpoint keys to match current model. Handles: 1. torch.compile prefix: _orig_mod.X → X 2. Vocab size mismatch: resize tok_emb.weight and head.weight """ model_keys = set(model_state_dict.keys())
# Step 1: Strip '_orig_mod.' prefix (from torch.compile during pretraining) stripped = {} n_stripped = 0 for key, value in ckpt_state_dict.items(): if key.startswith("_orig_mod."): stripped[key[len("_orig_mod."):]] = value n_stripped += 1 else: stripped[key] = value if n_stripped: log(f" 🔧 Stripped '_orig_mod.' from {n_stripped} keys (torch.compile artifact)")
# Step 2: Handle vocab size mismatch (e.g., base=64000 → SFT=64003) for emb_key in ["tok_emb.weight", "head.weight"]: if emb_key in stripped and emb_key in model_state_dict: ckpt_shape = stripped[emb_key].shape model_shape = model_state_dict[emb_key].shape if ckpt_shape != model_shape: log(f" 📐 Resizing '{emb_key}': {list(ckpt_shape)} → {list(model_shape)}") new_weight = model_state_dict[emb_key].clone() min_vocab = min(ckpt_shape[0], model_shape[0]) new_weight[:min_vocab] = stripped[emb_key][:min_vocab] stripped[emb_key] = new_weight
return stripped
# ============================================================================# 9. Checkpoint Save / Load# ============================================================================def save_checkpoint(model, optimizer, step, val_loss, filename): if not IS_MAIN: return path = f"{WORK}/{filename}" raw_model = model.module if hasattr(model, "module") else model if hasattr(raw_model, '_orig_mod'): raw_model = raw_model._orig_mod state_dict = raw_model.state_dict() clean_dict = {k.replace("_orig_mod.", ""): v for k, v in state_dict.items()}
torch.save({"model": clean_dict, "optimizer": optimizer.state_dict(), "step": step, "val_loss": val_loss}, path)
with_retry(api.upload_file, path_or_fileobj=path, path_in_repo=f"sft_checkpoints/{filename}", repo_id=MAIN_REPO, repo_type="model", token=HF_TOKEN) log(f" [sft checkpoint saved @ step {step}, val_loss={val_loss:.4f}]")
def save_best_checkpoint(model, step, val_loss): """Save best SFT model separately (no optimizer, smaller file).""" if not IS_MAIN: return path = f"{WORK}/sft_ckpt_best.pt" raw_model = model.module if hasattr(model, "module") else model if hasattr(raw_model, '_orig_mod'): raw_model = raw_model._orig_mod state_dict = raw_model.state_dict() clean_dict = {k.replace("_orig_mod.", ""): v for k, v in state_dict.items()}
torch.save({"model": clean_dict, "step": step, "val_loss": val_loss}, path)
with_retry(api.upload_file, path_or_fileobj=path, path_in_repo="sft_checkpoints/sft_ckpt_best.pt", repo_id=MAIN_REPO, repo_type="model", token=HF_TOKEN) log(f" ✨ Best SFT checkpoint saved @ step {step}, val_loss={val_loss:.4f}")
def load_sft_checkpoint(model, optimizer): """Load checkpoint: tries SFT first, then falls back to base pretrained.""" # Try 1: Resume from existing SFT checkpoint try: log("🔍 Looking for existing SFT checkpoint...") path = with_retry(hf_hub_download, MAIN_REPO, "sft_checkpoints/sft_ckpt_latest.pt", repo_type="model", local_dir=WORK, token=HF_TOKEN) ckpt = torch.load(path, map_location="cpu", weights_only=False) # Get the actual model (unwrap DDP + compile) raw_model = model.module if hasattr(model, "module") else model if hasattr(raw_model, '_orig_mod'): raw_model = raw_model._orig_mod remapped = remap_checkpoint_keys(ckpt["model"], raw_model.state_dict()) raw_model.load_state_dict(remapped) if "optimizer" in ckpt: try: optimizer.load_state_dict(ckpt["optimizer"]) except Exception: log(" ⚠️ Could not load optimizer state (architecture change?), using fresh optimizer") step = ckpt.get("step", 0) val_loss = ckpt.get("val_loss", -1) log(f"✅ Resumed SFT from step {step} (val_loss={val_loss:.4f})") del ckpt gc.collect() torch.cuda.empty_cache() return step except Exception as e: log(f" (No SFT checkpoint found: {type(e).__name__})")
# Try 2: Load BASE pretrained weights (30k step checkpoint) log("📥 Loading BASE 30k pretrained weights...") try: path = with_retry(hf_hub_download, MAIN_REPO, "checkpoints/ckpt_latest.pt", repo_type="model", local_dir=WORK, token=HF_TOKEN) ckpt = torch.load(path, map_location="cpu", weights_only=False) raw_model = model.module if hasattr(model, "module") else model if hasattr(raw_model, '_orig_mod'): raw_model = raw_model._orig_mod remapped = remap_checkpoint_keys(ckpt["model"], raw_model.state_dict()) raw_model.load_state_dict(remapped) pretrain_step = ckpt.get("step", "?") pretrain_loss = ckpt.get("val_loss", -1) log(f"✅ Loaded BASE pretrained weights (pretrain step={pretrain_step}, " f"val_loss={pretrain_loss:.4f})") log(" Starting SFT from step 0 (optimizer is fresh for SFT)") del ckpt gc.collect() torch.cuda.empty_cache() return 0 except Exception as e: log(f"❌ FATAL: Cannot load base pretrained weights!") log(f" Error: {type(e).__name__}: {e}") raise RuntimeError( "SFT requires a pretrained base model but none could be loaded.\n" f"Checked: {MAIN_REPO}/checkpoints/ckpt_latest.pt\n" f" {MAIN_REPO}/sft_checkpoints/sft_ckpt_latest.pt" )
# ============================================================================# 10. Learning Rate Schedule (Cosine with Warmup)# ============================================================================def get_lr(step, warmup, total, max_lr, min_lr): if step < warmup: return max_lr * (step + 1) / warmup if step > total: return min_lr ratio = (step - warmup) / max(total - warmup, 1) return min_lr + 0.5 * (1 + math.cos(math.pi * ratio)) * (max_lr - min_lr)
# ============================================================================# 11. SFT Loss Function (CRITICAL: handles shift mismatch)# ============================================================================# The 500M model.py does NOT shift logits/labels internally.# (It was removed because pretraining dataloader already shifts: y = tokens[i+1:])# But SFT data has labels at SAME position as input_ids.# So we MUST shift here:# - Input to model: x[:, :-1] (all tokens except the last)# - Labels: y[:, 1:] (all labels shifted left by 1)## This makes: logits[t] (predicts next token after 0..t) ↔ labels[t+1] ✓def compute_sft_loss(model, x, y, pad_id=0): """Forward pass with proper shift for SFT.""" x_in = x[:, :-1].contiguous() # [B, T-1] — drop last token y_shifted = y[:, 1:].contiguous() # [B, T-1] — shift labels left by 1 _, loss = model(x_in, targets=y_shifted, pad_id=pad_id) return loss
# ============================================================================# 12. Model Initialization# ============================================================================cfg = ViuAIConfig( vocab_size=SFT_VOCAB_SIZE, # 64003 (matches SFT tokenizer) context_length=CONTEXT_LEN, use_checkpoint=True, # Gradient checkpointing (saves VRAM) z_loss_weight=0.0, # Disable z-loss for SFT attn_dropout=0.1, # Regularization for SFT resid_dropout=0.1,)raw_model = ViuAI(cfg).to(DEVICE)if IS_MAIN: log(f"🧠 Model params: {raw_model.num_params()/1e6:.1f}M | vocab_size={SFT_VOCAB_SIZE}")
# Optionally compile (significant speedup on Ampere+ GPUs)if USE_COMPILE: log("⚡ Compiling model with torch.compile (this takes 1-2 mins on first step)...") raw_model = torch.compile(raw_model)
model = DDP(raw_model, device_ids=[local_rank])optimizer = torch.optim.AdamW( model.parameters(), lr=MAX_LR, weight_decay=WEIGHT_DECAY, betas=(0.9, 0.95))
# Load checkpoint (SFT resume or base pretrained)start_step = load_sft_checkpoint(model, optimizer)start_step_t = torch.tensor([start_step], device=DEVICE)dist.broadcast(start_step_t, src=0)start_step = start_step_t.item()
# ============================================================================# 13. Download & Load SFT Data# ============================================================================log("📥 Downloading SFT data (.npy files)...")SFT_DATA_FILES = [ "sft_train_ids.npy", "sft_train_labels.npy", "sft_train_offsets.npy", "sft_val_ids.npy", "sft_val_labels.npy", "sft_val_offsets.npy",]for fname in SFT_DATA_FILES: with_retry(hf_hub_download, SFT_DATA_REPO, fname, repo_type="dataset", local_dir=WORK, token=HF_TOKEN)log("✅ SFT data downloaded.")
train_ds = NpySFTDataset( f"{WORK}/sft_train_ids.npy", f"{WORK}/sft_train_labels.npy", f"{WORK}/sft_train_offsets.npy", CONTEXT_LEN)val_ds = NpySFTDataset( f"{WORK}/sft_val_ids.npy", f"{WORK}/sft_val_labels.npy", f"{WORK}/sft_val_offsets.npy", CONTEXT_LEN)if IS_MAIN: log(f"📊 Train examples: {len(train_ds)}, Val examples: {len(val_ds)}")
# ============================================================================# 14. Sanity Checks# ============================================================================if IS_MAIN: _s_ids, _s_labels = train_ds.get(0) _has_masked = (_s_labels == -100).any() _has_active = (_s_labels != -100).any() assert _has_masked, ( "SFT FATAL: No masked tokens (-100) found in labels! " "User-turn tokens MUST be -100. Your data pipeline is broken." ) assert _has_active, ( "SFT FATAL: ALL tokens are masked (-100)! " "No assistant tokens to train on. Your data pipeline is broken." ) _max_id = int(_s_ids[_s_ids > 0].max()) if (_s_ids > 0).any() else 0 _masked_count = (_s_labels == -100).sum() _active_count = ((_s_labels != -100) & (_s_labels != 0)).sum() log(f"✅ Data sanity check passed:") log(f" Masked (user) tokens: {_masked_count} | Active (assistant) tokens: {_active_count}") log(f" Max token ID in data: {_max_id} | Model vocab: {SFT_VOCAB_SIZE}") if _max_id >= SFT_VOCAB_SIZE: log(f"⚠️ WARNING: Max token ID ({_max_id}) >= vocab ({SFT_VOCAB_SIZE})! Will crash!") del _s_ids, _s_labels
# ============================================================================# 15. Training Step Math# ============================================================================PAD_ID = 0rng = random.Random(1337 + rank)val_rng = random.Random(999)
TOTAL_STEPS = (len(train_ds) // (MICRO_BATCH * GRAD_ACCUM * world_size)) * EPOCHSend_step = TOTAL_STEPSTOTAL_NEW_STEPS = max(1, end_step - start_step)
log(f"📈 Total SFT steps for {EPOCHS} epochs: {TOTAL_STEPS}")log(f" Resumed from step: {start_step} | Remaining: {TOTAL_NEW_STEPS}")log(f" Training: step {start_step} → {end_step}")
# ============================================================================# 16. Evaluation Function# ============================================================================@torch.no_grad()def evaluate(): if not IS_MAIN: return None model.eval() losses = [] eval_rng = random.Random(42) for _ in range(20): x, y = get_sft_batch(val_ds, MICRO_BATCH, eval_rng) with torch.autocast(device_type="cuda", dtype=AMP_DTYPE): loss = compute_sft_loss(model, x, y, pad_id=PAD_ID) losses.append(loss.item()) del x, y, loss model.train() torch.cuda.empty_cache() return sum(losses) / len(losses)
# ============================================================================# 17. Training Loop# ============================================================================log(f"\n{'='*60}")log(f"🚀 Starting SFT Training...")log(f"{'='*60}\n")
model.train()val_loss = Nonebest_val_loss = Noneema_tok_s = Noneglobal_t0 = time.time()t0 = time.time()
for step in range(start_step, end_step): # LR schedule (based on local step, not global) local_step = step - start_step lr = get_lr(local_step, WARMUP_STEPS, TOTAL_NEW_STEPS, MAX_LR, MIN_LR) for g in optimizer.param_groups: g["lr"] = lr
optimizer.zero_grad(set_to_none=True) accum_loss = 0.0
for micro_i in range(GRAD_ACCUM): x, y = get_sft_batch(train_ds, MICRO_BATCH, rng) sync_ctx = model.no_sync() if micro_i < GRAD_ACCUM - 1 else contextlib.nullcontext() with sync_ctx: with torch.autocast(device_type="cuda", dtype=AMP_DTYPE): loss = compute_sft_loss(model, x, y, pad_id=PAD_ID) loss = loss / GRAD_ACCUM loss.backward() accum_loss += loss.item() del x, y, loss
torch.nn.utils.clip_grad_norm_(model.parameters(), GRAD_CLIP)
# NaN/Inf protection if not math.isfinite(accum_loss): if IS_MAIN: log(f"⚠️ NaN/Inf loss at step {step}! Skipping optimizer step.") optimizer.zero_grad(set_to_none=True) continue
optimizer.step()
# ---- Logging (every 10 steps) ---- if IS_MAIN and step % 10 == 0: dt = time.time() - t0 tok_s = (MICRO_BATCH * GRAD_ACCUM * CONTEXT_LEN * world_size * 10) / dt if dt > 0 else 0 ema_tok_s = tok_s if ema_tok_s is None else 0.7 * ema_tok_s + 0.3 * tok_s t0 = time.time() mem_alloc = torch.cuda.memory_allocated(DEVICE) / 1e9 mem_reserved = torch.cuda.memory_reserved(DEVICE) / 1e9 steps_done = step - start_step if steps_done > 0: elapsed = time.time() - global_t0 eta_s = elapsed / steps_done * (end_step - step) eta_str = f"{eta_s/60:.0f}min" if eta_s < 3600 else f"{eta_s/3600:.1f}hr" else: eta_str = "..." log(f"SFT step {step:5d}/{end_step} | loss {accum_loss:.4f} | lr {lr:.2e} | " f"{ema_tok_s:.0f} tok/s | ETA {eta_str} | " f"mem {mem_alloc:.1f}GB/{mem_reserved:.1f}GB")
# ---- Memory cleanup (important for T4!) ---- if step > start_step and step % EMPTY_CACHE_EVERY == 0: torch.cuda.empty_cache()
# ---- Evaluation ---- if step > start_step and step % EVAL_EVERY == 0: val_loss = evaluate() if IS_MAIN and val_loss is not None: log(f" >> val_loss {val_loss:.4f}") if best_val_loss is None or val_loss < best_val_loss: best_val_loss = val_loss save_best_checkpoint(model, step, val_loss)
# ---- Save latest checkpoint ---- if step > start_step and step % CKPT_EVERY == 0: dist.barrier() save_checkpoint(model, optimizer, step, val_loss if val_loss is not None else -1, "sft_ckpt_latest.pt")
# ============================================================================# 18. Final Save & Cleanup# ============================================================================dist.barrier()final_val = evaluate()save_checkpoint(model, optimizer, end_step, final_val if final_val is not None else -1, "sft_ckpt_latest.pt")
if IS_MAIN: log(f"\n{'='*60}") log(f"✨ 500M SFT Training Complete!") log(f" Final val_loss: {final_val if final_val is not None else -1:.4f}") log(f" Best val_loss: {best_val_loss if best_val_loss is not None else -1:.4f}") log(f" Checkpoints saved to: {MAIN_REPO}/sft_checkpoints/") log(f"{'='*60}")
dist.destroy_process_group()code/train_sft.pyAdded+613