Upload code/train.py with huggingface_hub
Browse files215 unmodified lines21621721821922022122222322422522694 unmodified lines32132232332432532632732832933033133233333493 unmodified lines4284294304314324334344354364374384394407 unmodified lines448449450451452453454455456139 unmodified lines596597598599600601602603604605606607608609215 unmodified linest.join()_upload_threads.clear()def save_checkpoint(model, optimizer, step, val_loss, filename, blocking=False):if not IS_MAIN:returnstate_dict = extract_clean_state_dict(model)data = {"model": state_dict, "step": step, "val_loss": val_loss}# 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 linesstep = ckpt.get("step", 40000)val_loss = ckpt.get("val_loss", 0.0)log(f"✅ Successfully loaded Step {step} weights (val_loss={val_loss:.4f})! Continuing pretraining from Step {step}.")return stepexcept Exception as e:log(f"⚠️ Error reading local checkpoint: {e} — starting fresh.")return 0else:log("No checkpoint found — starting fresh from step 0.")return 0def 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)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 v17 unmodified linesval_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!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)")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 linesdist.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}")215 unmodified lines21621721821922022122222322422522622722894 unmodified lines32332432532632732832933033133233333433533633793 unmodified lines4314324334344354364374384394404414424434444454464474484494504514524534544554564574587 unmodified lines466467468469470471472473474475476477478139 unmodified lines618619620621622623624625626627628629630631215 unmodified linest.join()_upload_threads.clear()def save_checkpoint(model, optimizer, step, val_loss, filename, blocking=False, shard_cursor=None):if not IS_MAIN:returnstate_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 linesstep = 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, shard_cursorexcept Exception as e:log(f"⚠️ Error reading local checkpoint: {e} — starting fresh.")return 0, Noneelse:log("No checkpoint found — starting fresh from step 0.")return 0, Nonedef 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)decay_params = []no_decay_params = []for name, param in model.named_parameters():if not param.requires_grad:continueif 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, saved_cursor = load_checkpoint(model, optimizer)if world_size > 1: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 Nonefiles = api.list_repo_files(DATA_REPO, repo_type="dataset")# Prioritize new v2 shards if present, fallback to v17 unmodified linesval_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 = start_stepstart_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 linesdist.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", 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, 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