Upload 2 files
Browse filesFiles changed (2)
- code/model.py+4-1
- code/train_sft.py+49-20
138 unmodified lines139140141142142143144145146147148138 unmodified lines
for 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) 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 lines16016116216316316416516616516616716816917016917017117217375 unmodified lines2492502512522522532542552562572582592602612612622622632642652662672682692702712722732749 unmodified lines28428528628728827828929029129241 unmodified lines33433533633733832633934034134240 unmodified lines38338438538638738838939029 unmodified lines420421422423424425426427133 unmodified lines5615625635475645655665675685695705715725735745755765515525775785795805815825835 unmodified lines58959059156459256659359459559637 unmodified lines6346356366106116376386391 unmodified line64164264364464564664764832 unmodified lines68168268368468568668768810 unmodified lines699700701673702703704676705706707708709710682711712713714159 unmodified lines EMPTY_CACHE_EVERY = 50
# SFT-specific hyperparameters (same for all GPUs)MAX_LR = 1e-5 # Very small LR to preserve base knowledgeMAX_LR = 3e-5 # Increased for 500M adaptationMIN_LR = 1e-6WARMUP_STEPS = 50EPOCHS = 3WARMUP_STEPS = 150EPOCHS = 6WEIGHT_DECAY = 0.01GRAD_CLIP = 1.0EVAL_EVERY = 1000CKPT_EVERY = 5000EVAL_EVERY = 500CKPT_EVERY = 2000
# Vocab size: SFT data was tokenized with 250M SFT tokenizer (64003 vocab)# Base model was trained with 64000 vocab75 unmodified lines 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)}") target_device = model_state_dict[emb_key].device ckpt_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] = stripped[emb_key][:min_vocab] stripped[emb_key] = new_weight new_weight[:min_vocab] = ckpt_weight[:min_vocab] # Smart initialization: copy the mean embedding to new special tokens if 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_emb stripped[emb_key] = new_weight.to("cpu")
return stripped
9 unmodified lines """ if not IS_MAIN: return ckpt_dir = f"{WORK}/sft_checkpoints" os.makedirs(ckpt_dir, exist_ok=True) path = f"{WORK}/{filename}" path = f"{ckpt_dir}/{filename}" raw_model = model.module if hasattr(model, "module") else model if hasattr(raw_model, '_orig_mod'): raw_model = raw_model._orig_mod41 unmodified lines """ if not IS_MAIN: return ckpt_dir = f"{WORK}/sft_checkpoints" os.makedirs(ckpt_dir, exist_ok=True) path = f"{WORK}/sft_ckpt_best.pt" path = f"{ckpt_dir}/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_mod40 unmodified lines remapped = remap_checkpoint_keys(ckpt["model"], raw_model.state_dict()) raw_model.load_state_dict(remapped) raw_model.head.weight = raw_model.tok_emb.weight log(" π Re-tied head.weight with tok_emb.weight") if "optimizer" in ckpt: try:29 unmodified lines remapped = remap_checkpoint_keys(ckpt["model"], raw_model.state_dict()) raw_model.load_state_dict(remapped) raw_model.head.weight = raw_model.tok_emb.weight log(" π 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)
TOTAL_STEPS = (len(train_ds) // (MICRO_BATCH * GRAD_ACCUM * world_size)) * EPOCHS# 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 None
TOTAL_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: {TOTAL_STEPS}")log(f" Resumed from step: {start_step} | Remaining: {TOTAL_NEW_STEPS}")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 lines 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) 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 lines 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:1 unmodified line optimizer.zero_grad(set_to_none=True) continue
torch.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_ckpt_best.pt"):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_ckpt_best.pt", 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_ckpt_best.pt") 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 savescode/model.py+4-1
code/train_sft.py+49-20