import os import time import math import numpy as np import torch import bitsandbytes as bnb from huggingface_hub import HfApi from model import B24GPT, Config # --------------------------------------------------------------------------- # Config — adjust batch_size/grad_accum after the first real test run once we # see actual T4 memory usage (Step 5). These are conservative starting points # for a 1B model, much smaller than your 152M run's batch=8. # --------------------------------------------------------------------------- config = Config() batch_size = 2 # sequences per forward pass — small on purpose, 1B is heavy grad_accum = 16 # effective batch = batch_size * grad_accum = 32 sequences max_steps = 20000 # placeholder — retune once data_prep.py confirms total tokens lr = 3e-4 warmup_steps = 500 min_lr = 1e-5 eval_interval = 250 ckpt_interval = 250 data_dir = "data" # expects data/train.bin and data/val.bin (uint16 tokens) repo_id = "Brighton233j/Joy_1b" hf_token = os.environ.get("HF_TOKEN") device = "cuda" if torch.cuda.is_available() else "cpu" # --------------------------------------------------------------------------- # Data loading — memory-mapped so we never load the whole .bin file into RAM, # just the random windows we sample each step. Same pattern as your 152M run. # --------------------------------------------------------------------------- def get_batch(split): path = os.path.join(data_dir, f"{split}.bin") data = np.memmap(path, dtype=np.uint16, mode="r") ix = torch.randint(len(data) - config.block_size, (batch_size,)) x = torch.stack([torch.from_numpy(data[i:i+config.block_size].astype(np.int64)) for i in ix]) y = torch.stack([torch.from_numpy(data[i+1:i+1+config.block_size].astype(np.int64)) for i in ix]) return x.to(device), y.to(device) # --------------------------------------------------------------------------- # LR schedule — same warmup + cosine decay shape as your 152M run # --------------------------------------------------------------------------- def get_lr(step): if step < warmup_steps: return lr * step / warmup_steps progress = (step - warmup_steps) / max(1, max_steps - warmup_steps) return min_lr + 0.5 * (lr - min_lr) * (1 + math.cos(math.pi * progress)) # --------------------------------------------------------------------------- # Model + optimizer # --------------------------------------------------------------------------- model = B24GPT(config).to(device) # 8-bit Adam (bitsandbytes) — cuts optimizer state memory ~4x vs standard # fp32 Adam. Essential at 1B params on a 16GB T4. optimizer = bnb.optim.Adam8bit(model.parameters(), lr=lr) # fp16 mixed precision — GradScaler prevents gradient underflow that plain # fp16 (without scaling) would otherwise cause. scaler = torch.cuda.amp.GradScaler() start_step = 0 # --------------------------------------------------------------------------- # Resume logic — same as your 152M run: local checkpoint first, else pull # latest.pt from HF and resume from there # --------------------------------------------------------------------------- ckpt_dir = "ckpt" os.makedirs(ckpt_dir, exist_ok=True) local_ckpt = os.path.join(ckpt_dir, "latest.pt") if os.path.exists(local_ckpt): print(f"[resume] loading local checkpoint {local_ckpt}") ckpt = torch.load(local_ckpt, map_location=device) model.load_state_dict(ckpt["model"]) optimizer.load_state_dict(ckpt["optimizer"]) start_step = ckpt["step"] else: try: from huggingface_hub import hf_hub_download print("[resume] no local checkpoint, trying HF...") path = hf_hub_download(repo_id=repo_id, filename="latest.pt", token=hf_token) ckpt = torch.load(path, map_location=device) model.load_state_dict(ckpt["model"]) optimizer.load_state_dict(ckpt["optimizer"]) start_step = ckpt["step"] print(f"[resume] resumed from HF at step {start_step}") except Exception as e: print(f"[resume] no checkpoint found anywhere, starting fresh ({e})") api = HfApi() def save_and_push(step): torch.save({ "model": model.state_dict(), "optimizer": optimizer.state_dict(), "step": step, "model_args": { "vocab_size": config.vocab_size, "n_layer": config.n_layer, "n_head": config.n_head, "n_embd": config.n_embd, "block_size": config.block_size, }, }, local_ckpt) print(f"[checkpoint saved locally] step {step}") api.upload_file( path_or_fileobj=local_ckpt, path_in_repo="latest.pt", repo_id=repo_id, token=hf_token, ) print(f"[checkpoint pushed to HF] step {step} -> {repo_id}") @torch.no_grad() def evaluate(): model.eval() x, y = get_batch("val") with torch.autocast(device_type="cuda", dtype=torch.float16): _, loss = model(x, y) model.train() return loss.item() # --------------------------------------------------------------------------- # Training loop # --------------------------------------------------------------------------- model.train() t0 = time.time() for step in range(start_step, max_steps): current_lr = get_lr(step) for g in optimizer.param_groups: g["lr"] = current_lr optimizer.zero_grad(set_to_none=True) total_loss = 0.0 for micro_step in range(grad_accum): x, y = get_batch("train") with torch.autocast(device_type="cuda", dtype=torch.float16): _, loss = model(x, y) loss = loss / grad_accum scaler.scale(loss).backward() total_loss += loss.item() scaler.step(optimizer) scaler.update() if step % 50 == 0: elapsed = time.time() - t0 print(f"step {step:5d} | loss {total_loss:.4f} | lr {current_lr:.2e} | {elapsed:.1f}s elapsed") if step % eval_interval == 0 and step > 0: val_loss = evaluate() print(f"[eval] step {step} | val_loss {val_loss:.4f}") if step % ckpt_interval == 0 and step > 0: save_and_push(step) save_and_push(max_steps) print("Training complete.")