Upload 2 files
Browse filesFiles changed (2)
- code/model.py+28-23
- code/train.py+124-69
6 unmodified lines789101112131415161718192 unmodified lines22232425262728293011 unmodified lines4243444546473 unmodified lines515253545556575859606162636465666768697071727374757677787980814 unmodified lines86878889909192939495968 unmodified lines10510610710810911011111211311415 unmodified lines1301311321331341356 unmodified lines@dataclassclass ModelConfig:"""Configuration class for ViuResonance100M."""vocab_size: int = 64000d_model: int = 1024n_layers: int = 12n_heads: int = 16dropout: float = 0.1chunk_size: int = 512class RMSNorm(nn.Module):def __init__(self, dim: int, eps: float = 1e-6):2 unmodified linesself.eps = epsdef forward(self, x: torch.Tensor) -> torch.Tensor:# Enforce float32 accumulation for stability, then cast back to original dtypenorm_x = x.float() * torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + self.eps) * self.weight.float()return norm_x.to(x.dtype)class ResonanceLayerKaggle(nn.Module):def __init__(self, config: ModelConfig):11 unmodified linesself.to_v = nn.Linear(config.d_model, config.d_model, bias=False)self.to_out = nn.Linear(config.d_model, config.d_model, bias=False)self.norm = RMSNorm(config.d_model)def forward(self, x: torch.Tensor) -> torch.Tensor:B, T, C = x.shape3 unmodified linesfreq = torch.tanh(self.to_freq(h)) * 2.0 # B,T,Hphase = torch.tanh(self.to_phase(h)) * math.pi# Use torch.long for absolute positions to avoid float precision issues during subtractionpos = torch.arange(T, device=x.device, dtype=torch.long)out = torch.zeros(B, T, C, device=x.device, dtype=x.dtype)for i in range(0, T, self.chunk_size):end = min(i+self.chunk_size, T)phase_i = phase[:, i:end, :].permute(0,2,1).unsqueeze(-1) # B,H,chunk,1phase_j = phase.permute(0,2,1).unsqueeze(-2) # B,H,1,T# Robust distance calculation in torch.long to prevent overflow/dtype issuesrow_idx = torch.arange(i, end, device=x.device, dtype=torch.long)[:, None]col_idx = pos[None, :]dist_long = (row_idx - col_idx).clamp(min=0)dist = dist_long.to(freq.dtype).view(1, 1, end-i, T)freq_i = freq[:, i:end, :].permute(0,2,1).unsqueeze(-1)angle = (phase_i - phase_j) + freq_i * dist * 0.05# Pure Cosine similarity. We apply the sqrt(d) scaling during the gating phase belowscore = torch.cos(angle)# Boolean causal mask for precision and stabilitycausal_bool = (row_idx >= col_idx).view(1,1,end-i,T)# Mask out future tokensscore = score.masked_fill(~causal_bool, 0.0)score = score / math.sqrt(self.head_dim)4 unmodified linesV_t = V.permute(0,2,1,3).contiguous() # B,H,T,DBh = B * self.n_headsassert C == self.n_heads * self.head_dim, f"C ({C}) != n_heads*head_dim ({self.n_heads*self.head_dim})"s = score.reshape(Bh, end-i, T)v = V_t.reshape(Bh, T, self.head_dim)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)out[:, i:end] = oreturn self.to_out(out)8 unmodified linesself.head = nn.Linear(config.d_model, config.vocab_size, bias=False)self.resid_dropout = nn.Dropout(config.dropout)# Proper initialization sequence to preserve weight tying!# First randomly initialize everything...self.apply(self._init_weights)# THEN explicitly tie the weightsself.head.weight = self.emb.weightdef _init_weights(self, module: nn.Module):15 unmodified lineslogits = self.head(self.norm(x))loss = Noneif targets is not None:# targets with value -100 are automatically ignored in cross_entropyloss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-100)return logits, loss6 unmodified lines78910111213141516171819202 unmodified lines23242526272829303132333411 unmodified lines4647484950515253543 unmodified lines5859606162636465666768697071727374757677787980818283848586878889904 unmodified lines95969798991001011021031048 unmodified lines11311411511611711811912015 unmodified lines1361371381391406 unmodified lines@dataclassclass ModelConfig:"""Configuration for ViuResonance100M - T4 Optimized"""vocab_size: int = 64000d_model: int = 1024n_layers: int = 12n_heads: int = 16dropout: float = 0.1chunk_size: int = 256 # T4 ke liye 256, 512 se OOM aayegamax_seq_len: int = 4096class RMSNorm(nn.Module):def __init__(self, dim: int, eps: float = 1e-6):2 unmodified linesself.eps = epsdef forward(self, x: torch.Tensor) -> torch.Tensor:# T4 fp16 me stable rakhne ke liye float32 me norm# Original se same logic, bas efficientreturn F.rms_norm(x.float(), (x.shape[-1],), self.weight.float(), self.eps).to(x.dtype)# Fallback agar F.rms_norm na ho:# norm_x = x.float() * torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + self.eps)# return (norm_x * self.weight.float()).to(x.dtype)class ResonanceLayerKaggle(nn.Module):def __init__(self, config: ModelConfig):11 unmodified linesself.to_v = nn.Linear(config.d_model, config.d_model, bias=False)self.to_out = nn.Linear(config.d_model, config.d_model, bias=False)self.norm = RMSNorm(config.d_model)# T4: pos cache - har forward me arange banane se bachaoself.register_buffer("pos_cache", torch.arange(config.max_seq_len, dtype=torch.long), persistent=False)def forward(self, x: torch.Tensor) -> torch.Tensor:B, T, C = x.shape3 unmodified linesfreq = torch.tanh(self.to_freq(h)) * 2.0 # B,T,Hphase = torch.tanh(self.to_phase(h)) * math.pi# pos cache use karo, T tak sliceif T > self.pos_cache.shape[0]:# Agar kabhi bada T aaye to dynamically banaopos = torch.arange(T, device=x.device, dtype=torch.long)else:pos = self.pos_cache[:T]out = torch.empty(B, T, C, device=x.device, dtype=x.dtype)for i in range(0, T, self.chunk_size):end = min(i+self.chunk_size, T)chunk_len = end - iphase_i = phase[:, i:end, :].permute(0,2,1).unsqueeze(-1) # B,H,chunk,1phase_j = phase.permute(0,2,1).unsqueeze(-2) # B,H,1,Trow_idx = torch.arange(i, end, device=x.device, dtype=torch.long)[:, None]col_idx = pos[None, :]dist_long = (row_idx - col_idx).clamp(min=0)dist = dist_long.to(freq.dtype).view(1, 1, chunk_len, T)freq_i = freq[:, i:end, :].permute(0,2,1).unsqueeze(-1)angle = (phase_i - phase_j) + freq_i * dist * 0.05score = torch.cos(angle) # B,H,chunk,Tcausal_bool = (row_idx >= col_idx).view(1,1,chunk_len,T)score = score.masked_fill(~causal_bool, 0.0)score = score / math.sqrt(self.head_dim)4 unmodified linesV_t = V.permute(0,2,1,3).contiguous() # B,H,T,DBh = B * self.n_headss = score.reshape(Bh, chunk_len, T)v = V_t.reshape(Bh, T, self.head_dim)o = torch.bmm(s, v).view(B, self.n_heads, chunk_len, self.head_dim).permute(0,2,1,3).reshape(B, chunk_len, C)out[:, i:end] = oreturn self.to_out(out)8 unmodified linesself.head = nn.Linear(config.d_model, config.vocab_size, bias=False)self.resid_dropout = nn.Dropout(config.dropout)# Sahi order: pehle init, phir tieself.apply(self._init_weights)self.head.weight = self.emb.weightdef _init_weights(self, module: nn.Module):15 unmodified lineslogits = self.head(self.norm(x))loss = Noneif targets is not None:loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-100)return logits, loss
1234567894 unmodified lines1415161718192049 unmodified lines70717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111223 unmodified lines1361371381391401413 unmodified lines14514614714814915015115215315415515615715815916016116216316416516619 unmodified lines1861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442 unmodified lines2472482492502512522536 unmodified lines2602612622632642652662672682692 unmodified lines2722732742752762772782792802812822832842 unmodified lines2872882892902912922932942952962972982996 unmodified lines3063073083093103113121 unmodified line3143153163173183193203213223233243253263273283293303313323333 unmodified lines3373383393403413423433443453463473483493 unmodified lines353354355356357358359360361362363364365366367368import os# Setup env vars for robust Kaggle trainingos.environ["NCCL_P2P_DISABLE"] = "1"os.environ["NCCL_IB_DISABLE"] = "1"os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "1"import mathimport time4 unmodified linesimport torchimport torch.distributed as distfrom torch.nn.parallel import DistributedDataParallel as DDPfrom torch.cuda.amp import GradScalerimport numpy as npfrom transformers import AutoTokenizerfrom huggingface_hub import hf_hub_download, HfApi49 unmodified linesp = Path(p_str)if (p / "tokenizer.json").exists() or (p / "vocab.json").exists():try:return AutoTokenizer.from_pretrained(str(p), local_files_only=True, use_fast=fast, trust_remote_code=True)except Exception as e:if "sentencepiece" in str(e).lower() or "tiktoken" in str(e).lower():continuetry:return AutoTokenizer.from_pretrained(model_repo, subfolder=subfolder, token=hf_token, use_fast=fast, trust_remote_code=True)except Exception as e:passtry:return AutoTokenizer.from_pretrained(model_repo, token=hf_token, use_fast=fast, trust_remote_code=True)except Exception as e:passif is_main:logger.warning("Tokenizer failed, using dummy vocab 64000")return Nonedef load_checkpoint(model, optimizer, scaler, api, token, repo_id, filename="checkpoints/latest_chk.pt", strict=False):local_path = "latest_chk.pt"try:logger.info(f"Checking for existing checkpoint on HF: {filename}")hf_hub_download(repo_id=repo_id, filename=filename, local_dir=".", token=token)# Security Note: weights_only=False is used here to allow loading the optimizer state safely inside our trusted environment.ckpt = torch.load(local_path, map_location="cpu", weights_only=False)missing, unexpected = model.load_state_dict(ckpt["model"], strict=strict)if missing or unexpected:logger.warning(f"Checkpoint loaded with Missing keys: {missing} | Unexpected keys: {unexpected}")else:logger.info("Model weights loaded successfully.")optimizer.load_state_dict(ckpt["optimizer"])if "scaler" in ckpt and scaler is not None:scaler.load_state_dict(ckpt["scaler"])step = ckpt.get("step", 0)logger.info(f"Resuming from step {step}")Path(local_path).unlink(missing_ok=True)return stepexcept (EntryNotFoundError, HfHubHTTPError):logger.info("No checkpoint found on HF. Starting from scratch.")23 unmodified linesfiles = self.api.list_repo_files(repo_id=self.repo_id, repo_type="model", token=self.token)self.available_files = [f for f in files if f.startswith("shards/") and f.endswith(".bin") and not f.endswith("_val.bin")]np.random.shuffle(self.available_files)def fill(self, ctx_len):max_attempts = self.max_pool * 53 unmodified linesraise RuntimeError("Failed to fill ShardPool: too many invalid shards.")if not self.available_files:self._refresh_file_list()f = self.available_files.pop()local_p = hf_hub_download(repo_id=self.repo_id, repo_type="dataset", filename=f, local_dir=self.work_dir, token=self.token)# Safe dtype selectiondtype = np.uint16 if self.vocab_size <= 65535 else np.uint32mmap_arr = np.memmap(local_p, dtype=dtype, mode="r")if len(mmap_arr) < ctx_len + 1:logger.warning(f"Shard {f} is too small ({len(mmap_arr)} tokens). Discarding.")del mmap_arrPath(local_p).unlink(missing_ok=True)attempts += 1continueself.pool.append((local_p, mmap_arr))logger.info(f"Loaded shard {f}")def sample_batch(self, batch_size, ctx_len, rng):xs, ys = [], []19 unmodified lineslogger.warning(f"Failed to delete {old_path}: {e}")def main():parser = argparse.ArgumentParser()parser.add_argument("--max-steps", type=int, default=100)parser.add_argument("--micro-batch", type=int, default=2)parser.add_argument("--grad-accum", type=int, default=16)parser.add_argument("--eval-every", type=int, default=500)parser.add_argument("--save-every", type=int, default=500)parser.add_argument("--rotate-every", type=int, default=500)parser.add_argument("--lr", type=float, default=3e-4)parser.add_argument("--weight-decay", type=float, default=0.1)parser.add_argument("--ctx-len", type=int, default=2048)parser.add_argument("--vocab-size", type=int, default=None)args = parser.parse_args()token = get_hf_token()rank, local_rank, world_size, device, is_ddp = setup_ddp()is_main = (rank == 0)# Random seedseed = 42 + ranktorch.manual_seed(seed)np.random.seed(seed)rng = np.random.default_rng(seed)# Load resourcestokenizer = load_tokenizer_robust(token, "ViuAI/ViuRec", "tokenizer", is_main)vocab_size = args.vocab_size or (len(tokenizer) if tokenizer is not None else 64000)from model import ViuResonance100M, ModelConfigconfig = ModelConfig(vocab_size=vocab_size)model = ViuResonance100M(config).to(device)if is_ddp:model = DDP(model, device_ids=[local_rank], output_device=local_rank, broadcast_buffers=False)unwrapped_model = model.moduleelse:unwrapped_model = model# Optional torch.compile fallbacktry:model = torch.compile(model)if is_main: logger.info("Compiled model successfully.")except Exception as e:if is_main: logger.warning(f"Failed to compile model: {e}. Falling back to eager mode.")# Optimizertry:optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.weight_decay, betas=(0.9, 0.95), fused=True)except:if is_main: logger.warning("fused=True failed for AdamW. Falling back to non-fused.")optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.weight_decay, betas=(0.9, 0.95))# GradScaler for safe fp16/bf16scaler = GradScaler(enabled=not torch.cuda.is_bf16_supported())api = HfApi()start_step = load_checkpoint(unwrapped_model, optimizer, scaler, api, token, "ViuAI/ViuRec", strict=False)2 unmodified linesshard_pool = ShardPool(api, "ViuAI/viuai-500m-data", work_dir / "shards", token, vocab_size)shard_pool.fill(args.ctx_len)# Val Data Safely (cap at 20M tokens)val_tokens = Noneif is_main:logger.info("Loading validation data...")6 unmodified linesval_p = hf_hub_download(repo_id="ViuAI/viuai-500m-data", repo_type="dataset", filename=val_files[0], local_dir=work_dir, token=token)dtype = np.uint16 if vocab_size <= 65535 else np.uint32val_arr = np.memmap(val_p, dtype=dtype, mode="r")max_toks = 20_000_000val_tokens = np.array(val_arr[:max_toks]) # Copy to RAM, safely cappeddel val_arrPath(val_p).unlink(missing_ok=True)except Exception as e:logger.warning(f"Failed to load val data: {e}")2 unmodified linesif val_tokens is None or len(val_tokens) < args.ctx_len + 1: return 0.0unwrapped_model.eval()val_loss = 0.0val_iters = 20for _ in range(val_iters):i = rng.integers(0, len(val_tokens) - args.ctx_len - 1)x = torch.from_numpy(val_tokens[i:i+args.ctx_len].astype(np.int64)).unsqueeze(0).to(device, non_blocking=True)y = torch.from_numpy(val_tokens[i+1:i+1+args.ctx_len].astype(np.int64)).unsqueeze(0).to(device, non_blocking=True)with torch.autocast(device_type="cuda", dtype=torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16):# Pass use_checkpoint=False for evaluation_, loss = unwrapped_model(x, y, use_checkpoint=False)val_loss += loss.item()unwrapped_model.train()2 unmodified lines# Training Loopmodel.train()if is_main:logger.info(f"Starting training for {args.max_steps} steps...")for step in range(start_step, args.max_steps):# LR Schedulewarmup = 1000progress = min(1.0, step / max(1, warmup))lr = args.lr * progress if step < warmup else args.lr * (0.5 * (1.0 + math.cos(math.pi * (step - warmup) / max(1, args.max_steps - warmup))))for param_group in optimizer.param_groups:param_group['lr'] = lr6 unmodified linesx = torch.from_numpy(x_np).to(device, non_blocking=True)y = torch.from_numpy(y_np).to(device, non_blocking=True)with torch.autocast(device_type="cuda", dtype=torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16):_, loss = model(x, y)loss = loss / args.grad_accum1 unmodified lineaccum_loss += loss.item()del x, y, loss# Safe Gradient Clipping with Scalerscaler.unscale_(optimizer)torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)# Check for NaNshas_nan = not math.isfinite(accum_loss)for p in model.parameters():if p.grad is not None and not torch.isfinite(p.grad).all():has_nan = Truebreakif has_nan:if is_main: logger.warning(f"NaN/Inf detected at step {step}! Skipping optimizer step.")optimizer.zero_grad(set_to_none=True)continuescaler.step(optimizer)3 unmodified linesif is_main and step % 10 == 0:tok_s = (args.micro_batch * args.grad_accum * args.ctx_len * world_size) / dt if dt > 0 else 0mem_alloc = torch.cuda.memory_allocated(device) / 1e9mem_res = torch.cuda.memory_reserved(device) / 1e9logger.info(f"step {step:5d}/{args.max_steps} | loss {accum_loss:.4f} | lr {lr:.2e} | {tok_s:.0f} tok/s | mem alloc={mem_alloc:.2f}GB res={mem_res:.2f}GB")if step > start_step and step % args.rotate_every == 0:shard_pool.rotate_one()shard_pool.fill(args.ctx_len)if step > start_step and step % args.eval_every == 0 and is_main:val_loss = evaluate()3 unmodified linesif is_ddp: dist.barrier()if is_main:logger.info(f"Saving checkpoint at step {step}...")chk = {"model": unwrapped_model.state_dict(),"optimizer": optimizer.state_dict(),"scaler": scaler.state_dict(),"step": step,}torch.save(chk, "latest_chk.pt")try:api.upload_file(path_or_fileobj="latest_chk.pt",path_in_repo="checkpoints/latest_chk.pt",repo_id="ViuAI/ViuRec",token=token12345678910114 unmodified lines161718192021222349 unmodified lines73747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113223 unmodified lines1561571581591601611623 unmodified lines16616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819 unmodified lines2182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902 unmodified lines2932942952962972982996 unmodified lines3063073083093103113123133143153162 unmodified lines3193203213223233243253263273283293302 unmodified lines3333343353363373383393403413423433443453463473486 unmodified lines3553563573583593603611 unmodified line3633643653663673683693703713723733743753763773783793803813823833843 unmodified lines3883893903913923933943953963973983994004014023 unmodified lines406407408409410411412413414415416417418419420421422423import os# T4 ke liye robust envos.environ["NCCL_P2P_DISABLE"] = "1"os.environ["NCCL_IB_DISABLE"] = "1"os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "1"# T4 optimizationos.environ["TOKENIZERS_PARALLELISM"] = "false"import mathimport time4 unmodified linesimport torchimport torch.distributed as distfrom torch.nn.parallel import DistributedDataParallel as DDP# FIX 1: Naya amp API - T4 ke liye must (bf16 nahi, fp16)from torch.amp import GradScaler, autocastimport numpy as npfrom transformers import AutoTokenizerfrom huggingface_hub import hf_hub_download, HfApi49 unmodified linesp = Path(p_str)if (p / "tokenizer.json").exists() or (p / "vocab.json").exists():try:tok = AutoTokenizer.from_pretrained(str(p), local_files_only=True, use_fast=fast, trust_remote_code=True)if is_main: logger.info(f"Loaded tokenizer from {p} fast={fast}")return tokexcept Exception as e:if is_main: logger.warning(f"Local tokenizer {p} fast={fast} failed: {e}")if "sentencepiece" in str(e).lower() or "tiktoken" in str(e).lower():continue# HF se tryfor attempt_subfolder in [subfolder, None]:try:if attempt_subfolder:tok = AutoTokenizer.from_pretrained(model_repo, subfolder=attempt_subfolder, token=hf_token, use_fast=fast, trust_remote_code=True)else:tok = AutoTokenizer.from_pretrained(model_repo, token=hf_token, use_fast=fast, trust_remote_code=True)if is_main: logger.info(f"Loaded tokenizer from HF {model_repo} subfolder={attempt_subfolder} fast={fast}")return tokexcept Exception as e:if is_main: logger.warning(f"HF tokenizer try failed fast={fast} subfolder={attempt_subfolder}: {e}")continueif is_main:logger.warning("Tokenizer failed, using dummy vocab 64000")return Nonedef load_checkpoint(model, optimizer, scaler, api, token, repo_id, filename="checkpoints/latest_chk.pt", strict=False):# FIX 2: Path bug fix - hf_hub_download local_dir="." + filename="checkpoints/..." => ./checkpoints/...# Toh local_path bhi wahi hona chahiyelocal_path = Path(filename) # checkpoints/latest_chk.ptlocal_path.parent.mkdir(parents=True, exist_ok=True)try:logger.info(f"Checking for existing checkpoint on HF: {filename}")# download return karta hai actual local pathdownloaded_path = hf_hub_download(repo_id=repo_id, filename=filename, local_dir=".", token=token)logger.info(f"Downloaded checkpoint to {downloaded_path}")# Security: trusted env me hi weights_only=False use karockpt = torch.load(downloaded_path, map_location="cpu", weights_only=False)missing, unexpected = model.load_state_dict(ckpt["model"], strict=strict)if missing or unexpected:logger.warning(f"Checkpoint loaded with Missing: {len(missing)} | Unexpected: {len(unexpected)}")else:logger.info("Model weights loaded successfully.")try:optimizer.load_state_dict(ckpt["optimizer"])except Exception as e:logger.warning(f"Optimizer state load failed, continuing: {e}")if "scaler" in ckpt and scaler is not None:try:scaler.load_state_dict(ckpt["scaler"])except Exception as e:logger.warning(f"Scaler state load failed: {e}")step = ckpt.get("step", 0)logger.info(f"Resuming from step {step}")return stepexcept (EntryNotFoundError, HfHubHTTPError):logger.info("No checkpoint found on HF. Starting from scratch.")23 unmodified linesfiles = self.api.list_repo_files(repo_id=self.repo_id, repo_type="model", token=self.token)self.available_files = [f for f in files if f.startswith("shards/") and f.endswith(".bin") and not f.endswith("_val.bin")]np.random.shuffle(self.available_files)logger.info(f"Found {len(self.available_files)} training shards")def fill(self, ctx_len):max_attempts = self.max_pool * 53 unmodified linesraise RuntimeError("Failed to fill ShardPool: too many invalid shards.")if not self.available_files:self._refresh_file_list()if not self.available_files:raise RuntimeError("No shard files available")f = self.available_files.pop()local_p = hf_hub_download(repo_id=self.repo_id, repo_type="dataset", filename=f, local_dir=self.work_dir, token=self.token)dtype = np.uint16 if self.vocab_size <= 65535 else np.uint32mmap_arr = np.memmap(local_p, dtype=dtype, mode="r")if len(mmap_arr) < ctx_len + 1:logger.warning(f"Shard {f} too small ({len(mmap_arr)}). Discarding.")del mmap_arrPath(local_p).unlink(missing_ok=True)attempts += 1continue# FIX 3: Vocab validation - token vocab se bada toh shard corruptif len(mmap_arr) > 1000:sample_max = int(mmap_arr[:1000].max())if sample_max >= self.vocab_size:logger.warning(f"Shard {f} has token {sample_max} >= vocab {self.vocab_size}. Discarding.")del mmap_arrPath(local_p).unlink(missing_ok=True)attempts += 1continueself.pool.append((local_p, mmap_arr))logger.info(f"Loaded shard {f} ({len(mmap_arr)} tokens)")def sample_batch(self, batch_size, ctx_len, rng):xs, ys = [], []19 unmodified lineslogger.warning(f"Failed to delete {old_path}: {e}")def main():parser = argparse.ArgumentParser(description="ViuResonance Training - T4 Optimized")parser.add_argument("--max-steps", type=int, default=10000)parser.add_argument("--micro-batch", type=int, default=1, help="T4 16GB ke liye 1 rakho")parser.add_argument("--grad-accum", type=int, default=16)parser.add_argument("--eval-every", type=int, default=500)parser.add_argument("--save-every", type=int, default=500)parser.add_argument("--rotate-every", type=int, default=500)parser.add_argument("--lr", type=float, default=3e-4)parser.add_argument("--weight-decay", type=float, default=0.1)parser.add_argument("--ctx-len", type=int, default=1024, help="T4 pe 1024 safe, 2048 OOM de sakta hai")parser.add_argument("--vocab-size", type=int, default=None)args = parser.parse_args()# FIX 4: T4 TF32 optimizationtorch.backends.cuda.matmul.allow_tf32 = Truetorch.backends.cudnn.allow_tf32 = Truetorch.backends.cudnn.benchmark = Truetoken = get_hf_token()rank, local_rank, world_size, device, is_ddp = setup_ddp()is_main = (rank == 0)# FIX 5: Seed properly for CUDAseed = 42 + ranktorch.manual_seed(seed)torch.cuda.manual_seed_all(seed)np.random.seed(seed)rng = np.random.default_rng(seed)# Load tokenizertokenizer = load_tokenizer_robust(token, "ViuAI/ViuRec", "tokenizer", is_main)vocab_size = args.vocab_size or (len(tokenizer) if tokenizer is not None else 64000)if is_main:logger.info(f"Using vocab_size={vocab_size}, ctx_len={args.ctx_len}, device={device}, is_ddp={is_ddp}")from model_fixed_T4 import ViuResonance100M, ModelConfigconfig = ModelConfig(vocab_size=vocab_size, chunk_size=256) # T4 ke liye 256unwrapped_model = ViuResonance100M(config).to(device)# FIX 6: torch.compile pehle, DDP baad me - T4 par compile thoda heavy hai, fallback rakha haitry:unwrapped_model = torch.compile(unwrapped_model, mode="default") # T4 ke liye reduce-overhead bhi try kar sakte hoif is_main: logger.info("Compiled model successfully (before DDP).")compiled = Trueexcept Exception as e:if is_main: logger.warning(f"Failed to compile model: {e}. Falling back to eager.")compiled = Falseif is_ddp:model = DDP(unwrapped_model, device_ids=[local_rank], output_device=local_rank, broadcast_buffers=False)else:model = unwrapped_model# Optimizer - T4 Turing me fused AdamW support nahi hota, fallback rahegatry:optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.weight_decay, betas=(0.9, 0.95), fused=True)if is_main: logger.info("Using fused AdamW")except Exception as e:if is_main: logger.warning(f"fused=True failed ({e}). Using non-fused AdamW for T4.")optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.weight_decay, betas=(0.9, 0.95))# FIX 7: Naya GradScaler API + T4 = fp16 (bf16_supported=False hoga T4 par)use_bf16 = torch.cuda.is_available() and torch.cuda.is_bf16_supported()amp_dtype = torch.bfloat16 if use_bf16 else torch.float16scaler = GradScaler('cuda', enabled=not use_bf16)if is_main:logger.info(f"T4 Detected: bf16_supported={use_bf16}, using amp_dtype={amp_dtype}, scaler_enabled={scaler.is_enabled()}")api = HfApi()start_step = load_checkpoint(unwrapped_model, optimizer, scaler, api, token, "ViuAI/ViuRec", strict=False)2 unmodified linesshard_pool = ShardPool(api, "ViuAI/viuai-500m-data", work_dir / "shards", token, vocab_size)shard_pool.fill(args.ctx_len)# Val Data (only main)val_tokens = Noneif is_main:logger.info("Loading validation data...")6 unmodified linesval_p = hf_hub_download(repo_id="ViuAI/viuai-500m-data", repo_type="dataset", filename=val_files[0], local_dir=work_dir, token=token)dtype = np.uint16 if vocab_size <= 65535 else np.uint32val_arr = np.memmap(val_p, dtype=dtype, mode="r")max_toks = 2_000_000 # T4 RAM ke liye 20M se 2M kiyaval_tokens = np.array(val_arr[:max_toks])del val_arr# Val file ko delete mat karo taki dobara download na ho - T4 pe time bachega# Path(val_p).unlink(missing_ok=True)except Exception as e:logger.warning(f"Failed to load val data: {e}")2 unmodified linesif val_tokens is None or len(val_tokens) < args.ctx_len + 1: return 0.0unwrapped_model.eval()val_loss = 0.0val_iters = 10 # T4 pe kam iterfor _ in range(val_iters):i = rng.integers(0, len(val_tokens) - args.ctx_len - 1)x = torch.from_numpy(val_tokens[i:i+args.ctx_len].astype(np.int64)).unsqueeze(0).to(device, non_blocking=True)y = torch.from_numpy(val_tokens[i+1:i+1+args.ctx_len].astype(np.int64)).unsqueeze(0).to(device, non_blocking=True)with autocast('cuda', dtype=amp_dtype):_, loss = unwrapped_model(x, y, use_checkpoint=False)val_loss += loss.item()unwrapped_model.train()2 unmodified lines# Training Loopmodel.train()if is_main:logger.info(f"Starting training for {args.max_steps} steps from step {start_step}...")for step in range(start_step, args.max_steps):# LR Schedulewarmup = 1000progress = min(1.0, step / max(1, warmup))if step < warmup:lr = args.lr * progresselse:lr = args.lr * (0.5 * (1.0 + math.cos(math.pi * (step - warmup) / max(1, args.max_steps - warmup))))for param_group in optimizer.param_groups:param_group['lr'] = lr6 unmodified linesx = torch.from_numpy(x_np).to(device, non_blocking=True)y = torch.from_numpy(y_np).to(device, non_blocking=True)with autocast('cuda', dtype=amp_dtype):_, loss = model(x, y)loss = loss / args.grad_accum1 unmodified lineaccum_loss += loss.item()del x, y, loss# Gradient Clippingscaler.unscale_(optimizer)torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)# NaN Checkhas_nan = not math.isfinite(accum_loss)if not has_nan:for p in model.parameters():if p.grad is not None and not torch.isfinite(p.grad).all():has_nan = Truebreakif has_nan:if is_main: logger.warning(f"NaN/Inf detected at step {step}! Skipping.")optimizer.zero_grad(set_to_none=True)scaler.update() # FIX 8: NaN par bhi scaler update karna zaruri hai warna stuck hogacontinuescaler.step(optimizer)3 unmodified linesif is_main and step % 10 == 0:tok_s = (args.micro_batch * args.grad_accum * args.ctx_len * world_size) / dt if dt > 0 else 0mem_alloc = torch.cuda.memory_allocated(device) / 1e9 if torch.cuda.is_available() else 0mem_res = torch.cuda.memory_reserved(device) / 1e9 if torch.cuda.is_available() else 0logger.info(f"step {step:5d}/{args.max_steps} | loss {accum_loss:.4f} | lr {lr:.2e} | {tok_s:.0f} tok/s | mem {mem_alloc:.2f}GB/{mem_res:.2f}GB")if step > start_step and step % args.rotate_every == 0:shard_pool.rotate_one()shard_pool.fill(args.ctx_len)if torch.cuda.is_available():torch.cuda.empty_cache() # T4 me fragmentation se bachne ke liyeif step > start_step and step % args.eval_every == 0 and is_main:val_loss = evaluate()3 unmodified linesif is_ddp: dist.barrier()if is_main:logger.info(f"Saving checkpoint at step {step}...")ckpt_path = Path("checkpoints/latest_chk.pt")ckpt_path.parent.mkdir(parents=True, exist_ok=True)chk = {"model": unwrapped_model.state_dict(),"optimizer": optimizer.state_dict(),"scaler": scaler.state_dict(),"step": step,}torch.save(chk, ckpt_path)try:api.upload_file(path_or_fileobj=str(ckpt_path),path_in_repo="checkpoints/latest_chk.pt",repo_id="ViuAI/ViuRec",token=token
code/model.py+28-23
code/train.py+124-69