Upload 2 files
Browse files- code/model.py +94 -0
- code/train.py +390 -0
code/model.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
|
| 6 |
+
class RMSNorm(nn.Module):
|
| 7 |
+
def __init__(self, dim, eps=1e-5):
|
| 8 |
+
super().__init__()
|
| 9 |
+
self.w = nn.Parameter(torch.ones(dim))
|
| 10 |
+
self.eps = eps
|
| 11 |
+
|
| 12 |
+
def forward(self, x):
|
| 13 |
+
return (x.float() * torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + self.eps) * self.w).type_as(x)
|
| 14 |
+
|
| 15 |
+
class ResonanceLayerKaggle(nn.Module):
|
| 16 |
+
def __init__(self, d_model=1024, n_heads=16):
|
| 17 |
+
super().__init__()
|
| 18 |
+
self.n_heads = n_heads
|
| 19 |
+
self.head_dim = d_model // n_heads
|
| 20 |
+
self.to_amp = nn.Linear(d_model, d_model, bias=False)
|
| 21 |
+
self.to_freq = nn.Linear(d_model, n_heads, bias=False)
|
| 22 |
+
self.to_phase = nn.Linear(d_model, n_heads, bias=False)
|
| 23 |
+
self.to_v = nn.Linear(d_model, d_model, bias=False)
|
| 24 |
+
self.to_out = nn.Linear(d_model, d_model, bias=False)
|
| 25 |
+
self.norm = RMSNorm(d_model)
|
| 26 |
+
|
| 27 |
+
def forward(self, x):
|
| 28 |
+
B, T, C = x.shape
|
| 29 |
+
h = self.norm(x)
|
| 30 |
+
A = self.to_amp(h).view(B, T, self.n_heads, self.head_dim)
|
| 31 |
+
V = self.to_v(h).view(B, T, self.n_heads, self.head_dim)
|
| 32 |
+
freq = torch.tanh(self.to_freq(h)) * 2.0 # B,T,H
|
| 33 |
+
phase = torch.tanh(self.to_phase(h)) * math.pi
|
| 34 |
+
|
| 35 |
+
# Distance - causal ke liye
|
| 36 |
+
pos = torch.arange(T, device=x.device).float()
|
| 37 |
+
chunk = 512 # safe for Kaggle T4
|
| 38 |
+
out = torch.zeros(B, T, C, device=x.device, dtype=x.dtype)
|
| 39 |
+
|
| 40 |
+
for i in range(0, T, chunk):
|
| 41 |
+
end = min(i+chunk, T)
|
| 42 |
+
phase_i = phase[:, i:end, :].permute(0,2,1).unsqueeze(-1) # B,H,chunk,1
|
| 43 |
+
phase_j = phase.permute(0,2,1).unsqueeze(-2) # B,H,1,T
|
| 44 |
+
|
| 45 |
+
dist = (torch.arange(i, end, device=x.device)[:,None] - pos[None,:]).abs().clamp(min=0)
|
| 46 |
+
dist = dist.view(1, 1, end-i, T)
|
| 47 |
+
|
| 48 |
+
freq_i = freq[:, i:end, :].permute(0,2,1).unsqueeze(-1)
|
| 49 |
+
angle = (phase_i - phase_j) + freq_i * dist * 0.05
|
| 50 |
+
score = torch.cos(angle) / math.sqrt(self.head_dim) # Normalize to prevent explosion
|
| 51 |
+
|
| 52 |
+
causal_mask = (torch.arange(i, end, device=x.device)[:,None] >= pos[None,:]).float().view(1,1,end-i,T)
|
| 53 |
+
score = score * causal_mask
|
| 54 |
+
|
| 55 |
+
amp = A.norm(dim=-1).permute(0,2,1) # B,H,T
|
| 56 |
+
amp_i = amp[:,:,i:end].unsqueeze(-1)
|
| 57 |
+
amp_j = amp.unsqueeze(-2)
|
| 58 |
+
score = score * torch.sigmoid(amp_i * amp_j)
|
| 59 |
+
|
| 60 |
+
V_t = V.permute(0,2,1,3) # B,H,T,D
|
| 61 |
+
Bh = B * self.n_heads
|
| 62 |
+
s = score.reshape(Bh, end-i, T)
|
| 63 |
+
v = V_t.reshape(Bh, T, self.head_dim)
|
| 64 |
+
o = torch.bmm(s, v).view(B, self.n_heads, end-i, self.head_dim).permute(0,2,1,3).reshape(B, end-i, C)
|
| 65 |
+
out[:, i:end] = o
|
| 66 |
+
|
| 67 |
+
return self.to_out(out)
|
| 68 |
+
|
| 69 |
+
class ViuResonance100M(nn.Module):
|
| 70 |
+
def __init__(self, vocab_size=64000, d_model=1024, n_layers=12, n_heads=16, dropout=0.1):
|
| 71 |
+
super().__init__()
|
| 72 |
+
self.emb = nn.Embedding(vocab_size, d_model)
|
| 73 |
+
self.layers = nn.ModuleList([ResonanceLayerKaggle(d_model, n_heads) for _ in range(n_layers)])
|
| 74 |
+
self.norm = RMSNorm(d_model)
|
| 75 |
+
self.head = nn.Linear(d_model, vocab_size, bias=False)
|
| 76 |
+
self.head.weight = self.emb.weight
|
| 77 |
+
self.resid_dropout = nn.Dropout(dropout)
|
| 78 |
+
self.apply(self._init_weights)
|
| 79 |
+
|
| 80 |
+
def _init_weights(self, module):
|
| 81 |
+
if isinstance(module, nn.Linear):
|
| 82 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 83 |
+
elif isinstance(module, nn.Embedding):
|
| 84 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 85 |
+
|
| 86 |
+
def forward(self, idx, targets=None):
|
| 87 |
+
x = self.emb(idx)
|
| 88 |
+
for layer in self.layers:
|
| 89 |
+
x = x + self.resid_dropout(layer(x))
|
| 90 |
+
logits = self.head(self.norm(x))
|
| 91 |
+
loss = None
|
| 92 |
+
if targets is not None:
|
| 93 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-100)
|
| 94 |
+
return logits, loss
|
code/train.py
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
|
| 3 |
+
|
| 4 |
+
import json, math, time, random, sys, contextlib
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
torch.set_float32_matmul_precision('high')
|
| 9 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 10 |
+
torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction = True
|
| 11 |
+
|
| 12 |
+
import torch.distributed as dist
|
| 13 |
+
from torch.nn.parallel import DistributedDataParallel as DDP
|
| 14 |
+
from huggingface_hub import HfApi, hf_hub_download, create_repo, login
|
| 15 |
+
from datetime import timedelta
|
| 16 |
+
|
| 17 |
+
def setup_ddp():
|
| 18 |
+
dist.init_process_group(backend="nccl", timeout=timedelta(minutes=30))
|
| 19 |
+
rank = dist.get_rank()
|
| 20 |
+
local_rank = int(os.environ["LOCAL_RANK"])
|
| 21 |
+
world_size = dist.get_world_size()
|
| 22 |
+
torch.cuda.set_device(local_rank)
|
| 23 |
+
return rank, local_rank, world_size
|
| 24 |
+
|
| 25 |
+
rank, local_rank, world_size = setup_ddp()
|
| 26 |
+
DEVICE = f"cuda:{local_rank}"
|
| 27 |
+
IS_MAIN = rank == 0
|
| 28 |
+
|
| 29 |
+
def log(msg):
|
| 30 |
+
if IS_MAIN:
|
| 31 |
+
print(msg, flush=True)
|
| 32 |
+
|
| 33 |
+
def get_hf_token():
|
| 34 |
+
token = os.environ.get("HF_TOKEN")
|
| 35 |
+
if token:
|
| 36 |
+
return token
|
| 37 |
+
try:
|
| 38 |
+
from kaggle_secrets import UserSecretsClient
|
| 39 |
+
token = UserSecretsClient().get_secret("HF_TOKEN")
|
| 40 |
+
if token:
|
| 41 |
+
return token
|
| 42 |
+
except Exception:
|
| 43 |
+
pass
|
| 44 |
+
raise ValueError("HF_TOKEN environment variable or Kaggle Secret is not set!")
|
| 45 |
+
|
| 46 |
+
HF_TOKEN = get_hf_token()
|
| 47 |
+
login(token=HF_TOKEN)
|
| 48 |
+
api = HfApi(token=HF_TOKEN)
|
| 49 |
+
|
| 50 |
+
from transformers import AutoTokenizer
|
| 51 |
+
|
| 52 |
+
DATA_REPO = "ViuAI/viuai-500m-data"
|
| 53 |
+
MODEL_REPO = "ViuAI/ViuRec"
|
| 54 |
+
TOKENIZER_SUBFOLDER = "tokenizer"
|
| 55 |
+
CODE_SUBFOLDER = "code"
|
| 56 |
+
CKPT_SUBFOLDER = "checkpoints"
|
| 57 |
+
CKPT_REPO = MODEL_REPO
|
| 58 |
+
|
| 59 |
+
def load_tokenizer_robust():
|
| 60 |
+
paths_to_try = [
|
| 61 |
+
"/kaggle/working/ViuRec/tokenizer",
|
| 62 |
+
"/kaggle/input/viuai-500m-tokenizer",
|
| 63 |
+
"./viuai-500m-tokenizer"
|
| 64 |
+
]
|
| 65 |
+
for p in paths_to_try:
|
| 66 |
+
if os.path.exists(os.path.join(p, "vocab.json")):
|
| 67 |
+
try:
|
| 68 |
+
tok = AutoTokenizer.from_pretrained(p)
|
| 69 |
+
if IS_MAIN:
|
| 70 |
+
print(f"✅ Tokenizer loaded from {p}")
|
| 71 |
+
return tok
|
| 72 |
+
except Exception:
|
| 73 |
+
pass
|
| 74 |
+
try:
|
| 75 |
+
tok = AutoTokenizer.from_pretrained(MODEL_REPO, subfolder=TOKENIZER_SUBFOLDER, token=HF_TOKEN)
|
| 76 |
+
if IS_MAIN:
|
| 77 |
+
print(f"✅ Tokenizer loaded from HF ({MODEL_REPO}/{TOKENIZER_SUBFOLDER})")
|
| 78 |
+
return tok
|
| 79 |
+
except Exception as e:
|
| 80 |
+
raise RuntimeError(f"Could not load tokenizer: {e}")
|
| 81 |
+
|
| 82 |
+
tokenizer = load_tokenizer_robust()
|
| 83 |
+
VOCAB_SIZE = len(tokenizer)
|
| 84 |
+
|
| 85 |
+
if IS_MAIN:
|
| 86 |
+
create_repo(CKPT_REPO, repo_type="model", token=HF_TOKEN, exist_ok=True, private=True)
|
| 87 |
+
dist.barrier()
|
| 88 |
+
|
| 89 |
+
if os.path.exists("/kaggle/working"):
|
| 90 |
+
WORK = "/kaggle/working"
|
| 91 |
+
elif os.path.exists("/root/working"):
|
| 92 |
+
WORK = "/root/working"
|
| 93 |
+
else:
|
| 94 |
+
WORK = "./working"
|
| 95 |
+
os.makedirs(WORK, exist_ok=True)
|
| 96 |
+
|
| 97 |
+
sys.path.insert(0, WORK)
|
| 98 |
+
sys.path.insert(0, os.path.join(WORK, CODE_SUBFOLDER))
|
| 99 |
+
hf_hub_download(MODEL_REPO, f"{CODE_SUBFOLDER}/model.py", local_dir=WORK, token=HF_TOKEN)
|
| 100 |
+
from model import ViuResonance100M
|
| 101 |
+
|
| 102 |
+
def with_retry(fn, *args, retries=4, delay=5, **kwargs):
|
| 103 |
+
for attempt in range(1, retries + 1):
|
| 104 |
+
try:
|
| 105 |
+
return fn(*args, **kwargs)
|
| 106 |
+
except Exception as e:
|
| 107 |
+
if "404" in str(e) or "EntryNotFoundError" in type(e).__name__:
|
| 108 |
+
raise
|
| 109 |
+
if attempt == retries:
|
| 110 |
+
raise
|
| 111 |
+
log(f" [retry {attempt}/{retries}] {type(e).__name__}: {e}")
|
| 112 |
+
time.sleep(delay)
|
| 113 |
+
delay *= 2
|
| 114 |
+
|
| 115 |
+
class ShardPool:
|
| 116 |
+
def __init__(self, shard_names, repo_id, token, local_dir, pool_size=3, seed=0):
|
| 117 |
+
self.all_shards = list(shard_names)
|
| 118 |
+
self.rng = random.Random(seed)
|
| 119 |
+
self.rng.shuffle(self.all_shards)
|
| 120 |
+
self.cursor = 0
|
| 121 |
+
self.repo_id, self.token, self.local_dir, self.pool_size = repo_id, token, local_dir, pool_size
|
| 122 |
+
os.makedirs(local_dir, exist_ok=True)
|
| 123 |
+
self.pool = []
|
| 124 |
+
self.fill()
|
| 125 |
+
|
| 126 |
+
def _next_name(self):
|
| 127 |
+
if self.cursor >= len(self.all_shards):
|
| 128 |
+
self.rng.shuffle(self.all_shards)
|
| 129 |
+
self.cursor = 0
|
| 130 |
+
name = self.all_shards[self.cursor]
|
| 131 |
+
self.cursor += 1
|
| 132 |
+
return name
|
| 133 |
+
|
| 134 |
+
def fill(self):
|
| 135 |
+
while len(self.pool) < self.pool_size:
|
| 136 |
+
name = self._next_name()
|
| 137 |
+
path = with_retry(hf_hub_download, self.repo_id, name, repo_type="dataset",
|
| 138 |
+
local_dir=self.local_dir, token=self.token)
|
| 139 |
+
mmap_arr = np.memmap(path, dtype=np.uint16, mode="r")
|
| 140 |
+
if len(mmap_arr) < 2049: # Context length (2048) + 1
|
| 141 |
+
if IS_MAIN:
|
| 142 |
+
print(f"⚠️ Skipping shard {name} as it is too short ({len(mmap_arr)} tokens).")
|
| 143 |
+
continue
|
| 144 |
+
self.pool.append((path, mmap_arr))
|
| 145 |
+
|
| 146 |
+
def rotate_one(self):
|
| 147 |
+
old_path, old_mmap = self.pool.pop(0)
|
| 148 |
+
del old_mmap
|
| 149 |
+
try: os.remove(old_path)
|
| 150 |
+
except OSError: pass
|
| 151 |
+
self.fill()
|
| 152 |
+
|
| 153 |
+
def sample_batch(self, batch_size, ctx_len):
|
| 154 |
+
xs, ys = [], []
|
| 155 |
+
while len(xs) < batch_size:
|
| 156 |
+
_, tokens = self.rng.choice(self.pool)
|
| 157 |
+
max_start = len(tokens) - ctx_len - 1
|
| 158 |
+
if max_start <= 0:
|
| 159 |
+
continue
|
| 160 |
+
i = self.rng.randint(0, max_start)
|
| 161 |
+
xs.append(np.array(tokens[i:i+ctx_len], dtype=np.int64))
|
| 162 |
+
ys.append(np.array(tokens[i+1:i+1+ctx_len], dtype=np.int64))
|
| 163 |
+
return np.stack(xs), np.stack(ys)
|
| 164 |
+
|
| 165 |
+
def load_val_tokens(val_names, repo_id, token, local_dir):
|
| 166 |
+
os.makedirs(local_dir, exist_ok=True)
|
| 167 |
+
arrays = []
|
| 168 |
+
for name in val_names:
|
| 169 |
+
path = with_retry(hf_hub_download, repo_id, name, repo_type="dataset", local_dir=local_dir, token=token)
|
| 170 |
+
arrays.append(np.memmap(path, dtype=np.uint16, mode="r"))
|
| 171 |
+
return np.concatenate(arrays)
|
| 172 |
+
|
| 173 |
+
def get_batch(source, batch_size, ctx_len):
|
| 174 |
+
if isinstance(source, ShardPool):
|
| 175 |
+
x_np, y_np = source.sample_batch(batch_size, ctx_len)
|
| 176 |
+
else:
|
| 177 |
+
i = np.random.randint(0, len(source) - ctx_len - 1, size=batch_size)
|
| 178 |
+
x_np = np.stack([np.array(source[j:j+ctx_len], dtype=np.int64) for j in i])
|
| 179 |
+
y_np = np.stack([np.array(source[j+1:j+1+ctx_len], dtype=np.int64) for j in i])
|
| 180 |
+
x = torch.from_numpy(x_np).to(DEVICE, non_blocking=True)
|
| 181 |
+
y = torch.from_numpy(y_np).to(DEVICE, non_blocking=True)
|
| 182 |
+
return x, y
|
| 183 |
+
|
| 184 |
+
def extract_clean_state_dict(model):
|
| 185 |
+
raw_model = model.module if hasattr(model, "module") else model
|
| 186 |
+
state_dict = raw_model.state_dict()
|
| 187 |
+
return {k.replace("_orig_mod.", ""): v for k, v in state_dict.items()}
|
| 188 |
+
|
| 189 |
+
def save_checkpoint(model, optimizer, step, val_loss, filename):
|
| 190 |
+
if not IS_MAIN:
|
| 191 |
+
return
|
| 192 |
+
path = f"{WORK}/{filename}"
|
| 193 |
+
state_dict = extract_clean_state_dict(model)
|
| 194 |
+
data = {"model": state_dict, "step": step, "val_loss": val_loss}
|
| 195 |
+
|
| 196 |
+
if filename == "ckpt_latest.pt" and optimizer is not None:
|
| 197 |
+
data["optimizer"] = optimizer.state_dict()
|
| 198 |
+
|
| 199 |
+
torch.save(data, path)
|
| 200 |
+
with_retry(api.upload_file, path_or_fileobj=path, path_in_repo=f"{CKPT_SUBFOLDER}/{filename}",
|
| 201 |
+
repo_id=CKPT_REPO, repo_type="model", token=HF_TOKEN)
|
| 202 |
+
log(f" [{filename} saved @ step {step}, val_loss={val_loss:.4f}]")
|
| 203 |
+
|
| 204 |
+
def load_checkpoint(model, optimizer):
|
| 205 |
+
try:
|
| 206 |
+
try:
|
| 207 |
+
path = with_retry(hf_hub_download, CKPT_REPO, f"{CKPT_SUBFOLDER}/ckpt_latest.pt", repo_type="model",
|
| 208 |
+
local_dir=WORK, token=HF_TOKEN, retries=1)
|
| 209 |
+
except Exception as e:
|
| 210 |
+
if "404" in str(e) or "EntryNotFoundError" in type(e).__name__:
|
| 211 |
+
log("No checkpoint found on HF — starting from scratch.")
|
| 212 |
+
return 0
|
| 213 |
+
raise
|
| 214 |
+
|
| 215 |
+
ckpt = torch.load(path, map_location=DEVICE, weights_only=False)
|
| 216 |
+
target = model.module._orig_mod if hasattr(model.module, '_orig_mod') else model.module
|
| 217 |
+
target.load_state_dict(ckpt["model"])
|
| 218 |
+
if optimizer is not None and "optimizer" in ckpt:
|
| 219 |
+
optimizer.load_state_dict(ckpt["optimizer"])
|
| 220 |
+
log(f"Resumed from step {ckpt['step']} (val_loss={ckpt['val_loss']:.4f})")
|
| 221 |
+
return ckpt["step"]
|
| 222 |
+
except Exception as e:
|
| 223 |
+
log(f"Failed to load checkpoint — starting fresh. ({type(e).__name__}: {e})")
|
| 224 |
+
return 0
|
| 225 |
+
|
| 226 |
+
def get_lr(step, warmup, total, max_lr, min_lr):
|
| 227 |
+
if step < warmup:
|
| 228 |
+
return max_lr * (step + 1) / warmup
|
| 229 |
+
if step > total:
|
| 230 |
+
return min_lr
|
| 231 |
+
ratio = (step - warmup) / (total - warmup)
|
| 232 |
+
return min_lr + 0.5 * (1 + math.cos(math.pi * ratio)) * (max_lr - min_lr)
|
| 233 |
+
|
| 234 |
+
# === GPU CONFIG ===
|
| 235 |
+
mem_gb = torch.cuda.get_device_properties(DEVICE).total_memory / (1024**3)
|
| 236 |
+
if mem_gb > 100: # H200
|
| 237 |
+
MICRO_BATCH = 32
|
| 238 |
+
GRAD_ACCUM = 4
|
| 239 |
+
elif mem_gb > 70: # A100
|
| 240 |
+
MICRO_BATCH = 32
|
| 241 |
+
GRAD_ACCUM = 4
|
| 242 |
+
else: # T4 or RTX (15GB/24GB)
|
| 243 |
+
MICRO_BATCH = 2
|
| 244 |
+
GRAD_ACCUM = 16
|
| 245 |
+
|
| 246 |
+
if IS_MAIN:
|
| 247 |
+
print(f"🖥️ Detected GPU with {mem_gb:.1f}GB VRAM -> Auto-Configured: MICRO_BATCH={MICRO_BATCH}, GRAD_ACCUM={GRAD_ACCUM}")
|
| 248 |
+
# ==================
|
| 249 |
+
|
| 250 |
+
CONTEXT_LEN = 2048
|
| 251 |
+
MAX_LR = 3e-4
|
| 252 |
+
MIN_LR = 3e-5
|
| 253 |
+
WARMUP_STEPS = 1000
|
| 254 |
+
TOTAL_STEPS = 40_000
|
| 255 |
+
WEIGHT_DECAY = 0.1
|
| 256 |
+
GRAD_CLIP = 1.0
|
| 257 |
+
MAX_STEPS = int(os.environ.get("MAX_STEPS", TOTAL_STEPS))
|
| 258 |
+
EVAL_EVERY = 500
|
| 259 |
+
SAVE_EVERY = 2000
|
| 260 |
+
ROTATE_EVERY = 500
|
| 261 |
+
|
| 262 |
+
torch.backends.cudnn.benchmark = False
|
| 263 |
+
|
| 264 |
+
# Model 100M init
|
| 265 |
+
model = ViuResonance100M(vocab_size=VOCAB_SIZE, d_model=1024, n_layers=12, n_heads=16).to(DEVICE)
|
| 266 |
+
|
| 267 |
+
if IS_MAIN:
|
| 268 |
+
log(f"Model params: {sum(p.numel() for p in model.parameters())/1e6:.1f}M | world_size={world_size}")
|
| 269 |
+
log("Compiling model (if it fails, will fallback to eager)...")
|
| 270 |
+
|
| 271 |
+
try:
|
| 272 |
+
model = torch.compile(model)
|
| 273 |
+
except Exception as e:
|
| 274 |
+
if IS_MAIN:
|
| 275 |
+
log(f"⚠️ torch.compile failed, falling back to eager mode: {e}")
|
| 276 |
+
model = DDP(model, device_ids=[local_rank])
|
| 277 |
+
|
| 278 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=MAX_LR, weight_decay=WEIGHT_DECAY, betas=(0.9, 0.95), fused=True)
|
| 279 |
+
|
| 280 |
+
start_step = load_checkpoint(model, optimizer)
|
| 281 |
+
start_step_t = torch.tensor([start_step], device=DEVICE)
|
| 282 |
+
dist.broadcast(start_step_t, src=0)
|
| 283 |
+
start_step = start_step_t.item()
|
| 284 |
+
|
| 285 |
+
files = api.list_repo_files(DATA_REPO, repo_type="dataset")
|
| 286 |
+
train_shards = sorted(f for f in files if f.startswith("shards/") and f.endswith(".bin") and "_val" not in f)
|
| 287 |
+
val_shards = sorted(f for f in files if f.startswith("shards/") and f.endswith("_val.bin"))
|
| 288 |
+
|
| 289 |
+
shard_pool = ShardPool(train_shards, DATA_REPO, HF_TOKEN, f"{WORK}/train_shards_r{rank}", seed=rank + start_step)
|
| 290 |
+
val_tokens = load_val_tokens(val_shards, DATA_REPO, HF_TOKEN, f"{WORK}/val_shards") if IS_MAIN else None
|
| 291 |
+
|
| 292 |
+
@torch.no_grad()
|
| 293 |
+
def evaluate():
|
| 294 |
+
if not IS_MAIN:
|
| 295 |
+
return None
|
| 296 |
+
model.eval()
|
| 297 |
+
losses = []
|
| 298 |
+
for _ in range(20):
|
| 299 |
+
x, y = get_batch(val_tokens, 16, CONTEXT_LEN)
|
| 300 |
+
with torch.autocast(device_type="cuda", dtype=torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16):
|
| 301 |
+
unwrapped = model.module._orig_mod if hasattr(model.module, '_orig_mod') else model.module
|
| 302 |
+
_, loss = unwrapped(x, y)
|
| 303 |
+
losses.append(loss.item())
|
| 304 |
+
model.train()
|
| 305 |
+
return sum(losses) / len(losses)
|
| 306 |
+
|
| 307 |
+
model.train()
|
| 308 |
+
val_loss = None
|
| 309 |
+
best_val_loss = None
|
| 310 |
+
ema_tok_s = None
|
| 311 |
+
global_t0 = time.time()
|
| 312 |
+
t0 = time.time()
|
| 313 |
+
end_step = min(start_step + MAX_STEPS, TOTAL_STEPS)
|
| 314 |
+
|
| 315 |
+
for step in range(start_step, end_step):
|
| 316 |
+
lr = get_lr(step, WARMUP_STEPS, TOTAL_STEPS, MAX_LR, MIN_LR)
|
| 317 |
+
for g in optimizer.param_groups:
|
| 318 |
+
g["lr"] = lr
|
| 319 |
+
|
| 320 |
+
optimizer.zero_grad(set_to_none=True)
|
| 321 |
+
accum_loss = 0.0
|
| 322 |
+
for micro_i in range(GRAD_ACCUM):
|
| 323 |
+
x, y = get_batch(shard_pool, MICRO_BATCH, CONTEXT_LEN)
|
| 324 |
+
sync_ctx = model.no_sync() if micro_i < GRAD_ACCUM - 1 else contextlib.nullcontext()
|
| 325 |
+
with sync_ctx:
|
| 326 |
+
with torch.autocast(device_type="cuda", dtype=torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16):
|
| 327 |
+
_, loss = model(x, y)
|
| 328 |
+
loss = loss / GRAD_ACCUM
|
| 329 |
+
loss.backward()
|
| 330 |
+
accum_loss += loss.item()
|
| 331 |
+
del x, y, loss
|
| 332 |
+
|
| 333 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), GRAD_CLIP)
|
| 334 |
+
|
| 335 |
+
if not math.isfinite(accum_loss):
|
| 336 |
+
if IS_MAIN:
|
| 337 |
+
log(f"⚠️ NaN/Inf loss at step {step}! Skipping optimizer step.")
|
| 338 |
+
optimizer.zero_grad(set_to_none=True)
|
| 339 |
+
continue
|
| 340 |
+
|
| 341 |
+
optimizer.step()
|
| 342 |
+
|
| 343 |
+
if IS_MAIN and step % 10 == 0:
|
| 344 |
+
if step == start_step:
|
| 345 |
+
t0 = time.time()
|
| 346 |
+
mem_alloc = torch.cuda.memory_allocated(DEVICE) / 1e9
|
| 347 |
+
mem_reserved = torch.cuda.memory_reserved(DEVICE) / 1e9
|
| 348 |
+
log(f"step {step:5d}/{end_step} | loss {accum_loss:.4f} | lr {lr:.2e} | Calibrating speed... | "
|
| 349 |
+
f"mem alloc={mem_alloc:.2f}GB reserved={mem_reserved:.2f}GB")
|
| 350 |
+
else:
|
| 351 |
+
dt = time.time() - t0
|
| 352 |
+
tok_s = (MICRO_BATCH * GRAD_ACCUM * CONTEXT_LEN * world_size * 10) / dt if dt > 0 else 0
|
| 353 |
+
ema_tok_s = tok_s if ema_tok_s is None else 0.7 * ema_tok_s + 0.3 * tok_s
|
| 354 |
+
t0 = time.time()
|
| 355 |
+
mem_alloc = torch.cuda.memory_allocated(DEVICE) / 1e9
|
| 356 |
+
mem_reserved = torch.cuda.memory_reserved(DEVICE) / 1e9
|
| 357 |
+
steps_done = step - start_step
|
| 358 |
+
if steps_done > 0:
|
| 359 |
+
elapsed = time.time() - global_t0
|
| 360 |
+
eta_s = elapsed / steps_done * (end_step - step)
|
| 361 |
+
eta_str = f"{eta_s/60:.0f}min" if eta_s < 3600 else f"{eta_s/3600:.1f}hr"
|
| 362 |
+
else:
|
| 363 |
+
eta_str = "..."
|
| 364 |
+
log(f"step {step:5d}/{end_step} | loss {accum_loss:.4f} | lr {lr:.2e} | {ema_tok_s:.0f} tok/s | "
|
| 365 |
+
f"ETA {eta_str} | mem alloc={mem_alloc:.2f}GB reserved={mem_reserved:.2f}GB")
|
| 366 |
+
|
| 367 |
+
if step > start_step and step % ROTATE_EVERY == 0:
|
| 368 |
+
shard_pool.rotate_one()
|
| 369 |
+
|
| 370 |
+
if step > start_step and step % EVAL_EVERY == 0:
|
| 371 |
+
val_loss = evaluate()
|
| 372 |
+
if IS_MAIN and val_loss is not None:
|
| 373 |
+
log(f"step {step} | val_loss {val_loss:.4f}")
|
| 374 |
+
if best_val_loss is None or val_loss < best_val_loss:
|
| 375 |
+
best_val_loss = val_loss
|
| 376 |
+
|
| 377 |
+
if step > start_step and step % SAVE_EVERY == 0:
|
| 378 |
+
dist.barrier()
|
| 379 |
+
if IS_MAIN:
|
| 380 |
+
save_checkpoint(model.module._orig_mod if hasattr(model.module, '_orig_mod') else model.module,
|
| 381 |
+
optimizer, step, val_loss if val_loss is not None else -1, "ckpt_latest.pt")
|
| 382 |
+
|
| 383 |
+
dist.barrier()
|
| 384 |
+
final_val = evaluate()
|
| 385 |
+
if IS_MAIN:
|
| 386 |
+
save_checkpoint(model.module._orig_mod if hasattr(model.module, '_orig_mod') else model.module,
|
| 387 |
+
optimizer, end_step, final_val if final_val is not None else -1, "ckpt_latest.pt")
|
| 388 |
+
log(f"\n100M Training complete! Final val_loss: {final_val if final_val is not None else -1:.4f}")
|
| 389 |
+
|
| 390 |
+
dist.destroy_process_group()
|