Upload 4 files
Browse filesFiles changed (3)
- code/model.py+251-221
- code/train.py+3-3
- code/train_sft.py+933-747
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221import mathimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch.utils.checkpoint import checkpointfrom config import ViuAIConfigclass RMSNorm(nn.Module):def __init__(self, dim, eps=1e-5):super().__init__()self.eps = epsself.weight = nn.Parameter(torch.ones(dim))def forward(self, x):x_fp32 = x.float()norm = x_fp32 * torch.rsqrt(x_fp32.pow(2).mean(-1, keepdim=True) + self.eps)return (norm * self.weight.float()).type_as(x)def precompute_rope(head_dim, max_len, theta=10000.0, device="cpu"):freqs = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim))t = torch.arange(max_len, device=device).float()freqs = torch.outer(t, freqs)return torch.cos(freqs), torch.sin(freqs)def apply_rope(x, cos, sin):cos = cos.to(x.dtype)sin = sin.to(x.dtype)x1, x2 = x[..., ::2], x[..., 1::2]# x is [B, n_heads, T, head_dim]# cos, sin are [max_len, head_dim//2]T = x.size(2)cos = cos[:T][None, None, :, :]sin = sin[:T][None, None, :, :]rotated = torch.stack([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1)return rotated.flatten(-2)class Attention(nn.Module):def __init__(self, cfg: ViuAIConfig):super().__init__()self.n_heads = cfg.n_headsself.n_kv_heads = cfg.n_kv_headsself.head_dim = cfg.d_model // cfg.n_headsself.n_rep = self.n_heads // self.n_kv_headsself.q_proj = nn.Linear(cfg.d_model, cfg.n_heads * self.head_dim, bias=False)self.k_proj = nn.Linear(cfg.d_model, cfg.n_kv_heads * self.head_dim, bias=False)self.v_proj = nn.Linear(cfg.d_model, cfg.n_kv_heads * self.head_dim, bias=False)self.o_proj = nn.Linear(cfg.n_heads * self.head_dim, cfg.d_model, bias=False)self.o_proj._is_residual = True # flag for depth-scaled initself.q_norm = RMSNorm(self.head_dim, cfg.norm_eps)self.k_norm = RMSNorm(self.head_dim, cfg.norm_eps)self.attn_dropout = cfg.attn_dropoutdef forward(self, x, cos, sin, attn_mask=None):B, T, C = x.shapeq = self.q_proj(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2)k = self.k_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)v = self.v_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)q, k = self.q_norm(q), self.k_norm(k)q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)dropout_p = self.attn_dropout if self.training else 0.0if attn_mask is not None:out = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, dropout_p=dropout_p, enable_gqa=True)else:out = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=dropout_p, enable_gqa=True)out = out.transpose(1, 2).contiguous().view(B, T, -1)return self.o_proj(out)class SwiGLU(nn.Module):def __init__(self, cfg: ViuAIConfig):super().__init__()self.gate_proj = nn.Linear(cfg.d_model, cfg.ffn_hidden, bias=False)self.up_proj = nn.Linear(cfg.d_model, cfg.ffn_hidden, bias=False)self.down_proj = nn.Linear(cfg.ffn_hidden, cfg.d_model, bias=False)self.down_proj._is_residual = True # flag for depth-scaled initdef forward(self, x):return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))class Block(nn.Module):def __init__(self, cfg: ViuAIConfig):super().__init__()self.attn_norm = RMSNorm(cfg.d_model, cfg.norm_eps)self.attn = Attention(cfg)self.ffn_norm = RMSNorm(cfg.d_model, cfg.norm_eps)self.ffn = SwiGLU(cfg)self.resid_dropout = nn.Dropout(cfg.resid_dropout) if cfg.resid_dropout > 0 else nn.Identity()def forward(self, x, cos, sin, attn_mask=None):x = x + self.resid_dropout(self.attn(self.attn_norm(x), cos, sin, attn_mask))x = x + self.resid_dropout(self.ffn(self.ffn_norm(x)))return xclass ViuAI(nn.Module):def __init__(self, cfg: ViuAIConfig):super().__init__()self.cfg = cfgself.tok_emb = nn.Embedding(cfg.vocab_size, cfg.d_model)self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg.n_layers)])self.final_norm = RMSNorm(cfg.d_model, cfg.norm_eps)self.head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)self.head.weight = self.tok_emb.weighthead_dim = cfg.d_model // cfg.n_headscos, sin = precompute_rope(head_dim, cfg.context_length, cfg.rope_theta)self.register_buffer("rope_cos", cos, persistent=False)self.register_buffer("rope_sin", sin, persistent=False)self.apply(self._init_weights)def _init_weights(self, module):if isinstance(module, nn.Linear):# Skip the tied output head — shares weight with tok_embif hasattr(self, 'head') and module is self.head:returnstd = 0.02# Depth-scaled init for residual projections (o_proj, down_proj)if getattr(module, '_is_residual', False):std *= (2 * self.cfg.n_layers) ** -0.5nn.init.normal_(module.weight, mean=0.0, std=std)elif isinstance(module, nn.Embedding):nn.init.normal_(module.weight, mean=0.0, std=0.02)def forward(self, idx, targets=None, pad_id=None):B, T = idx.shapex = self.tok_emb(idx)cos = self.rope_cos.to(x.device)sin = self.rope_sin.to(x.device)attn_mask = Noneif pad_id is not None:causal = torch.tril(torch.ones(T, T, dtype=torch.bool, device=x.device))key_mask = (idx != pad_id).unsqueeze(1).unsqueeze(2) # [B,1,1,T] mask key-side padattn_mask = causal.unsqueeze(0).unsqueeze(0) & key_maskfor block in self.blocks:if self.training and self.cfg.use_checkpoint:if attn_mask is not None:x = checkpoint(block, x, cos, sin, attn_mask, use_reentrant=False)else:x = checkpoint(block, x, cos, sin, use_reentrant=False)else:x = block(x, cos, sin, attn_mask)x = self.final_norm(x)logits = self.head(x)loss = Noneif targets is not None:# SHIFT BUG FIXED: Data is already shifted in dataloader (y = tokens[i+1 : ...])# So logits and targets match 1-to-1 here. No need to shift again.loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-100)# z-loss: stabilizes logit magnitudes during pretraining; disable for SFT (z_loss_weight=0)if self.cfg.z_loss_weight > 0:z_loss = self.cfg.z_loss_weight * (torch.logsumexp(logits, dim=-1) ** 2).mean()loss = loss + z_lossreturn logits, lossdef num_params(self):"""Count parameters, deduplicating tied weights."""seen = set()total = 0for p in self.parameters():if p.data_ptr() not in seen:seen.add(p.data_ptr())total += p.numel()return total@torch.no_grad()def generate(self, idx, max_new_tokens, temperature=1.0, top_k=50, top_p=0.9,eos_token_id=None, repetition_penalty=1.0):self.eval()for _ in range(max_new_tokens):# Crop to context windowidx_cond = idx if idx.size(1) <= self.cfg.context_length else idx[:, -self.cfg.context_length:]logits, _ = self(idx_cond)logits = logits[:, -1, :] # only last position# Repetition penaltyif repetition_penalty != 1.0:for b in range(idx.size(0)):prev_tokens = idx[b].unique()score = logits[b, prev_tokens]logits[b, prev_tokens] = torch.where(score > 0, score / repetition_penalty, score * repetition_penalty)# Temperature scalinglogits = logits / max(temperature, 1e-8)# Top-k filteringif top_k > 0:top_k_val = min(top_k, logits.size(-1))kth_vals, _ = torch.topk(logits, top_k_val)logits[logits < kth_vals[:, [-1]]] = float('-inf')# Top-p (nucleus) filteringif top_p < 1.0:sorted_logits, sorted_indices = torch.sort(logits, descending=True)cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)sorted_indices_to_remove = cumulative_probs > top_psorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()sorted_indices_to_remove[..., 0] = Falseindices_to_remove = torch.zeros_like(logits, dtype=torch.bool).scatter_(1, sorted_indices, sorted_indices_to_remove)logits[indices_to_remove] = float('-inf')probs = F.softmax(logits, dim=-1)idx_next = torch.multinomial(probs, num_samples=1)idx = torch.cat([idx, idx_next], dim=1)# Stop on EOSif eos_token_id is not None and (idx_next == eos_token_id).all():breakreturn idx123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251import mathimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch.utils.checkpoint import checkpointfrom config import ViuAIConfigclass RMSNorm(nn.Module):def __init__(self, dim, eps=1e-5):super().__init__()self.eps = epsself.weight = nn.Parameter(torch.ones(dim))def forward(self, x):x_fp32 = x.float()norm = x_fp32 * torch.rsqrt(x_fp32.pow(2).mean(-1, keepdim=True) + self.eps)return (norm * self.weight.float()).type_as(x)def precompute_rope(head_dim, max_len, theta=10000.0, device="cpu"):freqs = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim))t = torch.arange(max_len, device=device).float()freqs = torch.outer(t, freqs)return torch.cos(freqs), torch.sin(freqs)def apply_rope(x, cos, sin):cos = cos.to(x.dtype)sin = sin.to(x.dtype)x1, x2 = x[..., ::2], x[..., 1::2]# x is [B, n_heads, T, head_dim]# cos, sin are [max_len, head_dim//2]T = x.size(2)cos = cos[:T][None, None, :, :]sin = sin[:T][None, None, :, :]rotated = torch.stack([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1)return rotated.flatten(-2)def repeat_kv(x, n_rep):if n_rep == 1:return xB, H, T, D = x.shapereturn x[:, :, None, :, :].expand(B, H, n_rep, T, D).reshape(B, H * n_rep, T, D)class Attention(nn.Module):def __init__(self, cfg: ViuAIConfig):super().__init__()self.n_heads = cfg.n_headsself.n_kv_heads = cfg.n_kv_headsself.head_dim = cfg.d_model // cfg.n_headsself.n_rep = self.n_heads // self.n_kv_headsself.q_proj = nn.Linear(cfg.d_model, cfg.n_heads * self.head_dim, bias=False)self.k_proj = nn.Linear(cfg.d_model, cfg.n_kv_heads * self.head_dim, bias=False)self.v_proj = nn.Linear(cfg.d_model, cfg.n_kv_heads * self.head_dim, bias=False)self.o_proj = nn.Linear(cfg.n_heads * self.head_dim, cfg.d_model, bias=False)self.o_proj._is_residual = True # flag for depth-scaled initself.q_norm = RMSNorm(self.head_dim, cfg.norm_eps)self.k_norm = RMSNorm(self.head_dim, cfg.norm_eps)self.attn_dropout = cfg.attn_dropoutdef forward(self, x, cos, sin, attn_mask=None):B, T, C = x.shapeq = self.q_proj(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2)k = self.k_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)v = self.v_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)q, k = self.q_norm(q), self.k_norm(k)q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)dropout_p = self.attn_dropout if self.training else 0.0try:if attn_mask is not None:out = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, dropout_p=dropout_p, enable_gqa=True)else:out = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=dropout_p, enable_gqa=True)except TypeError:if self.n_rep > 1:k = repeat_kv(k, self.n_rep)v = repeat_kv(v, self.n_rep)if attn_mask is not None:out = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, dropout_p=dropout_p)else:out = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=dropout_p)out = out.transpose(1, 2).contiguous().view(B, T, -1)return self.o_proj(out)class SwiGLU(nn.Module):def __init__(self, cfg: ViuAIConfig):super().__init__()self.gate_proj = nn.Linear(cfg.d_model, cfg.ffn_hidden, bias=False)self.up_proj = nn.Linear(cfg.d_model, cfg.ffn_hidden, bias=False)self.down_proj = nn.Linear(cfg.ffn_hidden, cfg.d_model, bias=False)self.down_proj._is_residual = True # flag for depth-scaled initdef forward(self, x):return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))class Block(nn.Module):def __init__(self, cfg: ViuAIConfig):super().__init__()self.attn_norm = RMSNorm(cfg.d_model, cfg.norm_eps)self.attn = Attention(cfg)self.ffn_norm = RMSNorm(cfg.d_model, cfg.norm_eps)self.ffn = SwiGLU(cfg)self.resid_dropout = nn.Dropout(cfg.resid_dropout) if cfg.resid_dropout > 0 else nn.Identity()def forward(self, x, cos, sin, attn_mask=None):x = x + self.resid_dropout(self.attn(self.attn_norm(x), cos, sin, attn_mask))x = x + self.resid_dropout(self.ffn(self.ffn_norm(x)))return xclass ViuAI(nn.Module):def __init__(self, cfg: ViuAIConfig):super().__init__()assert cfg.d_model % cfg.n_heads == 0, "d_model must be divisible by n_heads"assert cfg.n_heads % cfg.n_kv_heads == 0, "n_heads must be divisible by n_kv_heads"assert (cfg.d_model // cfg.n_heads) % 2 == 0, "head_dim must be even for RoPE"self.cfg = cfgself.tok_emb = nn.Embedding(cfg.vocab_size, cfg.d_model)self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg.n_layers)])self.final_norm = RMSNorm(cfg.d_model, cfg.norm_eps)self.head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False)self.head.weight = self.tok_emb.weighthead_dim = cfg.d_model // cfg.n_headscos, sin = precompute_rope(head_dim, cfg.context_length, cfg.rope_theta)self.register_buffer("rope_cos", cos, persistent=False)self.register_buffer("rope_sin", sin, persistent=False)self.apply(self._init_weights)def _init_weights(self, module):if isinstance(module, nn.Linear):# Skip the tied output head — shares weight with tok_embif hasattr(self, 'head') and module is self.head:returnstd = 0.02# Depth-scaled init for residual projections (o_proj, down_proj)if getattr(module, '_is_residual', False):std *= (2 * self.cfg.n_layers) ** -0.5nn.init.normal_(module.weight, mean=0.0, std=std)elif isinstance(module, nn.Embedding):nn.init.normal_(module.weight, mean=0.0, std=0.02)def forward(self, idx, targets=None, pad_id=None):B, T = idx.shapeassert T <= self.cfg.context_length, f"Sequence length {T} exceeds context_length {self.cfg.context_length}"x = self.tok_emb(idx)cos = self.rope_cos.to(x.device)sin = self.rope_sin.to(x.device)attn_mask = Noneif pad_id is not None:causal = torch.tril(torch.ones(T, T, dtype=torch.bool, device=x.device))key_mask = (idx != pad_id).unsqueeze(1).unsqueeze(2) # [B,1,1,T] mask key-side padattn_mask = causal.unsqueeze(0).unsqueeze(0) & key_maskfor block in self.blocks:if self.training and self.cfg.use_checkpoint:if attn_mask is not None:x = checkpoint(block, x, cos, sin, attn_mask, use_reentrant=False)else:x = checkpoint(block, x, cos, sin, use_reentrant=False)else:x = block(x, cos, sin, attn_mask)x = self.final_norm(x)logits = self.head(x)loss = Noneif targets is not None:# SHIFT BUG FIXED: Data is already shifted in dataloader (y = tokens[i+1 : ...])# So logits and targets match 1-to-1 here. No need to shift again.loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-100)# z-loss: stabilizes logit magnitudes during pretraining; disable for SFT (z_loss_weight=0)if self.cfg.z_loss_weight > 0:z_loss = self.cfg.z_loss_weight * (torch.logsumexp(logits, dim=-1) ** 2).mean()loss = loss + z_lossreturn logits, lossdef num_params(self):"""Count parameters, deduplicating tied weights."""seen = set()total = 0for p in self.parameters():if p.data_ptr() not in seen:seen.add(p.data_ptr())total += p.numel()return total@torch.no_grad()def generate(self, idx, max_new_tokens, temperature=1.0, top_k=50, top_p=0.9,eos_token_id=None, repetition_penalty=1.0):self.eval()idx = idx.to(next(self.parameters()).device)for _ in range(max_new_tokens):# Crop to context windowidx_cond = idx if idx.size(1) <= self.cfg.context_length else idx[:, -self.cfg.context_length:]logits, _ = self(idx_cond)logits = logits[:, -1, :] # only last position# Repetition penaltyif repetition_penalty != 1.0:for b in range(idx.size(0)):prev_tokens = idx[b].unique()score = logits[b, prev_tokens]logits[b, prev_tokens] = torch.where(score > 0, score / repetition_penalty, score * repetition_penalty)if temperature <= 0:idx_next = logits.argmax(dim=-1, keepdim=True)idx = torch.cat([idx, idx_next], dim=1)if eos_token_id is not None and (idx_next == eos_token_id).all():breakcontinue# Temperature scalinglogits = logits / max(temperature, 1e-8)if not torch.isfinite(logits).any():logits = torch.zeros_like(logits)# Top-k filteringif top_k > 0:top_k_val = min(top_k, logits.size(-1))kth_vals, _ = torch.topk(logits, top_k_val)logits[logits < kth_vals[:, [-1]]] = float('-inf')# Top-p (nucleus) filteringif top_p < 1.0:sorted_logits, sorted_indices = torch.sort(logits, descending=True)cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)sorted_indices_to_remove = cumulative_probs > top_psorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()sorted_indices_to_remove[..., 0] = Falseindices_to_remove = torch.zeros_like(logits, dtype=torch.bool).scatter_(1, sorted_indices, sorted_indices_to_remove)logits[indices_to_remove] = float('-inf')probs = F.softmax(logits, dim=-1)idx_next = torch.multinomial(probs, num_samples=1)idx = torch.cat([idx, idx_next], dim=1)# Stop on EOSif eos_token_id is not None and (idx_next == eos_token_id).all():breakreturn idx
189 unmodified lines190191192193194195196197198199189 unmodified linesEMPTY_CACHE_EVERY = 500USE_CHECKPOINT = Falseelif mem_gb > 70: # A100 (80GB) or RTX 6000 Ada (96GB)MICRO_BATCH = 32GRAD_ACCUM = 4EMPTY_CACHE_EVERY = 250USE_CHECKPOINT = Trueelif mem_gb > 28: # 32GB GPUs (e.g. V100 32GB)MICRO_BATCH = 16GRAD_ACCUM = 8189 unmodified lines190191192193194195196197198199189 unmodified linesEMPTY_CACHE_EVERY = 500USE_CHECKPOINT = Falseelif mem_gb > 70: # A100 (80GB) or RTX 6000 Ada (96GB)MICRO_BATCH = 16GRAD_ACCUM = 8EMPTY_CACHE_EVERY = 250USE_CHECKPOINT = Falseelif mem_gb > 28: # 32GB GPUs (e.g. V100 32GB)MICRO_BATCH = 16GRAD_ACCUM = 8
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747# ============================================================================# ViuAI 500M — Supervised Fine-Tuning (SFT) Script# ============================================================================# Universal script: works on H200(140GB), 5090(32GB), L4(24GB), T4x2(16GBx2)# Works on: Kaggle, Rental GPU, Any cloud provider## Run commands:# Kaggle T4x2: torchrun --nproc_per_node=2 train_sft.py# Single GPU: torchrun --nproc_per_node=1 train_sft.py# Multi-GPU: torchrun --nproc_per_node=<N> train_sft.py# ============================================================================import osos.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"# Redirect HF cache to working directory (rental GPUs often have tiny OS partitions)# This prevents "No space left on device" errors during checkpoint uploadif os.path.exists("/kaggle/working"):os.environ.setdefault("HF_HOME", "/kaggle/working/hf_cache")else:os.environ.setdefault("HF_HOME", "./working/hf_cache")import json, math, time, random, sys, contextlib, gc, threading# Global list to track all background upload threads_upload_threads = []import numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as Fimport torch.distributed as distfrom torch.nn.parallel import DistributedDataParallel as DDPfrom huggingface_hub import HfApi, hf_hub_download, create_repo, loginfrom datetime import timedelta# ============================================================================# 1. DDP Setup (works for single GPU too via torchrun --nproc_per_node=1)# ============================================================================def setup_ddp():dist.init_process_group(backend="nccl", timeout=timedelta(minutes=30))rank = dist.get_rank()local_rank = int(os.environ.get("LOCAL_RANK", 0))world_size = dist.get_world_size()torch.cuda.set_device(local_rank)return rank, local_rank, world_sizerank, local_rank, world_size = setup_ddp()DEVICE = f"cuda:{local_rank}"IS_MAIN = rank == 0def log(msg):if IS_MAIN:print(msg, flush=True)# ============================================================================# 2. Authentication (Kaggle + Rental GPU dono support)# ============================================================================HF_TOKEN = os.environ.get("HF_TOKEN")if not HF_TOKEN:try:from kaggle_secrets import UserSecretsClientHF_TOKEN = UserSecretsClient().get_secret("HF_TOKEN")os.environ["HF_TOKEN"] = HF_TOKENexcept Exception:passif not HF_TOKEN:raise RuntimeError("HF_TOKEN not found!\n"" Kaggle: Settings → Secrets → Add HF_TOKEN\n"" Rental GPU: export HF_TOKEN='hf_your_token'")login(token=HF_TOKEN)api = HfApi(token=HF_TOKEN)# ============================================================================# 3. Repository Configuration# ============================================================================MAIN_REPO = "ViuAI/ViuAI-500M" # Base model + SFT checkpointsSFT_DATA_REPO = "ViuAI/viuai-250m-sft-tokenized" # Pre-tokenized SFT dataif IS_MAIN:create_repo(MAIN_REPO, repo_type="model", token=HF_TOKEN, exist_ok=True, private=True)dist.barrier()# ============================================================================# 4. Working Directory (auto-detect environment)# ============================================================================if os.path.exists("/kaggle/working"):WORK = "/kaggle/working"elif os.path.exists("/root/working"):WORK = "/root/working"else:WORK = "./working"os.makedirs(WORK, exist_ok=True)os.makedirs(f"{WORK}/code", exist_ok=True)sys.path.insert(0, f"{WORK}/code")# ============================================================================# 5. Download Model Code from HuggingFace# ============================================================================def with_retry(fn, *args, retries=4, delay=5, **kwargs):for attempt in range(1, retries + 1):try:return fn(*args, **kwargs)except Exception as e:if "404" in str(e) or "EntryNotFoundError" in type(e).__name__:raiseif attempt == retries:raiselog(f" [retry {attempt}/{retries}] {type(e).__name__}: {e}")time.sleep(delay)delay *= 2if IS_MAIN:log("📥 Downloading model code...")hf_hub_download(MAIN_REPO, "code/config.py", local_dir=WORK, token=HF_TOKEN)hf_hub_download(MAIN_REPO, "code/model.py", local_dir=WORK, token=HF_TOKEN)dist.barrier()from config import ViuAIConfigfrom model import ViuAI# ============================================================================# 6. GPU Auto-Detection & Hyperparameters# ============================================================================mem_gb = torch.cuda.get_device_properties(local_rank).total_memory / 1e9gpu_name = torch.cuda.get_device_name(local_rank)# Check if GPU supports bfloat16 (Ampere+ architecture, compute capability >= 8.0)compute_cap = torch.cuda.get_device_capability(local_rank)supports_bf16 = compute_cap[0] >= 8 # Ampere (8.0), Hopper (9.0) etc.if mem_gb >= 70: # H200 (140GB), H100 (80GB), A100 (80GB)MICRO_BATCH = 16GRAD_ACCUM = 2CONTEXT_LEN = 2048AMP_DTYPE = torch.bfloat16USE_COMPILE = TrueEMPTY_CACHE_EVERY = 500elif mem_gb >= 28: # RTX 5090 (32GB), A10G (24GB but reported higher)MICRO_BATCH = 16 # increased from 2 -> 16, now feasible since# we're on a 32GB RTX 5090 instead of a 15.6GB# Kaggle T4. Matches the proven working 250M# config exactly.# NOTE: If this causes a CUDA out-of-memory# (OOM) error (500M has ~2x the parameters of# 250M, so may need more headroom), fall back# to MICRO_BATCH=8, GRAD_ACCUM=8 instead# (keeps the same effective batch size of 64).GRAD_ACCUM = 4 # reverted from 8 -> 4, matches 250M's proven# config. Effective batch size = 16 x 4 = 64# (same as the working 250M run).CONTEXT_LEN = 1024 # unchangedAMP_DTYPE = torch.bfloat16USE_COMPILE = TrueEMPTY_CACHE_EVERY = 200elif mem_gb >= 20: # L4 (24GB), RTX 4090 (24GB)MICRO_BATCH = 4GRAD_ACCUM = 8CONTEXT_LEN = 2048AMP_DTYPE = torch.bfloat16 if supports_bf16 else torch.float16USE_COMPILE = supports_bf16 # Only compile on Ampere+EMPTY_CACHE_EVERY = 100else: # T4 (16GB), RTX 3060 (12GB)MICRO_BATCH = 2 # unchanged — limited by T4 GPU VRAM (15.6GB)GRAD_ACCUM = 16 # increased from 8 → 16, to raise effective# batch size from 32 to 64 (matches the# proven-stable 250M SFT run's effective batch,# reduces gradient noise)CONTEXT_LEN = 1024 # unchangedAMP_DTYPE = torch.float16 # T4 does NOT support bfloat16USE_COMPILE = False # T4 Turing has poor torch.compile supportEMPTY_CACHE_EVERY = 50# SFT-specific hyperparameters (same for all GPUs)MAX_LR = 1e-05 # reverted from 3e-05 back to 1e-05 — this is# the PROVEN value from the working 250M run;# 3e-05 combined with our smaller batch size# caused training instability and garbage outputMIN_LR = 1e-06 # unchangedWARMUP_STEPS = 50 # reverted from 150 → 50, matching the working# 250M run (no longer need extra-long warmup# since LR is back to a gentler, proven value)EPOCHS = 4 # reduced from 6 → 4 (250M used 3 successfully;# we keep slightly more since 500M has more# parameters to adapt, but avoid excessive# total training time)WEIGHT_DECAY = 0.01GRAD_CLIP = 1.0EVAL_EVERY = 500CKPT_EVERY = 2000# Vocab size: SFT data was tokenized with 250M SFT tokenizer (64003 vocab)# Base model was trained with 64000 vocab# We use 64003 to match the SFT data; embedding resize handles the mismatchSFT_VOCAB_SIZE = 64003effective_batch = MICRO_BATCH * GRAD_ACCUM * world_sizelog(f"{'='*60}")log(f"🖥️ GPU: {gpu_name} | VRAM: {mem_gb:.1f}GB | Compute: {compute_cap[0]}.{compute_cap[1]}")log(f"⚙️ MICRO_BATCH={MICRO_BATCH} | GRAD_ACCUM={GRAD_ACCUM} | CTX={CONTEXT_LEN}")log(f"⚙️ AMP={AMP_DTYPE} | torch.compile={'ON' if USE_COMPILE else 'OFF'}")log(f"⚙️ Effective Batch Size: {effective_batch} | GPUs: {world_size}")log(f"⚙️ LR: {MAX_LR} → {MIN_LR} | Epochs: {EPOCHS}")log(f"{'='*60}")torch.backends.cudnn.benchmark = Truetorch.backends.cuda.matmul.allow_tf32 = True# ============================================================================# 7. SFT Dataset (Pre-tokenized .npy with -100 label masking)# ============================================================================# Labels have -100 on user-turn tokens → loss is ONLY on assistant responses.# input_ids and labels are at SAME alignment (no shift in the data files).# The shift is handled in compute_sft_loss() below.class NpySFTDataset:def __init__(self, ids_path, labels_path, offsets_path, ctx_len):self.ids = np.load(ids_path, mmap_mode='r')self.labels = np.load(labels_path, mmap_mode='r')self.offsets = np.load(offsets_path)self.ctx_len = ctx_lendef __len__(self):return len(self.offsets)def get(self, idx):start = int(self.offsets[idx])end = int(self.offsets[idx + 1]) if idx + 1 < len(self.offsets) else len(self.ids)length = min(end - start, self.ctx_len)input_ids = np.zeros(self.ctx_len, dtype=np.int64)labels = np.full(self.ctx_len, -100, dtype=np.int64)input_ids[:length] = self.ids[start:start + length].astype(np.int64)labels[:length] = self.labels[start:start + length].astype(np.int64)return input_ids, labelsdef get_sft_batch(dataset, batch_size, rng):batch_ids, batch_labels = [], []for _ in range(batch_size):idx = rng.randrange(len(dataset))ids, labels = dataset.get(idx)batch_ids.append(ids)batch_labels.append(labels)x = torch.from_numpy(np.stack(batch_ids)).pin_memory().to(DEVICE, non_blocking=True)y = torch.from_numpy(np.stack(batch_labels)).pin_memory().to(DEVICE, non_blocking=True)return x, y# ============================================================================# 8. Checkpoint Key Remapping (handles torch.compile prefix + vocab resize)# ============================================================================def remap_checkpoint_keys(ckpt_state_dict, model_state_dict):"""Remap checkpoint keys to match current model.Handles:1. torch.compile prefix: _orig_mod.X → X2. Vocab size mismatch: resize tok_emb.weight and head.weight"""model_keys = set(model_state_dict.keys())# Step 1: Strip '_orig_mod.' prefix (from torch.compile during pretraining)stripped = {}n_stripped = 0for key, value in ckpt_state_dict.items():if key.startswith("_orig_mod."):stripped[key[len("_orig_mod."):]] = valuen_stripped += 1else:stripped[key] = valueif n_stripped:log(f" 🔧 Stripped '_orig_mod.' from {n_stripped} keys (torch.compile artifact)")for emb_key in ["tok_emb.weight", "head.weight"]:if emb_key in stripped and emb_key in model_state_dict:ckpt_shape = stripped[emb_key].shapemodel_shape = model_state_dict[emb_key].shapeif ckpt_shape != model_shape:log(f" 📐 Resizing '{emb_key}': {list(ckpt_shape)} → {list(model_shape)}")target_device = model_state_dict[emb_key].deviceckpt_weight = stripped[emb_key].to(target_device)new_weight = model_state_dict[emb_key].clone()min_vocab = min(ckpt_shape[0], model_shape[0])new_weight[:min_vocab] = ckpt_weight[:min_vocab]# Smart initialization: copy the mean embedding to new special tokensif model_shape[0] > ckpt_shape[0]:log(f" 🧠 Smart init for new {model_shape[0] - ckpt_shape[0]} tokens (using mean embedding)")mean_emb = ckpt_weight[:min_vocab].mean(dim=0)for i in range(min_vocab, model_shape[0]):new_weight[i] = mean_embstripped[emb_key] = new_weight.to("cpu")return stripped# ============================================================================# 9. Checkpoint Save / Load# ============================================================================def save_checkpoint(model, optimizer, step, val_loss, filename, blocking=False):"""Save checkpoint locally + upload to HF in background.Args:blocking: If True, upload synchronously (used for final save).If False, upload in background thread (used during training)."""if not IS_MAIN:returnckpt_dir = f"{WORK}/sft_checkpoints"os.makedirs(ckpt_dir, exist_ok=True)path = f"{ckpt_dir}/{filename}"raw_model = model.module if hasattr(model, "module") else modelif hasattr(raw_model, '_orig_mod'):raw_model = raw_model._orig_modstate_dict = raw_model.state_dict()clean_dict = {k.replace("_orig_mod.", ""): v for k, v in state_dict.items()}torch.save({"model": clean_dict, "optimizer": optimizer.state_dict(),"step": step, "val_loss": val_loss}, path)log(f" 💾 Checkpoint saved locally @ step {step}, val_loss={val_loss:.4f}")if blocking:# Synchronous upload (for final save — must complete before exit)log(f" ☁️ Uploading {filename} to HF (blocking, please wait)...")try:with_retry(api.upload_file, path_or_fileobj=path,path_in_repo=f"sft_checkpoints/{filename}",repo_id=MAIN_REPO, repo_type="model", token=HF_TOKEN)log(f" ✅ Upload complete for {filename} @ step {step}")except Exception as e:log(f" ❌ Upload FAILED for {filename}: {e}")log(f" ⚠️ File is still saved locally at: {path}")log(f" ⚠️ Please upload manually before shutting down GPU!")else:# Background upload (for mid-training saves — doesn't block GPU)def _bg_upload():try:with_retry(api.upload_file, path_or_fileobj=path,path_in_repo=f"sft_checkpoints/{filename}",repo_id=MAIN_REPO, repo_type="model", token=HF_TOKEN)log(f" ☁️ [Background upload complete for {filename} @ step {step}]")except Exception as e:log(f" ❌ [Background upload failed for {filename}: {e}]")t = threading.Thread(target=_bg_upload, daemon=False) # daemon=False: won't be killed on exitt.start()_upload_threads.append(t)log(f" ☁️ Uploading {filename} in background...")def save_best_checkpoint(model, step, val_loss):"""Save best SFT model locally only (no HF upload).Like pretraining: just saves locally and logs val_loss.Final upload happens at the end or manually.This avoids wasting GPU time on repeated uploads."""if not IS_MAIN:returnckpt_dir = f"{WORK}/sft_checkpoints"os.makedirs(ckpt_dir, exist_ok=True)path = f"{ckpt_dir}/sft_ckpt_best.pt"raw_model = model.module if hasattr(model, "module") else modelif hasattr(raw_model, '_orig_mod'):raw_model = raw_model._orig_modstate_dict = raw_model.state_dict()clean_dict = {k.replace("_orig_mod.", ""): v for k, v in state_dict.items()}torch.save({"model": clean_dict, "step": step, "val_loss": val_loss}, path)log(f" ✨ New best! val_loss={val_loss:.4f} @ step {step} (saved locally)")def wait_for_uploads():"""Wait for ALL background uploads to finish before exiting."""if not _upload_threads:returnlog(f"\n⏳ Waiting for {len(_upload_threads)} background upload(s) to complete...")for i, t in enumerate(_upload_threads):t.join(timeout=600) # Wait up to 10 minutes per uploadif t.is_alive():log(f" ⚠️ Upload thread {i+1} timed out after 10 minutes!")else:log(f" ✅ Upload {i+1}/{len(_upload_threads)} complete.")log(f"✅ All background uploads finished.")def load_sft_checkpoint(model, optimizer):"""Load checkpoint: tries SFT first, then falls back to base pretrained."""# Try 1: Resume from existing SFT checkpointtry:log("🔍 Looking for existing SFT checkpoint...")if IS_MAIN:try:with_retry(hf_hub_download, MAIN_REPO,"sft_checkpoints/sft_ckpt_latest.pt",repo_type="model", local_dir=WORK, token=HF_TOKEN)except Exception:passdist.barrier()path = f"{WORK}/sft_checkpoints/sft_ckpt_latest.pt"ckpt = torch.load(path, map_location="cpu", weights_only=False)# Get the actual model (unwrap DDP + compile)raw_model = model.module if hasattr(model, "module") else modelif hasattr(raw_model, '_orig_mod'):raw_model = raw_model._orig_modremapped = remap_checkpoint_keys(ckpt["model"], raw_model.state_dict())raw_model.load_state_dict(remapped)raw_model.head.weight = raw_model.tok_emb.weightlog(" 🔗 Re-tied head.weight with tok_emb.weight")if "optimizer" in ckpt:try:optimizer.load_state_dict(ckpt["optimizer"])except Exception:log(" ⚠️ Could not load optimizer state (architecture change?), using fresh optimizer")step = ckpt.get("step", 0)val_loss = ckpt.get("val_loss", -1)log(f"✅ Resumed SFT from step {step} (val_loss={val_loss:.4f})")del ckptgc.collect()torch.cuda.empty_cache()return stepexcept Exception as e:log(f" (No SFT checkpoint found: {type(e).__name__})")# Try 2: Load BASE pretrained weights (30k step checkpoint)log("📥 Loading BASE 30k pretrained weights...")try:if IS_MAIN:with_retry(hf_hub_download, MAIN_REPO,"checkpoints/ckpt_latest.pt",repo_type="model", local_dir=WORK, token=HF_TOKEN)dist.barrier()path = f"{WORK}/checkpoints/ckpt_latest.pt"ckpt = torch.load(path, map_location="cpu", weights_only=False)raw_model = model.module if hasattr(model, "module") else modelif hasattr(raw_model, '_orig_mod'):raw_model = raw_model._orig_modremapped = remap_checkpoint_keys(ckpt["model"], raw_model.state_dict())raw_model.load_state_dict(remapped)raw_model.head.weight = raw_model.tok_emb.weightlog(" 🔗 Re-tied head.weight with tok_emb.weight")pretrain_step = ckpt.get("step", "?")pretrain_loss = ckpt.get("val_loss", -1)log(f"✅ Loaded BASE pretrained weights (pretrain step={pretrain_step}, "f"val_loss={pretrain_loss:.4f})")log(" Starting SFT from step 0 (optimizer is fresh for SFT)")del ckptgc.collect()torch.cuda.empty_cache()return 0except Exception as e:log(f"❌ FATAL: Cannot load base pretrained weights!")log(f" Error: {type(e).__name__}: {e}")raise RuntimeError("SFT requires a pretrained base model but none could be loaded.\n"f"Checked: {MAIN_REPO}/checkpoints/ckpt_latest.pt\n"f" {MAIN_REPO}/sft_checkpoints/sft_ckpt_latest.pt")# ============================================================================# 10. Learning Rate Schedule (Cosine with Warmup)# ============================================================================def get_lr(step, warmup, total, max_lr, min_lr):if step < warmup:return max_lr * (step + 1) / warmupif step > total:return min_lrratio = (step - warmup) / max(total - warmup, 1)return min_lr + 0.5 * (1 + math.cos(math.pi * ratio)) * (max_lr - min_lr)# ============================================================================# 11. SFT Loss Function (CRITICAL: handles shift mismatch)# ============================================================================# The 500M model.py does NOT shift logits/labels internally.# (It was removed because pretraining dataloader already shifts: y = tokens[i+1:])# But SFT data has labels at SAME position as input_ids.# So we MUST shift here:# - Input to model: x[:, :-1] (all tokens except the last)# - Labels: y[:, 1:] (all labels shifted left by 1)## This makes: logits[t] (predicts next token after 0..t) ↔ labels[t+1] ✓def compute_sft_loss(model, x, y, pad_id=0):"""Forward pass with proper shift for SFT."""x_in = x[:, :-1].contiguous() # [B, T-1] — drop last tokeny_shifted = y[:, 1:].contiguous() # [B, T-1] — shift labels left by 1_, loss = model(x_in, targets=y_shifted, pad_id=pad_id)return loss# ============================================================================# 12. Model Initialization# ============================================================================cfg = ViuAIConfig(vocab_size=SFT_VOCAB_SIZE, # 64003 (matches SFT tokenizer)context_length=CONTEXT_LEN,use_checkpoint=True, # Gradient checkpointing (saves VRAM)z_loss_weight=0.0, # Disable z-loss for SFTattn_dropout=0.1, # Regularization for SFTresid_dropout=0.1,)raw_model = ViuAI(cfg).to(DEVICE)if IS_MAIN:log(f"🧠 Model params: {raw_model.num_params()/1e6:.1f}M | vocab_size={SFT_VOCAB_SIZE}")# Optionally compile (significant speedup on Ampere+ GPUs)if USE_COMPILE:log("⚡ Compiling model with torch.compile (this takes 1-2 mins on first step)...")raw_model = torch.compile(raw_model)model = DDP(raw_model, device_ids=[local_rank])optimizer = torch.optim.AdamW(model.parameters(), lr=MAX_LR,weight_decay=WEIGHT_DECAY, betas=(0.9, 0.95))# Load checkpoint (SFT resume or base pretrained)start_step = load_sft_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()# ============================================================================# 13. Download & Load SFT Data# ============================================================================log("📥 Downloading SFT data (.npy files)...")SFT_DATA_FILES = ["sft_train_ids.npy", "sft_train_labels.npy", "sft_train_offsets.npy","sft_val_ids.npy", "sft_val_labels.npy", "sft_val_offsets.npy",]if IS_MAIN:for fname in SFT_DATA_FILES:with_retry(hf_hub_download, SFT_DATA_REPO, fname, repo_type="dataset",local_dir=WORK, token=HF_TOKEN)dist.barrier()log("✅ SFT data ready.")train_ds = NpySFTDataset(f"{WORK}/sft_train_ids.npy", f"{WORK}/sft_train_labels.npy",f"{WORK}/sft_train_offsets.npy", CONTEXT_LEN)val_ds = NpySFTDataset(f"{WORK}/sft_val_ids.npy", f"{WORK}/sft_val_labels.npy",f"{WORK}/sft_val_offsets.npy", CONTEXT_LEN)if IS_MAIN:log(f"📊 Train examples: {len(train_ds)}, Val examples: {len(val_ds)}")# ============================================================================# 14. Sanity Checks# ============================================================================if IS_MAIN:_s_ids, _s_labels = train_ds.get(0)_has_masked = (_s_labels == -100).any()_has_active = (_s_labels != -100).any()assert _has_masked, ("SFT FATAL: No masked tokens (-100) found in labels! ""User-turn tokens MUST be -100. Your data pipeline is broken.")assert _has_active, ("SFT FATAL: ALL tokens are masked (-100)! ""No assistant tokens to train on. Your data pipeline is broken.")_max_id = int(_s_ids[_s_ids > 0].max()) if (_s_ids > 0).any() else 0_masked_count = (_s_labels == -100).sum()_active_count = ((_s_labels != -100) & (_s_labels != 0)).sum()log(f"✅ Data sanity check passed:")log(f" Masked (user) tokens: {_masked_count} | Active (assistant) tokens: {_active_count}")log(f" Max token ID in data: {_max_id} | Model vocab: {SFT_VOCAB_SIZE}")if _max_id >= SFT_VOCAB_SIZE:log(f"⚠️ WARNING: Max token ID ({_max_id}) >= vocab ({SFT_VOCAB_SIZE})! Will crash!")del _s_ids, _s_labels# ============================================================================# 15. Training Step Math# ============================================================================PAD_ID = 0rng = random.Random(1337 + rank)val_rng = random.Random(999)# Optional cap on training steps, read from environment variable.# Set MAX_TRAIN_STEPS in the shell/notebook before running to do a# limited test run (e.g. "2000"). Leave unset for full training# (runs all steps for EPOCHS as originally planned)._max_steps_env = os.environ.get("MAX_TRAIN_STEPS")MAX_TRAIN_STEPS = int(_max_steps_env) if _max_steps_env else NoneTOTAL_STEPS = max(1, (len(train_ds) // effective_batch) * EPOCHS)end_step = TOTAL_STEPSif MAX_TRAIN_STEPS is not None:end_step = min(end_step, start_step + MAX_TRAIN_STEPS)TOTAL_NEW_STEPS = max(1, end_step - start_step)log(f"📈 Total SFT steps for {EPOCHS} epochs (full plan): {TOTAL_STEPS}")if MAX_TRAIN_STEPS is not None:log(f" ⚠️ MAX_TRAIN_STEPS cap active: {MAX_TRAIN_STEPS}")log(f" Resumed from step: {start_step} | This run will go to: {end_step}")log(f" Training: step {start_step} → {end_step}")# ============================================================================# 16. Evaluation Function# ============================================================================@torch.no_grad()def evaluate():model.eval()losses = []for _ in range(20):x, y = get_sft_batch(val_ds, MICRO_BATCH, val_rng)with torch.autocast(device_type="cuda", dtype=AMP_DTYPE):loss = compute_sft_loss(model, x, y, pad_id=PAD_ID)losses.append(loss.item())del x, y, lossmodel.train()torch.cuda.empty_cache()return sum(losses) / len(losses)# ============================================================================# 17. Training Loop# ============================================================================log(f"\n{'='*60}")log(f"🚀 Starting SFT Training...")log(f"{'='*60}\n")model.train()val_loss = Nonebest_val_loss = Noneema_tok_s = Noneglobal_t0 = time.time()t0 = time.time()for step in range(start_step, end_step):# LR schedule (based on local step, not global)local_step = step - start_steplr = get_lr(local_step, WARMUP_STEPS, TOTAL_NEW_STEPS, MAX_LR, MIN_LR)for g in optimizer.param_groups:g["lr"] = lroptimizer.zero_grad(set_to_none=True)accum_loss = 0.0for micro_i in range(GRAD_ACCUM):x, y = get_sft_batch(train_ds, MICRO_BATCH, rng)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 = compute_sft_loss(model, x, y, pad_id=PAD_ID)loss = loss / GRAD_ACCUMloss.backward()accum_loss += loss.item()del x, y, loss# NaN/Inf protection (synced across all ranks)is_nan = torch.tensor([0 if math.isfinite(accum_loss) else 1], device=DEVICE)dist.all_reduce(is_nan, op=dist.ReduceOp.MAX)if is_nan.item() > 0:if IS_MAIN:log(f"⚠️ NaN/Inf loss at step {step}! Skipping optimizer step.")optimizer.zero_grad(set_to_none=True)continuetorch.nn.utils.clip_grad_norm_(model.parameters(), GRAD_CLIP)optimizer.step()# ---- Logging (every 10 steps) ----if IS_MAIN and step % 10 == 0:dt = time.time() - t0tok_s = (MICRO_BATCH * GRAD_ACCUM * CONTEXT_LEN * world_size * 10) / dt if dt > 0 else 0ema_tok_s = tok_s if ema_tok_s is None else 0.7 * ema_tok_s + 0.3 * tok_st0 = time.time()mem_alloc = torch.cuda.memory_allocated(DEVICE) / 1e9mem_reserved = torch.cuda.memory_reserved(DEVICE) / 1e9steps_done = step - start_stepif steps_done > 0:elapsed = time.time() - global_t0eta_s = elapsed / steps_done * (end_step - step)eta_str = f"{eta_s/60:.0f}min" if eta_s < 3600 else f"{eta_s/3600:.1f}hr"else:eta_str = "..."log(f"SFT step {step:5d}/{end_step} | loss {accum_loss:.4f} | lr {lr:.2e} | "f"{ema_tok_s:.0f} tok/s | ETA {eta_str} | "f"mem {mem_alloc:.1f}GB/{mem_reserved:.1f}GB")# ---- Memory cleanup (important for T4!) ----if step > start_step and step % EMPTY_CACHE_EVERY == 0:torch.cuda.empty_cache()# ---- Evaluation ----if step > start_step and step % EVAL_EVERY == 0:val_loss = evaluate()if IS_MAIN and val_loss is not None:log(f" >> val_loss {val_loss:.4f}")if best_val_loss is None or val_loss < best_val_loss:best_val_loss = val_losssave_best_checkpoint(model, step, val_loss)# ---- Save latest checkpoint (background upload) ----if step > start_step and step % CKPT_EVERY == 0:if IS_MAIN:wait_for_uploads()save_checkpoint(model, optimizer, step,val_loss if val_loss is not None else -1,"sft_ckpt_latest.pt", blocking=False)dist.barrier()# ============================================================================# 18. Final Save & Cleanup# ============================================================================dist.barrier()final_val = evaluate()# Final save: BLOCKING (synchronous) — must complete before program exitssave_checkpoint(model, optimizer, end_step,final_val if final_val is not None else -1,"sft_ckpt_latest.pt", blocking=True)# Upload best checkpoint at the very end (only once, saves GPU time)if IS_MAIN and os.path.exists(f"{WORK}/sft_checkpoints/sft_ckpt_best.pt"):log(f" ☁️ Uploading best checkpoint to HF (blocking, please wait)...")try:with_retry(api.upload_file, path_or_fileobj=f"{WORK}/sft_checkpoints/sft_ckpt_best.pt",path_in_repo="sft_checkpoints/sft_ckpt_best.pt",repo_id=MAIN_REPO, repo_type="model", token=HF_TOKEN)log(f" ✅ Best checkpoint uploaded to HF!")except Exception as e:log(f" ❌ Best checkpoint upload failed: {e}")log(f" ⚠️ File saved locally at: {WORK}/sft_checkpoints/sft_ckpt_best.pt")log(f" ⚠️ Please upload manually before shutting down GPU!")# Wait for any remaining background uploads from mid-training savesif IS_MAIN:wait_for_uploads()if IS_MAIN:log(f"\n{'='*60}")log(f"✨ 500M SFT Training Complete!")log(f" Final val_loss: {final_val if final_val is not None else -1:.4f}")log(f" Best val_loss: {best_val_loss if best_val_loss is not None else -1:.4f}")log(f" Checkpoints saved to: {MAIN_REPO}/sft_checkpoints/")log(f"{'='*60}")dist.destroy_process_group()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933# ============================================================================# ViuAI 500M — Supervised Fine-Tuning (SFT) Script# ============================================================================# Universal script: works on H200(140GB), 5090(32GB), L4(24GB), T4x2(16GBx2)# Works on: Kaggle, Rental GPU, Any cloud provider## Run commands:# Kaggle T4x2: torchrun --nproc_per_node=2 train_sft.py# Single GPU: torchrun --nproc_per_node=1 train_sft.py# Multi-GPU: torchrun --nproc_per_node=<N> train_sft.py# ============================================================================import osos.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")# Redirect HF cache to working directory (rental GPUs often have tiny OS partitions)# This prevents "No space left on device" errors during checkpoint uploadif os.path.exists("/kaggle/working"):os.environ.setdefault("HF_HOME", "/kaggle/working/hf_cache")else:os.environ.setdefault("HF_HOME", "./working/hf_cache")import json, math, time, random, sys, contextlib, gc, threading# Global list to track all background upload threads_upload_threads = []import numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as Fimport torch.distributed as distfrom torch.nn.parallel import DistributedDataParallel as DDPfrom huggingface_hub import HfApi, hf_hub_download, create_repofrom datetime import timedelta# ============================================================================# 1. DDP Setup (works for single GPU too via torchrun --nproc_per_node=1)# ============================================================================def setup_ddp():if not torch.cuda.is_available():raise RuntimeError("SFT training requires at least one CUDA GPU.")dist.init_process_group(backend="nccl", timeout=timedelta(minutes=30))rank = dist.get_rank()local_rank = int(os.environ.get("LOCAL_RANK", 0))world_size = dist.get_world_size()torch.cuda.set_device(local_rank)return rank, local_rank, world_sizerank, local_rank, world_size = setup_ddp()DEVICE = f"cuda:{local_rank}"IS_MAIN = rank == 0IS_LOCAL_MAIN = local_rank == 0def log(msg):if IS_MAIN:print(msg, flush=True)# ============================================================================# 2. Authentication (Kaggle + Rental GPU dono support)# ============================================================================HF_TOKEN = os.environ.get("HF_TOKEN")if not HF_TOKEN:try:from kaggle_secrets import UserSecretsClientHF_TOKEN = UserSecretsClient().get_secret("HF_TOKEN")os.environ["HF_TOKEN"] = HF_TOKENexcept Exception:passif not HF_TOKEN:raise RuntimeError("HF_TOKEN not found!\n"" Kaggle: Settings → Secrets → Add HF_TOKEN\n"" Rental GPU: export HF_TOKEN='hf_your_token'")api = HfApi(token=HF_TOKEN)# ============================================================================# 3. Repository Configuration# ============================================================================MAIN_REPO = os.environ.get("VIUAI_MODEL_REPO", "ViuAI/ViuAI-500M")SFT_DATA_REPO = os.environ.get("VIUAI_SFT_DATA_REPO", "ViuAI/viuai-250m-sft-tokenized")def env_flag(name, default=False):value = os.environ.get(name)if value is None:return defaultreturn value.strip().lower() in {"1", "true", "yes", "y", "on"}# Fresh SFT is the safe default. Set RESUME_SFT=1 only to continue an# interrupted SFT run from the configured SFT checkpoint directory.RESUME_SFT = env_flag("RESUME_SFT", default=False)RESUME_CHECKPOINT_FILE = "sft_ckpt_latest.pt" if RESUME_SFT else "__fresh_sft_start__.pt"SFT_CHECKPOINT_DIR = os.environ.get("SFT_CHECKPOINT_DIR", "sft_checkpoints/sft_v1").strip("/")if not SFT_CHECKPOINT_DIR or SFT_CHECKPOINT_DIR.startswith(".") or ".." in SFT_CHECKPOINT_DIR.split("/"):raise ValueError("SFT_CHECKPOINT_DIR must be a safe relative Hugging Face repository path.")if IS_MAIN:create_repo(MAIN_REPO, repo_type="model", token=HF_TOKEN, exist_ok=True, private=True)dist.barrier()# ============================================================================# 4. Working Directory (auto-detect environment)# ============================================================================if os.path.exists("/kaggle/working"):WORK = "/kaggle/working"elif os.path.exists("/root/working"):WORK = "/root/working"else:WORK = "./working"os.makedirs(WORK, exist_ok=True)os.makedirs(f"{WORK}/code", exist_ok=True)sys.path.insert(0, f"{WORK}/code")# ============================================================================# 5. Download Model Code from HuggingFace# ============================================================================def with_retry(fn, *args, retries=4, delay=5, **kwargs):for attempt in range(1, retries + 1):try:return fn(*args, **kwargs)except Exception as e:if "404" in str(e) or "EntryNotFoundError" in type(e).__name__:raiseif attempt == retries:raiselog(f" [retry {attempt}/{retries}] {type(e).__name__}: {e}")time.sleep(delay)delay *= 2if IS_MAIN:log("📥 Downloading model code...")try:download_on_main(hf_hub_download, MAIN_REPO, "code/config.py", local_dir=WORK, token=HF_TOKEN)download_on_main(hf_hub_download, MAIN_REPO, "code/model.py", local_dir=WORK, token=HF_TOKEN)except NameError:# download_on_main is defined later, so we just use the original with_retry pattern for code download# Since we're downloading the code, we just do it manually with all_reduceok = Trueerr = ""if IS_MAIN:try:with_retry(hf_hub_download, MAIN_REPO, "code/config.py", local_dir=WORK, token=HF_TOKEN)with_retry(hf_hub_download, MAIN_REPO, "code/model.py", local_dir=WORK, token=HF_TOKEN)except Exception as e:ok = Falseerr = str(e)print(f"Download failed: {err}")# Can't use DEVICE here since setup_ddp is done but DEVICE isn't assigned if this is before device assignment# Wait, DEVICE is defined right after setup_ddp.ok_tensor = torch.tensor([1 if ok else 0], device=DEVICE)dist.all_reduce(ok_tensor, op=dist.ReduceOp.MIN)if ok_tensor.item() == 0:raise RuntimeError(f"Model code download failed on main rank: {err}")dist.barrier()from config import ViuAIConfigfrom model import ViuAI# ============================================================================# 6. GPU Auto-Detection & Hyperparameters# ============================================================================mem_gb = torch.cuda.get_device_properties(local_rank).total_memory / 1e9gpu_name = torch.cuda.get_device_name(local_rank)# Check if GPU supports bfloat16 (Ampere+ architecture, compute capability >= 8.0)compute_cap = torch.cuda.get_device_capability(local_rank)supports_bf16 = compute_cap[0] >= 8 # Ampere (8.0), Hopper (9.0) etc.if mem_gb >= 70: # H200 (140GB), H100 (80GB), A100 (80GB)MICRO_BATCH = 16GRAD_ACCUM = 2CONTEXT_LEN = 2048AMP_DTYPE = torch.bfloat16USE_COMPILE = TrueEMPTY_CACHE_EVERY = 500elif mem_gb >= 28: # RTX 5090 (32GB), A10G (24GB but reported higher)MICRO_BATCH = 16 # increased from 2 -> 16, now feasible since# we're on a 32GB RTX 5090 instead of a 15.6GB# Kaggle T4. Matches the proven working 250M# config exactly.# NOTE: If this causes a CUDA out-of-memory# (OOM) error (500M has ~2x the parameters of# 250M, so may need more headroom), fall back# to MICRO_BATCH=8, GRAD_ACCUM=8 instead# (keeps the same effective batch size of 64).GRAD_ACCUM = 4 # reverted from 8 -> 4, matches 250M's proven# config. Effective batch size = 16 x 4 = 64# (same as the working 250M run).CONTEXT_LEN = 1024 # unchangedAMP_DTYPE = torch.bfloat16USE_COMPILE = TrueEMPTY_CACHE_EVERY = 200elif mem_gb >= 20: # L4 (24GB), RTX 4090 (24GB)MICRO_BATCH = 4GRAD_ACCUM = 8CONTEXT_LEN = 2048AMP_DTYPE = torch.bfloat16 if supports_bf16 else torch.float16USE_COMPILE = supports_bf16 # Only compile on Ampere+EMPTY_CACHE_EVERY = 100else: # T4 (16GB), RTX 3060 (12GB)MICRO_BATCH = 2 # unchanged — limited by T4 GPU VRAM (15.6GB)GRAD_ACCUM = 16 # increased from 8 → 16, to raise effective# batch size from 32 to 64 (matches the# proven-stable 250M SFT run's effective batch,# reduces gradient noise)CONTEXT_LEN = 1024 # unchangedAMP_DTYPE = torch.float32 # Changed from float16 to float32 for stabilityUSE_COMPILE = False # T4 Turing has poor torch.compile supportEMPTY_CACHE_EVERY = 50# SFT-specific hyperparameters (same for all GPUs)MAX_LR = 1e-05 # reverted from 3e-05 back to 1e-05 — this is# the PROVEN value from the working 250M run;# 3e-05 combined with our smaller batch size# caused training instability and garbage outputMIN_LR = 1e-06 # unchangedWARMUP_STEPS = 50 # reverted from 150 → 50, matching the working# 250M run (no longer need extra-long warmup# since LR is back to a gentler, proven value)EPOCHS = 4 # reduced from 6 → 4 (250M used 3 successfully;# we keep slightly more since 500M has more# parameters to adapt, but avoid excessive# total training time)WEIGHT_DECAY = 0.01GRAD_CLIP = 1.0EVAL_EVERY = 500CKPT_EVERY = 2000# Vocab size: SFT data was tokenized with 250M SFT tokenizer (64003 vocab)# Base model was trained with 64000 vocab# We use 64003 to match the SFT data; embedding resize handles the mismatchSFT_VOCAB_SIZE = 64003TARGET_EFFECTIVE_BATCH = int(os.environ.get("TARGET_EFFECTIVE_BATCH", "64"))GRAD_ACCUM = max(1, TARGET_EFFECTIVE_BATCH // (MICRO_BATCH * world_size))if MICRO_BATCH * world_size > TARGET_EFFECTIVE_BATCH:log(f"WARNING: MICRO_BATCH * world_size ({MICRO_BATCH * world_size}) > target effective batch ({TARGET_EFFECTIVE_BATCH}).")effective_batch = MICRO_BATCH * GRAD_ACCUM * world_sizelog(f"{'='*60}")log(f"🖥️ GPU: {gpu_name} | VRAM: {mem_gb:.1f}GB | Compute: {compute_cap[0]}.{compute_cap[1]}")log(f"⚙️ MICRO_BATCH={MICRO_BATCH} | GRAD_ACCUM={GRAD_ACCUM} | CTX={CONTEXT_LEN}")log(f"⚙️ AMP={AMP_DTYPE} | torch.compile={'ON' if USE_COMPILE else 'OFF'}")log(f"⚙️ Effective Batch Size: {effective_batch} | GPUs: {world_size}")log(f"⚙️ LR: {MAX_LR} → {MIN_LR} | Epochs: {EPOCHS}")log(f"{'='*60}")torch.backends.cudnn.benchmark = Truetorch.backends.cuda.matmul.allow_tf32 = True# ============================================================================# 7. SFT Dataset (Pre-tokenized .npy with -100 label masking)# ============================================================================# Labels have -100 on user-turn tokens → loss is ONLY on assistant responses.# input_ids and labels are at SAME alignment (no shift in the data files).# The shift is handled in compute_sft_loss() below.class NpySFTDataset:def __init__(self, ids_path, labels_path, offsets_path, ctx_len):self.ids = np.load(ids_path, mmap_mode='r')self.labels = np.load(labels_path, mmap_mode='r')self.offsets = np.load(offsets_path)self.ctx_len = ctx_lenif self.ids.ndim != 1 or self.labels.ndim != 1:raise ValueError("SFT ids and labels must be one-dimensional arrays.")if len(self.ids) != len(self.labels):raise ValueError(f"SFT ids/labels length mismatch: {len(self.ids)} != {len(self.labels)}")if self.offsets.ndim != 1 or len(self.offsets) == 0:raise ValueError("SFT offsets must be a non-empty one-dimensional array.")if int(self.offsets[0]) != 0 or np.any(np.diff(self.offsets) < 0):raise ValueError("SFT offsets must start at 0 and be monotonically increasing.")if int(self.offsets[-1]) > len(self.ids):raise ValueError("SFT offsets point beyond the ids array.")# Support both common formats: N start offsets, or N+1 offsets where# the final entry is the len(ids) sentinel.self.num_examples = len(self.offsets) - 1 if int(self.offsets[-1]) == len(self.ids) else len(self.offsets)if self.num_examples <= 0:raise ValueError("SFT dataset contains no examples.")def __len__(self):return self.num_examplesdef get(self, idx):start = int(self.offsets[idx])end = int(self.offsets[idx + 1]) if idx + 1 < len(self.offsets) else len(self.ids)if end <= start:raise ValueError(f"SFT example {idx} is empty or has invalid offsets.")# Keep the end of an overlong conversation. Assistant targets are# normally at the end, while prefix truncation can remove every label.start = max(start, end - self.ctx_len)length = end - startinput_ids = np.zeros(self.ctx_len, dtype=np.int64)labels = np.full(self.ctx_len, -100, dtype=np.int64)input_ids[:length] = self.ids[start:start + length].astype(np.int64)labels[:length] = self.labels[start:start + length].astype(np.int64)return input_ids, labelsdef get_sft_batch(dataset, batch_size, rng):batch_ids, batch_labels = [], []empty_examples = 0while len(batch_ids) < batch_size:idx = rng.randrange(len(dataset))try:ids, labels = dataset.get(idx)except ValueError:empty_examples += 1if empty_examples >= batch_size * 10:raise RuntimeError("Too many invalid/empty SFT examples encountered.")continueif not np.any(labels != -100):empty_examples += 1if empty_examples >= batch_size * 10:raise RuntimeError("Too many SFT examples have no unmasked assistant labels. ""Check the data preprocessing and conversation template.")continuebatch_ids.append(ids)batch_labels.append(labels)x = torch.from_numpy(np.stack(batch_ids)).pin_memory().to(DEVICE, non_blocking=True)y = torch.from_numpy(np.stack(batch_labels)).pin_memory().to(DEVICE, non_blocking=True)return x, y# ============================================================================# 8. Checkpoint Key Remapping (handles torch.compile prefix + vocab resize)# ============================================================================def remap_checkpoint_keys(ckpt_state_dict, model_state_dict):"""Remap checkpoint keys to match current model.Handles:1. torch.compile prefix: _orig_mod.X → X2. Vocab size mismatch: resize tok_emb.weight and head.weight"""model_keys = set(model_state_dict.keys())# Normalize common DistributedDataParallel and torch.compile prefixes.stripped = {}n_stripped = 0for key, value in ckpt_state_dict.items():normalized_key = keyfor prefix in ("module._orig_mod.", "_orig_mod.", "module."):if normalized_key.startswith(prefix):normalized_key = normalized_key[len(prefix):]breakif normalized_key != key:stripped[normalized_key] = valuen_stripped += 1else:stripped[key] = valueif n_stripped:log(f" 🔧 Stripped '_orig_mod.' from {n_stripped} keys (torch.compile artifact)")for emb_key in ["tok_emb.weight", "head.weight"]:if emb_key in stripped and emb_key in model_state_dict:ckpt_shape = stripped[emb_key].shapemodel_shape = model_state_dict[emb_key].shapeif ckpt_shape != model_shape:log(f" 📐 Resizing '{emb_key}': {list(ckpt_shape)} → {list(model_shape)}")if len(ckpt_shape) != 2 or len(model_shape) != 2 or ckpt_shape[1] != model_shape[1]:raise ValueError(f"Cannot resize '{emb_key}' from {list(ckpt_shape)} to {list(model_shape)}")# Keep checkpoint surgery on CPU so loading does not create a# second large embedding tensor on the GPU.ckpt_weight = stripped[emb_key].detach().cpu()new_weight = model_state_dict[emb_key].detach().cpu().clone()min_vocab = min(ckpt_shape[0], model_shape[0])new_weight[:min_vocab] = ckpt_weight[:min_vocab]# Smart initialization: copy the mean embedding to new special tokensif model_shape[0] > ckpt_shape[0]:log(f" 🧠 Smart init for new {model_shape[0] - ckpt_shape[0]} tokens (using mean embedding)")mean_emb = ckpt_weight[:min_vocab].mean(dim=0)for i in range(min_vocab, model_shape[0]):new_weight[i] = mean_embstripped[emb_key] = new_weightreturn stripped# ============================================================================# 9. Checkpoint Save / Load# ============================================================================def save_checkpoint(model, optimizer, step, val_loss, filename, blocking=False, best_val_loss=None):"""Save checkpoint locally + upload to HF in background.Args:blocking: If True, upload synchronously (used for final save).If False, upload in background thread (used during training)."""if not IS_MAIN:returnckpt_dir = f"{WORK}/{SFT_CHECKPOINT_DIR}"os.makedirs(ckpt_dir, exist_ok=True)path = f"{ckpt_dir}/{filename}"raw_model = model.module if hasattr(model, "module") else modelif hasattr(raw_model, '_orig_mod'):raw_model = raw_model._orig_modstate_dict = raw_model.state_dict()clean_dict = {k.replace("_orig_mod.", ""): v for k, v in state_dict.items()}torch.save({"model": clean_dict, "optimizer": optimizer.state_dict(),"step": step, "val_loss": val_loss, "best_val_loss": best_val_loss}, path)log(f" 💾 Checkpoint saved locally @ step {step}, val_loss={val_loss:.4f}")if blocking:# Synchronous upload (for final save — must complete before exit)log(f" ☁️ Uploading {filename} to HF (blocking, please wait)...")try:with_retry(api.upload_file, path_or_fileobj=path,path_in_repo=f"{SFT_CHECKPOINT_DIR}/{filename}",repo_id=MAIN_REPO, repo_type="model", token=HF_TOKEN)log(f" ✅ Upload complete for {filename} @ step {step}")except Exception as e:log(f" ❌ Upload FAILED for {filename}: {e}")log(f" ⚠️ File is still saved locally at: {path}")log(f" ⚠️ Please upload manually before shutting down GPU!")else:# Background upload (for mid-training saves — doesn't block GPU)def _bg_upload():try:with_retry(api.upload_file, path_or_fileobj=path,path_in_repo=f"{SFT_CHECKPOINT_DIR}/{filename}",repo_id=MAIN_REPO, repo_type="model", token=HF_TOKEN)log(f" ☁️ [Background upload complete for {filename} @ step {step}]")except Exception as e:log(f" ❌ [Background upload failed for {filename}: {e}]")t = threading.Thread(target=_bg_upload, daemon=False) # daemon=False: won't be killed on exitt.start()_upload_threads.append(t)log(f" ☁️ Uploading {filename} in background...")def save_best_checkpoint(model, step, val_loss):"""Save best SFT model locally only (no HF upload).Like pretraining: just saves locally and logs val_loss.Final upload happens at the end or manually.This avoids wasting GPU time on repeated uploads."""if not IS_MAIN:returnckpt_dir = f"{WORK}/{SFT_CHECKPOINT_DIR}"os.makedirs(ckpt_dir, exist_ok=True)path = f"{ckpt_dir}/sft_ckpt_best.pt"raw_model = model.module if hasattr(model, "module") else modelif hasattr(raw_model, '_orig_mod'):raw_model = raw_model._orig_modstate_dict = raw_model.state_dict()clean_dict = {k.replace("_orig_mod.", ""): v for k, v in state_dict.items()}torch.save({"model": clean_dict, "step": step, "val_loss": val_loss}, path)log(f" ✨ New best! val_loss={val_loss:.4f} @ step {step} (saved locally)")def wait_for_uploads():"""Wait for ALL background uploads to finish before exiting."""if not _upload_threads:returnlog(f"\n⏳ Waiting for {len(_upload_threads)} background upload(s) to complete...")for i, t in enumerate(_upload_threads):t.join(timeout=600) # Wait up to 10 minutes per uploadif t.is_alive():log(f" ⚠️ Upload thread {i+1} timed out after 10 minutes!")else:log(f" ✅ Upload {i+1}/{len(_upload_threads)} complete.")log(f"✅ All background uploads finished.")def load_sft_checkpoint(model, optimizer):"""Load checkpoint: tries SFT first, then falls back to base pretrained."""if not RESUME_SFT:log("Fresh SFT requested: loading the base pretrained checkpoint.")# Try 1: Resume from existing SFT checkpointtry:if not RESUME_SFT:raise FileNotFoundError("Fresh SFT run requested.")log("🔍 Looking for existing SFT checkpoint...")if IS_LOCAL_MAIN:try:with_retry(hf_hub_download, MAIN_REPO,f"{SFT_CHECKPOINT_DIR}/{RESUME_CHECKPOINT_FILE}",repo_type="model", local_dir=WORK, token=HF_TOKEN)except Exception:passdist.barrier()path = f"{WORK}/{SFT_CHECKPOINT_DIR}/{RESUME_CHECKPOINT_FILE}"ckpt = torch.load(path, map_location="cpu", weights_only=False)# Get the actual model (unwrap DDP + compile)raw_model = model.module if hasattr(model, "module") else modelif hasattr(raw_model, '_orig_mod'):raw_model = raw_model._orig_modremapped = remap_checkpoint_keys(ckpt["model"], raw_model.state_dict())missing, unexpected = raw_model.load_state_dict(remapped, strict=False)allowed_missing = {"head.weight"}bad_missing = [m for m in missing if m not in allowed_missing]if bad_missing:raise RuntimeError(f"Missing critical checkpoint keys: {bad_missing}")if unexpected:log(f"Warning: unexpected checkpoint keys ignored: {unexpected}")raw_model.head.weight = raw_model.tok_emb.weightlog(" 🔗 Re-tied head.weight with tok_emb.weight")if "optimizer" in ckpt:try:optimizer.load_state_dict(ckpt["optimizer"])except Exception:log(" ⚠️ Could not load optimizer state (architecture change?), using fresh optimizer")step = ckpt.get("step", 0)val_loss = ckpt.get("val_loss", -1)best_val_loss = ckpt.get("best_val_loss", None)log(f"✅ Resumed SFT from step {step} (val_loss={val_loss:.4f})")del ckptgc.collect()torch.cuda.empty_cache()return step, val_loss, best_val_lossexcept Exception as e:if RESUME_SFT:raise RuntimeError("RESUME_SFT=1 was requested, but the SFT checkpoint could not be loaded. ""Fix the checkpoint or unset RESUME_SFT to start a fresh SFT run.") from elog(f" (No SFT checkpoint found: {type(e).__name__})")# Try 2: Load BASE pretrained weights (30k step checkpoint)log("📥 Loading BASE 30k pretrained weights...")try:if IS_LOCAL_MAIN:with_retry(hf_hub_download, MAIN_REPO,"checkpoints/ckpt_latest.pt",repo_type="model", local_dir=WORK, token=HF_TOKEN)dist.barrier()path = f"{WORK}/checkpoints/ckpt_latest.pt"ckpt = torch.load(path, map_location="cpu", weights_only=False)raw_model = model.module if hasattr(model, "module") else modelif hasattr(raw_model, '_orig_mod'):raw_model = raw_model._orig_modremapped = remap_checkpoint_keys(ckpt["model"], raw_model.state_dict())missing, unexpected = raw_model.load_state_dict(remapped, strict=False)allowed_missing = {"head.weight"}bad_missing = [m for m in missing if m not in allowed_missing]if bad_missing:raise RuntimeError(f"Missing critical checkpoint keys: {bad_missing}")if unexpected:log(f"Warning: unexpected checkpoint keys ignored: {unexpected}")raw_model.head.weight = raw_model.tok_emb.weightlog(" 🔗 Re-tied head.weight with tok_emb.weight")pretrain_step = ckpt.get("step", "?")pretrain_loss = ckpt.get("val_loss", -1)log(f"✅ Loaded BASE pretrained weights (pretrain step={pretrain_step}, "f"val_loss={pretrain_loss:.4f})")log(" Starting SFT from step 0 (optimizer is fresh for SFT)")del ckptgc.collect()torch.cuda.empty_cache()return 0, -1, Noneexcept Exception as e:log(f"❌ FATAL: Cannot load base pretrained weights!")log(f" Error: {type(e).__name__}: {e}")raise RuntimeError("SFT requires a pretrained base model but none could be loaded.\n"f"Checked: {MAIN_REPO}/checkpoints/ckpt_latest.pt\n"f" {MAIN_REPO}/{SFT_CHECKPOINT_DIR}/sft_ckpt_latest.pt")# ============================================================================# 10. Learning Rate Schedule (Cosine with Warmup)# ============================================================================def get_lr(step, warmup, total, max_lr, min_lr):if step < warmup:return max_lr * (step + 1) / warmupif step > total:return min_lrratio = (step - warmup) / max(total - warmup, 1)return min_lr + 0.5 * (1 + math.cos(math.pi * ratio)) * (max_lr - min_lr)# ============================================================================# 11. SFT Loss Function (CRITICAL: handles shift mismatch)# ============================================================================# The 500M model.py does NOT shift logits/labels internally.# (It was removed because pretraining dataloader already shifts: y = tokens[i+1:])# But SFT data has labels at SAME position as input_ids.# So we MUST shift here:# - Input to model: x[:, :-1] (all tokens except the last)# - Labels: y[:, 1:] (all labels shifted left by 1)## This makes: logits[t] (predicts next token after 0..t) ↔ labels[t+1] ✓def compute_sft_loss(model, x, y, pad_id=0):"""Forward pass with proper shift for SFT."""x_in = x[:, :-1].contiguous() # [B, T-1] — drop last tokeny_shifted = y[:, 1:].contiguous() # [B, T-1] — shift labels left by 1use_pad_id = Noneif pad_id is not None and (x_in == pad_id).any():use_pad_id = pad_idlogits, loss = model(x_in, targets=y_shifted, pad_id=use_pad_id)if not (y_shifted != -100).any():return torch.nan_to_num(logits.float()).sum() * 0.0return loss# ============================================================================# 12. Model Initialization# ============================================================================cfg = ViuAIConfig(vocab_size=SFT_VOCAB_SIZE, # 64003 (matches SFT tokenizer)context_length=CONTEXT_LEN,use_checkpoint=True, # Gradient checkpointing (saves VRAM)z_loss_weight=0.0, # Disable z-loss for SFTattn_dropout=0.1, # Regularization for SFTresid_dropout=0.1,)raw_model = ViuAI(cfg).to(DEVICE)if IS_MAIN:log(f"🧠 Model params: {raw_model.num_params()/1e6:.1f}M | vocab_size={SFT_VOCAB_SIZE}")# Optionally compile (significant speedup on Ampere+ GPUs)if USE_COMPILE:log("⚡ Compiling model with torch.compile (this takes 1-2 mins on first step)...")raw_model = torch.compile(raw_model)model = DDP(raw_model, device_ids=[local_rank])decay_params = []no_decay_params = []for name, param in model.named_parameters():if not param.requires_grad:continueif any(k in name for k in ["norm", "tok_emb"]):no_decay_params.append(param)else:decay_params.append(param)optimizer = torch.optim.AdamW([{"params": decay_params, "weight_decay": WEIGHT_DECAY},{"params": no_decay_params, "weight_decay": 0.0},],lr=MAX_LR,betas=(0.9, 0.95))# Load checkpoint (SFT resume or base pretrained)start_step, prev_val_loss, best_val_loss_loaded = load_sft_checkpoint(model, optimizer)state_t = torch.tensor([start_step,prev_val_loss if isinstance(prev_val_loss, (int, float)) else -1.0,best_val_loss_loaded if isinstance(best_val_loss_loaded, (int, float)) else -1.0], dtype=torch.float32, device=DEVICE)dist.broadcast(state_t, src=0)start_step = int(state_t[0].item())prev_val_loss = state_t[1].item() if state_t[1].item() != -1.0 else Nonebest_val_loss = state_t[2].item() if state_t[2].item() != -1.0 else Noneif best_val_loss is None and isinstance(prev_val_loss, (int, float)) and prev_val_loss >= 0:best_val_loss = prev_val_loss# ============================================================================# 13. Download & Load SFT Data# ============================================================================log("📥 Downloading SFT data (.npy files)...")SFT_DATA_FILES = ["sft_train_ids.npy", "sft_train_labels.npy", "sft_train_offsets.npy","sft_val_ids.npy", "sft_val_labels.npy", "sft_val_offsets.npy",]def download_on_main(fn, *args, fatal=True, **kwargs):ok = Trueerr = ""if IS_LOCAL_MAIN:try:with_retry(fn, *args, **kwargs)except Exception as e:ok = Falseerr = f"{type(e).__name__}: {e}"log(f"Download failed: {err}")ok_tensor = torch.tensor([1 if ok else 0], device=DEVICE)dist.all_reduce(ok_tensor, op=dist.ReduceOp.MIN)if ok_tensor.item() == 0:if fatal:raise RuntimeError(f"Download failed on main rank: {err}")return Falsedist.barrier()return Truefor fname in SFT_DATA_FILES:download_on_main(hf_hub_download, SFT_DATA_REPO, fname, repo_type="dataset", local_dir=WORK, token=HF_TOKEN)log("✅ SFT data ready.")train_ds = NpySFTDataset(f"{WORK}/sft_train_ids.npy", f"{WORK}/sft_train_labels.npy",f"{WORK}/sft_train_offsets.npy", CONTEXT_LEN)val_ds = NpySFTDataset(f"{WORK}/sft_val_ids.npy", f"{WORK}/sft_val_labels.npy",f"{WORK}/sft_val_offsets.npy", CONTEXT_LEN)if IS_MAIN:log(f"📊 Train examples: {len(train_ds)}, Val examples: {len(val_ds)}")# ============================================================================# 14. Sanity Checks# ============================================================================if IS_MAIN:_s_ids, _s_labels = train_ds.get(0)_has_masked = (_s_labels == -100).any()_has_active = (_s_labels != -100).any()assert _has_active, ("SFT FATAL: ALL tokens are masked (-100)! ""No assistant tokens to train on. Your data pipeline is broken.")if not _has_masked:log("WARNING: sample 0 has no -100 labels; it will train on every token in that sample.")_max_id = int(_s_ids[_s_ids > 0].max()) if (_s_ids > 0).any() else 0_masked_count = (_s_labels == -100).sum()_active_count = ((_s_labels != -100) & (_s_labels != 0)).sum()log(f"✅ Data sanity check passed:")log(f" Masked (user) tokens: {_masked_count} | Active (assistant) tokens: {_active_count}")log(f" Max token ID in data: {_max_id} | Model vocab: {SFT_VOCAB_SIZE}")if _max_id >= SFT_VOCAB_SIZE:raise ValueError(f"SFT token ID ({_max_id}) is outside model vocab ({SFT_VOCAB_SIZE}). ""Use the tokenizer that created this dataset.")log(f"⚠️ WARNING: Max token ID ({_max_id}) >= vocab ({SFT_VOCAB_SIZE})! Will crash!")del _s_ids, _s_labels# ============================================================================# 15. Training Step Math# ============================================================================PAD_ID = 0rng = random.Random(1337 + rank)val_rng = random.Random(999)# Optional cap on training steps, read from environment variable.# Set MAX_TRAIN_STEPS in the shell/notebook before running to do a# limited test run (e.g. "2000"). Leave unset for full training# (runs all steps for EPOCHS as originally planned)._max_steps_env = os.environ.get("MAX_TRAIN_STEPS")MAX_TRAIN_STEPS = int(_max_steps_env) if _max_steps_env else NoneTOTAL_STEPS = max(1, (len(train_ds) // effective_batch) * EPOCHS)end_step = TOTAL_STEPSif MAX_TRAIN_STEPS is not None:end_step = min(end_step, start_step + MAX_TRAIN_STEPS)log(f"📈 Total SFT steps for {EPOCHS} epochs (full plan): {TOTAL_STEPS}")if MAX_TRAIN_STEPS is not None:log(f" ⚠️ MAX_TRAIN_STEPS cap active: {MAX_TRAIN_STEPS}")log(f" Resumed from step: {start_step} | This run will go to: {end_step}")log(f" Training: step {start_step} → {end_step}")# ============================================================================# 16. Evaluation Function# ============================================================================@torch.no_grad()def evaluate():# Call the wrapped module directly: only rank 0 evaluates, so DDP's# collective hooks must not be entered by a single process.eval_model = model.module if hasattr(model, "module") else modeleval_model.eval()losses = []for _ in range(20):x, y = get_sft_batch(val_ds, MICRO_BATCH, val_rng)with torch.autocast(device_type="cuda", dtype=AMP_DTYPE):loss = compute_sft_loss(eval_model, x, y, pad_id=PAD_ID)if torch.isfinite(loss):losses.append(loss.item())del x, y, losseval_model.train()torch.cuda.empty_cache()if not losses:return float("inf")return sum(losses) / len(losses)# ============================================================================# 17. Training Loop# ============================================================================log(f"\n{'='*60}")log(f"🚀 Starting SFT Training...")log(f"{'='*60}\n")model.train()val_loss = None# best_val_loss is already loaded aboveema_tok_s = Noneglobal_t0 = time.time()t0 = time.time()for step in range(start_step, end_step):# Keep the original cosine schedule when resuming; restarting warm-up on# every resume causes an unintended learning-rate jump.lr = get_lr(step, WARMUP_STEPS, TOTAL_STEPS, MAX_LR, MIN_LR)for g in optimizer.param_groups:g["lr"] = lroptimizer.zero_grad(set_to_none=True)accum_loss = 0.0for micro_i in range(GRAD_ACCUM):x, y = get_sft_batch(train_ds, MICRO_BATCH, rng)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 = compute_sft_loss(model, x, y, pad_id=PAD_ID)loss = loss / GRAD_ACCUMloss.backward()accum_loss += loss.item()del x, y, loss# NaN/Inf protection (synced across all ranks)is_nan = torch.tensor([0 if math.isfinite(accum_loss) else 1], device=DEVICE)dist.all_reduce(is_nan, op=dist.ReduceOp.MAX)if is_nan.item() > 0:if IS_MAIN:log(f"⚠️ NaN/Inf loss at step {step}! Skipping optimizer step.")optimizer.zero_grad(set_to_none=True)continuegrad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), GRAD_CLIP)if not torch.isfinite(grad_norm):if IS_MAIN:log(f"⚠️ Non-finite grad norm at step {step}. Skipping optimizer step.")optimizer.zero_grad(set_to_none=True)continueoptimizer.step()# ---- Logging (every 10 steps) ----if IS_MAIN and step % 10 == 0:dt = time.time() - t0tok_s = (MICRO_BATCH * GRAD_ACCUM * CONTEXT_LEN * world_size * 10) / dt if dt > 0 else 0ema_tok_s = tok_s if ema_tok_s is None else 0.7 * ema_tok_s + 0.3 * tok_st0 = time.time()mem_alloc = torch.cuda.memory_allocated(DEVICE) / 1e9mem_reserved = torch.cuda.memory_reserved(DEVICE) / 1e9steps_done = step - start_stepif steps_done > 0:elapsed = time.time() - global_t0eta_s = elapsed / steps_done * (end_step - step)eta_str = f"{eta_s/60:.0f}min" if eta_s < 3600 else f"{eta_s/3600:.1f}hr"else:eta_str = "..."log(f"SFT step {step:5d}/{end_step} | loss {accum_loss:.4f} | lr {lr:.2e} | "f"{ema_tok_s:.0f} tok/s | ETA {eta_str} | "f"mem {mem_alloc:.1f}GB/{mem_reserved:.1f}GB")# ---- Memory cleanup (important for T4!) ----if step > start_step and step % EMPTY_CACHE_EVERY == 0:torch.cuda.empty_cache()# ---- Evaluation ----if step > start_step and step % EVAL_EVERY == 0:dist.barrier()val_loss = evaluate() if IS_MAIN else Noneif IS_MAIN and val_loss is not None:log(f" >> val_loss {val_loss:.4f}")if best_val_loss is None or val_loss < best_val_loss:best_val_loss = val_losssave_best_checkpoint(model, step, val_loss)dist.barrier()# ---- Save latest checkpoint (background upload) ----if step > start_step and step % CKPT_EVERY == 0:if IS_MAIN:wait_for_uploads()save_checkpoint(model, optimizer, step,val_loss if val_loss is not None else -1,"sft_ckpt_latest.pt", blocking=False, best_val_loss=best_val_loss)dist.barrier()# ============================================================================# 18. Final Save & Cleanup# ============================================================================dist.barrier()final_val = evaluate() if IS_MAIN else None# Final save: BLOCKING (synchronous) — must complete before program exitsif IS_MAIN:wait_for_uploads() # Added to prevent race condition on final savefinal_val_for_save = final_val if final_val is not None and math.isfinite(final_val) else -1save_checkpoint(model, optimizer, end_step,final_val_for_save,"sft_ckpt_latest.pt", blocking=True, best_val_loss=best_val_loss)# Upload best checkpoint at the very end (only once, saves GPU time)if IS_MAIN and os.path.exists(f"{WORK}/{SFT_CHECKPOINT_DIR}/sft_ckpt_best.pt"):log(f" ☁️ Uploading best checkpoint to HF (blocking, please wait)...")try:with_retry(api.upload_file, path_or_fileobj=f"{WORK}/{SFT_CHECKPOINT_DIR}/sft_ckpt_best.pt",path_in_repo=f"{SFT_CHECKPOINT_DIR}/sft_ckpt_best.pt",repo_id=MAIN_REPO, repo_type="model", token=HF_TOKEN)log(f" ✅ Best checkpoint uploaded to HF!")except Exception as e:log(f" ❌ Best checkpoint upload failed: {e}")log(f" ⚠️ File saved locally at: {WORK}/sft_checkpoints/sft_ckpt_best.pt")log(f" ⚠️ Please upload manually before shutting down GPU!")# Wait for any remaining background uploads from mid-training savesif IS_MAIN:wait_for_uploads()if IS_MAIN:log(f"\n{'='*60}")log(f"✨ 500M SFT Training Complete!")log(f" Final val_loss: {final_val if final_val is not None else -1:.4f}")log(f" Best val_loss: {best_val_loss if best_val_loss is not None else -1:.4f}")log(f" Checkpoints saved to: {MAIN_REPO}/{SFT_CHECKPOINT_DIR}/")log(f"{'='*60}")dist.barrier()dist.destroy_process_group()
code/model.py+251-221
code/train.py+3-3
code/train_sft.py+933-747