Fix sm_120 compatibility & unwrap model on single GPU
Browse files56 unmodified lines57585960616263140 unmodified lines20420520620720820921021121267 unmodified lines280281282283284285286287288289290291292293127 unmodified lines42142242342442542642742842943043143243343414 unmodified lines44945045145245345445545645745845946046146246346446546646746846914 unmodified lines48448548648748848949070 unmodified lines56156256356456556656756856957057157257357457557657757857956 unmodified linescreate_repo(CKPT_REPO, repo_type="model", token=HF_TOKEN, exist_ok=True, private=True)hf_hub_download(MODEL_REPO, f"{CODE_SUBFOLDER}/config.py", local_dir=WORK, token=HF_TOKEN)hf_hub_download(MODEL_REPO, f"{CODE_SUBFOLDER}/model.py", local_dir=WORK, token=HF_TOKEN)dist.barrier()sys.path.insert(0, f"{WORK}/{CODE_SUBFOLDER}")from config import ViuAIConfig140 unmodified linesself.preload()return x, ydef extract_clean_state_dict(model):"""Safely extracts state dict removing DDP and compile prefixes."""raw_model = model.module if hasattr(model, "module") else modelstate_dict = raw_model.state_dict()# Remove _orig_mod. prefix if present (from torch.compile)return {k.replace("_orig_mod.", ""): v for k, v in state_dict.items()}67 unmodified lineslog(f"No checkpoint found on HF — starting fresh. ({type(e).__name__})")# Step 2: Synchronize all processes so file is 100% written to diskdist.barrier()# Step 3: Now all ranks safely read the downloaded file from local diskif os.path.exists(ckpt_path):try:ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)raw_model = model.module if hasattr(model, "module") else modeltarget = raw_model._orig_mod if hasattr(raw_model, "_orig_mod") else raw_modelstate_dict = ckpt["model"]ckpt_vocab = state_dict["tok_emb.weight"].shape[0]127 unmodified linesif USE_COMPILE:model = torch.compile(model)model = DDP(model, device_ids=[local_rank])optimizer = torch.optim.AdamW(model.parameters(), lr=MAX_LR, weight_decay=WEIGHT_DECAY, betas=(0.9, 0.95), fused=True)start_step = load_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()files = api.list_repo_files(DATA_REPO, repo_type="dataset")# Prioritize new v2 shards if present, fallback to v114 unmodified linesPOOL_SIZE = int(os.environ.get("POOL_SIZE", "5" if mem_gb > 70 else "3"))shard_pool = ShardPool(train_shards, DATA_REPO, HF_TOKEN, f"{WORK}/train_shards_r{rank}", seed=rank + start_step, start_cursor=start_shard_idx, pool_size=POOL_SIZE)val_tokens = load_val_tokens(val_shards, DATA_REPO, HF_TOKEN, f"{WORK}/val_shards") if IS_MAIN else Nonedist.barrier() # Synchronize so Rank 1 doesn't desync while Rank 0 downloads validation tokens@torch.no_grad()def evaluate():if not IS_MAIN:return Nonemodel.eval()losses = []for _ in range(50):x, y = get_batch(val_tokens, 4, CONTEXT_LEN)with torch.autocast(device_type="cuda", dtype=AMP_DTYPE):unwrapped = model.module._orig_mod if hasattr(model.module, '_orig_mod') else model.module_, loss = unwrapped(x, y)losses.append(loss.item())model.train()return sum(losses) / len(losses)model.train()14 unmodified linesaccum_loss = 0.0for micro_i in range(GRAD_ACCUM):x, y = prefetcher.next()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 = model(x, y)70 unmodified lines# optimizer, step, val_loss, "ckpt_best.pt")if step > start_step and step % SAVE_EVERY == 0:dist.barrier()if IS_MAIN:# Save latest checkpoint (with optimizer, 5GB)save_checkpoint(model.module._orig_mod if hasattr(model.module, '_orig_mod') else model.module,optimizer, step, val_loss if val_loss is not None else -1, "ckpt_latest.pt")dist.barrier()final_val = evaluate()if IS_MAIN:wait_for_uploads()save_checkpoint(model.module._orig_mod if hasattr(model.module, '_orig_mod') else model.module,optimizer, end_step, final_val if final_val is not None else -1, "ckpt_latest.pt", blocking=True)if IS_MAIN:log(f"\n500M Training complete! Final val_loss: {final_val if final_val is not None else -1:.4f}")dist.destroy_process_group()56 unmodified lines5758596061626364140 unmodified lines20520620720820921021121221321421521621721821922022122267 unmodified lines290291292293294295296297298299300301302303127 unmodified lines43143243343443543643743843944044144244344444544614 unmodified lines46146246346446546646746846947047147247347447547647747847948048148214 unmodified lines49749849950050150250370 unmodified lines57457557657757857958058158258358458558658758858959059159259356 unmodified linescreate_repo(CKPT_REPO, repo_type="model", token=HF_TOKEN, exist_ok=True, private=True)hf_hub_download(MODEL_REPO, f"{CODE_SUBFOLDER}/config.py", local_dir=WORK, token=HF_TOKEN)hf_hub_download(MODEL_REPO, f"{CODE_SUBFOLDER}/model.py", local_dir=WORK, token=HF_TOKEN)if world_size > 1:dist.barrier()sys.path.insert(0, f"{WORK}/{CODE_SUBFOLDER}")from config import ViuAIConfig140 unmodified linesself.preload()return x, ydef unwrap_model(m):"""Safely unwrap model whether wrapped in DDP, torch.compile, or both."""while hasattr(m, "module") or hasattr(m, "_orig_mod"):if hasattr(m, "module"):m = m.moduleelif hasattr(m, "_orig_mod"):m = m._orig_modreturn mdef extract_clean_state_dict(model):"""Safely extracts state dict removing DDP and compile prefixes."""raw_model = unwrap_model(model)state_dict = raw_model.state_dict()# Remove _orig_mod. prefix if present (from torch.compile)return {k.replace("_orig_mod.", ""): v for k, v in state_dict.items()}67 unmodified lineslog(f"No checkpoint found on HF — starting fresh. ({type(e).__name__})")# Step 2: Synchronize all processes so file is 100% written to diskif world_size > 1:dist.barrier()# Step 3: Now all ranks safely read the downloaded file from local diskif os.path.exists(ckpt_path):try:ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)target = unwrap_model(model)state_dict = ckpt["model"]ckpt_vocab = state_dict["tok_emb.weight"].shape[0]127 unmodified linesif USE_COMPILE:model = torch.compile(model)if world_size > 1:model = DDP(model, device_ids=[local_rank])optimizer = torch.optim.AdamW(model.parameters(), lr=MAX_LR, weight_decay=WEIGHT_DECAY, betas=(0.9, 0.95), fused=True)start_step = load_checkpoint(model, optimizer)if world_size > 1:start_step_t = torch.tensor([start_step], device=DEVICE)dist.broadcast(start_step_t, src=0)start_step = start_step_t.item()files = api.list_repo_files(DATA_REPO, repo_type="dataset")# Prioritize new v2 shards if present, fallback to v114 unmodified linesPOOL_SIZE = int(os.environ.get("POOL_SIZE", "5" if mem_gb > 70 else "3"))shard_pool = ShardPool(train_shards, DATA_REPO, HF_TOKEN, f"{WORK}/train_shards_r{rank}", seed=rank + start_step, start_cursor=start_shard_idx, pool_size=POOL_SIZE)val_tokens = load_val_tokens(val_shards, DATA_REPO, HF_TOKEN, f"{WORK}/val_shards") if IS_MAIN else Noneif world_size > 1:dist.barrier() # Synchronize so other ranks don't desync while Rank 0 downloads validation tokens@torch.no_grad()def evaluate():if not IS_MAIN:return Noneraw_model = unwrap_model(model)raw_model.eval()losses = []for _ in range(50):x, y = get_batch(val_tokens, 4, CONTEXT_LEN)with torch.autocast(device_type="cuda", dtype=AMP_DTYPE):_, loss = raw_model(x, y)losses.append(loss.item())raw_model.train()return sum(losses) / len(losses)model.train()14 unmodified linesaccum_loss = 0.0for micro_i in range(GRAD_ACCUM):x, y = prefetcher.next()sync_ctx = model.no_sync() if (world_size > 1 and micro_i < GRAD_ACCUM - 1) else contextlib.nullcontext()with sync_ctx:with torch.autocast(device_type="cuda", dtype=AMP_DTYPE):_, loss = model(x, y)70 unmodified lines# optimizer, step, val_loss, "ckpt_best.pt")if step > start_step and step % SAVE_EVERY == 0:if world_size > 1:dist.barrier()if IS_MAIN:# Save latest checkpoint (with optimizer, 5GB)save_checkpoint(unwrap_model(model), optimizer, step, val_loss if val_loss is not None else -1, "ckpt_latest.pt")if world_size > 1:dist.barrier()final_val = evaluate()if IS_MAIN:wait_for_uploads()save_checkpoint(unwrap_model(model), optimizer, end_step, final_val if final_val is not None else -1, "ckpt_latest.pt", blocking=True)if IS_MAIN:log(f"\n500M Training complete! Final val_loss: {final_val if final_val is not None else -1:.4f}")if dist.is_initialized():dist.destroy_process_group()
code/train.py+36-22