Upload train_sft.py
Browse files12 unmodified lines1314151617181920212223242526272829236 unmodified lines2662672682592692702712722732742752762772785 unmodified lines2842852862872882722892902912922932942952772962972792802812822982993003013023033043053063073083093103113123133143153163172853183193203213223233243253264 unmodified lines331332333334335297298299300301302303304305306307336337338339340341342343344345346347348349350300 unmodified lines65165265361465465565665765861965966066166266366466566666766866962867067167267367467567667767867968068168268368468568668768868969012 unmodified linesimport osos.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
# Redirect HF cache to working directory (rental GPUs often have tiny OS partitions)# This prevents "No space left on device" errors during checkpoint uploadif os.path.exists("/kaggle/working"): os.environ.setdefault("HF_HOME", "/kaggle/working/hf_cache")else: os.environ.setdefault("HF_HOME", "./working/hf_cache")
import json, math, time, random, sys, contextlib, gc, threading
# Global list to track all background upload threads_upload_threads = []import numpy as npimport torchimport torch.nn as nn236 unmodified lines# ============================================================================# 9. Checkpoint Save / Load# ============================================================================def save_checkpoint(model, optimizer, step, val_loss, filename):def save_checkpoint(model, optimizer, step, val_loss, filename, blocking=False): """Save checkpoint locally + upload to HF in background. Args: blocking: If True, upload synchronously (used for final save). If False, upload in background thread (used during training). """ if not IS_MAIN: return path = f"{WORK}/{filename}"5 unmodified lines
torch.save({"model": clean_dict, "optimizer": optimizer.state_dict(), "step": step, "val_loss": val_loss}, path) log(f" 💾 Checkpoint saved locally @ step {step}, val_loss={val_loss:.4f}")
def _bg_upload(): if blocking: # Synchronous upload (for final save — must complete before exit) log(f" ☁️ Uploading {filename} to HF (blocking, please wait)...") try: 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" ☁️ [Background upload complete for {filename} @ step {step}]") log(f" ✅ Upload complete for {filename} @ step {step}") except Exception as e: log(f" ❌ [Background upload failed for {filename}: {e}]")
threading.Thread(target=_bg_upload, daemon=True).start() log(f" [sft checkpoint saved locally @ step {step}, val_loss={val_loss:.4f}] (uploading in background...)") log(f" ❌ Upload FAILED for {filename}: {e}") log(f" ⚠️ File is still saved locally at: {path}") log(f" ⚠️ Please upload manually before shutting down GPU!") else: # Background upload (for mid-training saves — doesn't block GPU) def _bg_upload(): try: 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" ☁️ [Background upload complete for {filename} @ step {step}]") except Exception as e: log(f" ❌ [Background upload failed for {filename}: {e}]")
t = threading.Thread(target=_bg_upload, daemon=False) # daemon=False: won't be killed on exit t.start() _upload_threads.append(t) log(f" ☁️ Uploading {filename} in background...")
def save_best_checkpoint(model, step, val_loss): """Save best SFT model separately (no optimizer, smaller file).""" """Save best SFT model locally only (no HF upload). Like pretraining: just saves locally and logs val_loss. Final upload happens at the end or manually. This avoids wasting GPU time on repeated uploads. """ if not IS_MAIN: return path = f"{WORK}/sft_ckpt_best.pt"4 unmodified lines 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) log(f" ✨ New best! val_loss={val_loss:.4f} @ step {step} (saved locally)")
def _bg_upload(): try: 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" ☁️ [Background upload complete for best checkpoint @ step {step}]") except Exception as e: log(f" ❌ [Background upload failed for best checkpoint: {e}]")
threading.Thread(target=_bg_upload, daemon=True).start() log(f" ✨ Best SFT checkpoint saved locally @ step {step}, val_loss={val_loss:.4f} (uploading in background...)")def wait_for_uploads(): """Wait for ALL background uploads to finish before exiting.""" if not _upload_threads: return log(f"\n⏳ Waiting for {len(_upload_threads)} background upload(s) to complete...") for i, t in enumerate(_upload_threads): t.join(timeout=600) # Wait up to 10 minutes per upload if t.is_alive(): log(f" ⚠️ Upload thread {i+1} timed out after 10 minutes!") else: log(f" ✅ Upload {i+1}/{len(_upload_threads)} complete.") log(f"✅ All background uploads finished.")
def load_sft_checkpoint(model, optimizer): """Load checkpoint: tries SFT first, then falls back to base pretrained."""300 unmodified lines best_val_loss = val_loss save_best_checkpoint(model, step, val_loss)
# ---- Save latest checkpoint ---- # ---- 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") "sft_ckpt_latest.pt", blocking=False)
# ============================================================================# 18. Final Save & Cleanup# ============================================================================dist.barrier()final_val = evaluate()
# Final save: BLOCKING (synchronous) — must complete before program exitssave_checkpoint(model, optimizer, end_step, final_val if final_val is not None else -1, "sft_ckpt_latest.pt") "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 savesif IS_MAIN: wait_for_uploads()
if IS_MAIN: log(f"\n{'='*60}")code/train_sft.py+81-22