Upload code/train.py with huggingface_hub
Browse files215 unmodified lines21621721821921922022122222322422522622722894 unmodified lines32332432532632732532832933032833133233333133433533633793 unmodified lines4314324334314344354364374384394404414424434444454464474484494334504514354364374524534544554564574587 unmodified lines466467468469470471472451452453473474475476477478139 unmodified lines618619620599621622623624625626627606628629630631215 unmodified lines t.join() _upload_threads.clear()
def save_checkpoint(model, optimizer, step, val_loss, filename, blocking=False):def save_checkpoint(model, optimizer, step, val_loss, filename, blocking=False, shard_cursor=None): if not IS_MAIN: return state_dict = extract_clean_state_dict(model) data = {"model": state_dict, "step": step, "val_loss": val_loss} if shard_cursor is not None: data["shard_cursor"] = shard_cursor # Save optimizer only for latest checkpoint to keep best checkpoint small (1GB vs 5GB) if filename == "ckpt_latest.pt" and optimizer is not None:94 unmodified lines
step = ckpt.get("step", 40000) val_loss = ckpt.get("val_loss", 0.0) shard_cursor = ckpt.get("shard_cursor", None) log(f"✅ Successfully loaded Step {step} weights (val_loss={val_loss:.4f})! Continuing pretraining from Step {step}.") return step return step, shard_cursor except Exception as e: log(f"⚠️ Error reading local checkpoint: {e} — starting fresh.") return 0 return 0, None else: log("No checkpoint found — starting fresh from step 0.") return 0 return 0, None
def get_lr(step, warmup, total, max_lr, min_lr): if step < warmup:93 unmodified linesif world_size > 1: model = DDP(model, device_ids=[local_rank], gradient_as_bucket_view=True)
optimizer = torch.optim.AdamW(model.parameters(), lr=MAX_LR, weight_decay=WEIGHT_DECAY, betas=(0.9, 0.95), fused=True)decay_params = []no_decay_params = []for name, param in model.named_parameters(): if not param.requires_grad: continue if param.ndim < 2 or "norm" in name.lower() or "bias" in name.lower() or "tok_emb" in name.lower(): no_decay_params.append(param) else: decay_params.append(param)
optimizer_grouped_parameters = [ {"params": decay_params, "weight_decay": WEIGHT_DECAY}, {"params": no_decay_params, "weight_decay": 0.0}]optimizer = torch.optim.AdamW(optimizer_grouped_parameters, lr=MAX_LR, betas=(0.9, 0.95), eps=1e-8, fused=True)
start_step = load_checkpoint(model, optimizer)start_step, saved_cursor = 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() sync_t = torch.tensor([start_step, -1 if saved_cursor is None else saved_cursor], device=DEVICE) dist.broadcast(sync_t, src=0) start_step = sync_t[0].item() saved_cursor = sync_t[1].item() if sync_t[1].item() >= 0 else None
files = api.list_repo_files(DATA_REPO, repo_type="dataset")# Prioritize new v2 shards if present, fallback to v17 unmodified lines val_shards = sorted(f for f in files if f.startswith("shards/") and f.endswith("_val.bin"))
# Compute deterministic starting shard so resuming NEVER repeats old shards!if saved_cursor is not None: start_shard_idx = saved_cursor % max(1, len(train_shards)) log(f"🎯 Step {start_step}: Resuming at exact saved Shard #{start_shard_idx:03d}")else:steps_completed = max(0, start_step - 40000)start_shard_idx = (steps_completed // ROTATE_EVERY) % max(1, len(train_shards))log(f"🎯 Step {start_step}: Resuming at Shard #{start_shard_idx:03d} ({start_shard_idx} shards already consumed, 0 duplicates)") steps_completed = start_step start_shard_idx = (steps_completed // ROTATE_EVERY) % max(1, len(train_shards)) log(f"🎯 Step {start_step}: Resuming at Shard #{start_shard_idx:03d} ({start_shard_idx} shards already consumed, 0 duplicates)")
POOL_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)139 unmodified lines 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") save_checkpoint(unwrap_model(model), optimizer, step, val_loss if val_loss is not None else -1, "ckpt_latest.pt", shard_cursor=shard_pool.cursor)
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) save_checkpoint(unwrap_model(model), optimizer, end_step, final_val if final_val is not None else -1, "ckpt_latest.pt", blocking=True, shard_cursor=shard_pool.cursor)if IS_MAIN: log(f"\n500M Training complete! Final val_loss: {final_val if final_val is not None else -1:.4f}")
code/train.py+36-14