Upload 2 files
Browse filesFiles changed (2)
- code/model.py+4-1
- code/train_sft.py+49-20
138 unmodified lines139140141142143144145138 unmodified linesfor block in self.blocks:if self.training and self.cfg.use_checkpoint:x = checkpoint(block, x, cos, sin, attn_mask, use_reentrant=False)else:x = block(x, cos, sin, attn_mask)x = self.final_norm(x)138 unmodified lines139140141142143144145146147148138 unmodified linesfor block in self.blocks:if self.training and self.cfg.use_checkpoint:if attn_mask is not None:x = checkpoint(block, x, cos, sin, attn_mask, use_reentrant=False)else:x = checkpoint(block, x, cos, sin, use_reentrant=False)else:x = block(x, cos, sin, attn_mask)x = self.final_norm(x)
159 unmodified lines16016116216316416516616716816917017117217375 unmodified lines2492502512522532542552562572582592602612622632642659 unmodified lines27527627727827928028141 unmodified lines32332432532632732832940 unmodified lines37037137237337437529 unmodified lines405406407408409410133 unmodified lines5445455465475485495505515525535545555 unmodified lines56156256356456556656756856937 unmodified lines6076086096106116126136141 unmodified line61661761861962062132 unmodified lines65465565665765865910 unmodified lines670671672673674675676677678679680681682683684685159 unmodified linesEMPTY_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 = 1000CKPT_EVERY = 5000# Vocab size: SFT data was tokenized with 250M SFT tokenizer (64003 vocab)# Base model was trained with 64000 vocab75 unmodified linesif 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].shapemodel_shape = model_state_dict[emb_key].shapeif 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_weightreturn stripped9 unmodified lines"""if not IS_MAIN:returnpath = f"{WORK}/{filename}"raw_model = model.module if hasattr(model, "module") else modelif hasattr(raw_model, '_orig_mod'):raw_model = raw_model._orig_mod41 unmodified lines"""if not IS_MAIN:returnpath = f"{WORK}/sft_ckpt_best.pt"raw_model = model.module if hasattr(model, "module") else modelif hasattr(raw_model, '_orig_mod'):raw_model = raw_model._orig_mod40 unmodified linesremapped = remap_checkpoint_keys(ckpt["model"], raw_model.state_dict())raw_model.load_state_dict(remapped)if "optimizer" in ckpt:try:29 unmodified linesremapped = 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)133 unmodified linesrng = 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}")# ============================================================================5 unmodified linesreturn Nonemodel.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())37 unmodified linesaccum_loss += loss.item()del x, y, losstorch.nn.utils.clip_grad_norm_(model.parameters(), GRAD_CLIP)# NaN/Inf protectionif not math.isfinite(accum_loss):if IS_MAIN:1 unmodified lineoptimizer.zero_grad(set_to_none=True)continueoptimizer.step()# ---- Logging (every 10 steps) ----32 unmodified lines# ---- Save latest checkpoint (background upload) ----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", blocking=False)10 unmodified lines"sft_ckpt_latest.pt", blocking=True)# Upload best checkpoint at the very end (only once, saves GPU time)if IS_MAIN and os.path.exists(f"{WORK}/sft_ckpt_best.pt"):log(f" βοΈ Uploading best checkpoint to HF (blocking, please wait)...")try:with_retry(api.upload_file, path_or_fileobj=f"{WORK}/sft_ckpt_best.pt",path_in_repo="sft_checkpoints/sft_ckpt_best.pt",repo_id=MAIN_REPO, repo_type="model", token=HF_TOKEN)log(f" β Best checkpoint uploaded to HF!")except Exception as e:log(f" β Best checkpoint upload failed: {e}")log(f" β οΈ File saved locally at: {WORK}/sft_ckpt_best.pt")log(f" β οΈ Please upload manually before shutting down GPU!")# Wait for any remaining background uploads from mid-training saves159 unmodified lines16016116216316416516616716816917017117217375 unmodified lines2492502512522532542552562572582592602612622632642652662672682692702712722732749 unmodified lines28428528628728828929029129241 unmodified lines33433533633733833934034134240 unmodified lines38338438538638738838939029 unmodified lines420421422423424425426427133 unmodified lines5615625635645655665675685695705715725735745755765775785795805815825835 unmodified lines58959059159259359459559637 unmodified lines6346356366376386391 unmodified line64164264364464564664764832 unmodified lines68168268368468568668768810 unmodified lines699700701702703704705706707708709710711712713714159 unmodified linesEMPTY_CACHE_EVERY = 50# SFT-specific hyperparameters (same for all GPUs)MAX_LR = 3e-5 # Increased for 500M adaptationMIN_LR = 1e-6WARMUP_STEPS = 150EPOCHS = 6WEIGHT_DECAY = 0.01GRAD_CLIP = 1.0EVAL_EVERY = 500CKPT_EVERY = 2000# Vocab size: SFT data was tokenized with 250M SFT tokenizer (64003 vocab)# Base model was trained with 64000 vocab75 unmodified linesif n_stripped:log(f" π§ Stripped '_orig_mod.' from {n_stripped} keys (torch.compile artifact)")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].shapemodel_shape = model_state_dict[emb_key].shapeif ckpt_shape != model_shape:log(f" π Resizing '{emb_key}': {list(ckpt_shape)} β {list(model_shape)}")target_device = model_state_dict[emb_key].deviceckpt_weight = stripped[emb_key].to(target_device)new_weight = model_state_dict[emb_key].clone()min_vocab = min(ckpt_shape[0], model_shape[0])new_weight[:min_vocab] = ckpt_weight[:min_vocab]# Smart initialization: copy the mean embedding to new special tokensif model_shape[0] > ckpt_shape[0]:log(f" π§ Smart init for new {model_shape[0] - ckpt_shape[0]} tokens (using mean embedding)")mean_emb = ckpt_weight[:min_vocab].mean(dim=0)for i in range(min_vocab, model_shape[0]):new_weight[i] = mean_embstripped[emb_key] = new_weight.to("cpu")return stripped9 unmodified lines"""if not IS_MAIN:returnckpt_dir = f"{WORK}/sft_checkpoints"os.makedirs(ckpt_dir, exist_ok=True)path = f"{ckpt_dir}/{filename}"raw_model = model.module if hasattr(model, "module") else modelif hasattr(raw_model, '_orig_mod'):raw_model = raw_model._orig_mod41 unmodified lines"""if not IS_MAIN:returnckpt_dir = f"{WORK}/sft_checkpoints"os.makedirs(ckpt_dir, exist_ok=True)path = f"{ckpt_dir}/sft_ckpt_best.pt"raw_model = model.module if hasattr(model, "module") else modelif hasattr(raw_model, '_orig_mod'):raw_model = raw_model._orig_mod40 unmodified linesremapped = remap_checkpoint_keys(ckpt["model"], raw_model.state_dict())raw_model.load_state_dict(remapped)raw_model.head.weight = raw_model.tok_emb.weightlog(" π Re-tied head.weight with tok_emb.weight")if "optimizer" in ckpt:try:29 unmodified linesremapped = remap_checkpoint_keys(ckpt["model"], raw_model.state_dict())raw_model.load_state_dict(remapped)raw_model.head.weight = raw_model.tok_emb.weightlog(" π Re-tied head.weight with tok_emb.weight")pretrain_step = ckpt.get("step", "?")pretrain_loss = ckpt.get("val_loss", -1)133 unmodified linesrng = random.Random(1337 + rank)val_rng = random.Random(999)# Optional cap on training steps, read from environment variable.# Set MAX_TRAIN_STEPS in the shell/notebook before running to do a# limited test run (e.g. "2000"). Leave unset for full training# (runs all steps for EPOCHS as originally planned)._max_steps_env = os.environ.get("MAX_TRAIN_STEPS")MAX_TRAIN_STEPS = int(_max_steps_env) if _max_steps_env else NoneTOTAL_STEPS = max(1, (len(train_ds) // effective_batch) * EPOCHS)end_step = TOTAL_STEPSif MAX_TRAIN_STEPS is not None:end_step = min(end_step, start_step + MAX_TRAIN_STEPS)TOTAL_NEW_STEPS = max(1, end_step - start_step)log(f"π Total SFT steps for {EPOCHS} epochs (full plan): {TOTAL_STEPS}")if MAX_TRAIN_STEPS is not None:log(f" β οΈ MAX_TRAIN_STEPS cap active: {MAX_TRAIN_STEPS}")log(f" Resumed from step: {start_step} | This run will go to: {end_step}")log(f" Training: step {start_step} β {end_step}")# ============================================================================5 unmodified linesreturn Nonemodel.eval()losses = []for _ in range(20):x, y = get_sft_batch(val_ds, MICRO_BATCH, val_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())37 unmodified linesaccum_loss += loss.item()del x, y, loss# NaN/Inf protectionif not math.isfinite(accum_loss):if IS_MAIN:1 unmodified lineoptimizer.zero_grad(set_to_none=True)continuetorch.nn.utils.clip_grad_norm_(model.parameters(), GRAD_CLIP)optimizer.step()# ---- Logging (every 10 steps) ----32 unmodified lines# ---- Save latest checkpoint (background upload) ----if step > start_step and step % CKPT_EVERY == 0:dist.barrier()if IS_MAIN:wait_for_uploads()save_checkpoint(model, optimizer, step,val_loss if val_loss is not None else -1,"sft_ckpt_latest.pt", blocking=False)10 unmodified lines"sft_ckpt_latest.pt", blocking=True)# Upload best checkpoint at the very end (only once, saves GPU time)if IS_MAIN and os.path.exists(f"{WORK}/sft_checkpoints/sft_ckpt_best.pt"):log(f" βοΈ Uploading best checkpoint to HF (blocking, please wait)...")try:with_retry(api.upload_file, path_or_fileobj=f"{WORK}/sft_checkpoints/sft_ckpt_best.pt",path_in_repo="sft_checkpoints/sft_ckpt_best.pt",repo_id=MAIN_REPO, repo_type="model", token=HF_TOKEN)log(f" β Best checkpoint uploaded to HF!")except Exception as e:log(f" β Best checkpoint upload failed: {e}")log(f" β οΈ File saved locally at: {WORK}/sft_checkpoints/sft_ckpt_best.pt")log(f" β οΈ Please upload manually before shutting down GPU!")# Wait for any remaining background uploads from mid-training saves
code/model.py+4-1
code/train_sft.py+49-20