# ============================================================================== # 🚀 ViuAI Sarus-500M — SFT v15 Master 2-Stage Training Engine # ============================================================================== # Architecture: # - Stage 1: Pure English Foundation (25k samples: Reasoning, Code, Math, Instructions, Natural Chat) # - Stage 2: Hinglish Adaptation (25k samples: 80% Hinglish/Hindi + 20% English Anchor) # - Shuffling: Standard Uniform Epoch Shuffle (shuffle=True) — Zero Domain Hijack # - Reasoning: 100% [THINK] ... [/THINK] Loss Masking on Assistant Tokens # - Anti-Overfitting Safeguards: Cosine LR Decay, Weight Decay 0.1, Grad Accum 4 # - Self-Contained Cloud Sync: Auto-downloads tokenized datasets and base checkpoints from HF # - Output Checkpoint: sft_checkpoints/sft_v15/sft_v15_stage1.pt & sft_v15_final.pt # ============================================================================== import os import sys import math import time import glob import json import random import argparse from datetime import datetime, timezone import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader from huggingface_hub import HfApi, hf_hub_download if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8", errors="replace") if hasattr(sys.stderr, "reconfigure"): sys.stderr.reconfigure(encoding="utf-8", errors="replace") # Set random seeds for reproducibility random.seed(42) np.random.seed(42) torch.manual_seed(42) if torch.cuda.is_available(): torch.cuda.manual_seed_all(42) # Add code directory to path and auto-fetch companion files if missing cur_dir = os.path.dirname(os.path.abspath(__file__)) if cur_dir not in sys.path: sys.path.insert(0, cur_dir) try: from config import ViuAIConfig from model import ViuAI except ImportError: for dep in ["config.py", "model.py"]: dep_path = os.path.join(cur_dir, dep) if not os.path.exists(dep_path): try: hf_hub_download( repo_id="ViuAI/ViuAI-500M", filename=f"code/{dep}", local_dir=cur_dir if os.path.basename(cur_dir) == "code" else os.path.join(cur_dir, "code"), token=os.environ.get("HF_TOKEN") ) except Exception: pass try: from config import ViuAIConfig from model import ViuAI except ImportError: p_dir = os.path.abspath(os.path.join(cur_dir, "code")) if os.path.exists(p_dir) and p_dir not in sys.path: sys.path.insert(0, p_dir) from config import ViuAIConfig from model import ViuAI # --- 1. Dataset Class --- class SFTDataset(Dataset): def __init__(self, ids_path, labels_path, offsets_path, domains_path=None): 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.domains = np.load(domains_path) if (domains_path and os.path.exists(domains_path)) else None self.n_samples = len(self.offsets) - 1 def __len__(self): return self.n_samples def __getitem__(self, idx): start = self.offsets[idx] end = self.offsets[idx + 1] input_ids = torch.from_numpy(self.ids[start:end].astype(np.int64)) labels = torch.from_numpy(self.labels[start:end].astype(np.int64)) domain = int(self.domains[idx]) if self.domains is not None else 0 return input_ids, labels, domain # --- 2. Dynamic Padding Batch Collate Function --- def collate_fn(batch, pad_token_id=0): input_ids_list, labels_list, domain_list = zip(*batch) max_len = max(x.size(0) for x in input_ids_list) batch_size = len(input_ids_list) padded_inputs = torch.full((batch_size, max_len), pad_token_id, dtype=torch.int64) padded_labels = torch.full((batch_size, max_len), -100, dtype=torch.int64) for i, (inp, lbl) in enumerate(zip(input_ids_list, labels_list)): length = inp.size(0) padded_inputs[i, :length] = inp padded_labels[i, :length] = lbl return padded_inputs, padded_labels, torch.tensor(domain_list, dtype=torch.uint8) # --- 3. Cosine Learning Rate Schedule with Warmup --- def get_lr(step, warmup_steps, total_steps, max_lr, min_lr): if step < warmup_steps: return max_lr * (step + 1) / warmup_steps if step > total_steps: return min_lr decay_ratio = (step - warmup_steps) / (total_steps - warmup_steps) coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio)) return min_lr + coeff * (max_lr - min_lr) # --- 4. Remote Cloud Downloader --- def ensure_cloud_data_and_checkpoint(stage: str, data_dir: str, ckpt_path: str, hf_token: str = None): """Auto-downloads tokenized datasets and starting checkpoints if missing.""" token = hf_token or os.environ.get("HF_TOKEN") # 1. Ensure Dataset stage_subfolder = "sft_v15_stage1" if stage == "stage1" else "sft_v15_stage2" target_data_folder = os.path.join(data_dir, stage_subfolder) required_files = [ "train_tokens.npy", "train_labels.npy", "train_offsets.npy", "train_domains.npy", "val_tokens.npy", "val_labels.npy", "val_offsets.npy", "val_domains.npy", "metadata.json" ] missing_data = any(not os.path.exists(os.path.join(target_data_folder, f)) for f in required_files) if missing_data: print(f"📥 Downloading dataset {stage_subfolder} from HF ViuAI/viuai-500m-sft-tokenized...") os.makedirs(target_data_folder, exist_ok=True) for f in required_files: try: hf_hub_download( repo_id="ViuAI/viuai-500m-sft-tokenized", filename=f"{stage_subfolder}/{f}", local_dir=data_dir, repo_type="dataset", token=token ) except Exception as e: print(f" ⚠️ Note on {f}: {e}") print(f"✅ Dataset {stage_subfolder} ready at {target_data_folder}") # 2. Ensure Starting Checkpoint if not os.path.exists(ckpt_path): os.makedirs(os.path.dirname(ckpt_path), exist_ok=True) if stage == "stage1": print(f"📥 Downloading base checkpoint from HF ViuAI/ViuAI-500M (checkpoints/ckpt_latest.pt)...") hf_hub_download( repo_id="ViuAI/ViuAI-500M", filename="checkpoints/ckpt_latest.pt", local_dir=os.path.dirname(os.path.dirname(ckpt_path)), token=token ) else: print(f"📥 Downloading Stage 1 checkpoint from HF ViuAI/ViuAI-500M (sft_checkpoints/sft_v15/sft_v15_stage1.pt)...") try: hf_hub_download( repo_id="ViuAI/ViuAI-500M", filename="sft_checkpoints/sft_v15/sft_v15_stage1.pt", local_dir=os.path.dirname(os.path.dirname(ckpt_path)), token=token ) except Exception: print(" ⚠️ Stage 1 checkpoint not found in cloud, falling back to base checkpoint.") hf_hub_download( repo_id="ViuAI/ViuAI-500M", filename="checkpoints/ckpt_latest.pt", local_dir=os.path.dirname(os.path.dirname(ckpt_path)), token=token ) # --- 5. Main Training Pipeline --- def train(): parser = argparse.ArgumentParser(description="ViuAI Sarus-500M — SFT v15 Master Training Engine") parser.add_argument("--stage", type=str, choices=["stage1", "stage2"], default="stage1", help="Training curriculum stage: 'stage1' (Pure English) or 'stage2' (Hinglish Adaptation)") parser.add_argument("--data_dir", type=str, default=None, help="Root directory containing tokenized_data") parser.add_argument("--init_ckpt", type=str, default=None, help="Initial checkpoint path") parser.add_argument("--output_dir", type=str, default=None, help="Directory to save checkpoints") parser.add_argument("--batch_size", type=int, default=32, help="Micro batch size per forward pass") parser.add_argument("--grad_accum", type=int, default=4, help="Gradient accumulation steps (effective batch = 128)") parser.add_argument("--epochs", type=int, default=2, help="Number of training epochs per stage") parser.add_argument("--max_lr", type=float, default=1.8e-5, help="Peak learning rate for Cosine Schedule") parser.add_argument("--min_lr", type=float, default=1.8e-6, help="Minimum learning rate") parser.add_argument("--weight_decay", type=float, default=0.1, help="AdamW weight decay") parser.add_argument("--warmup_ratio", type=float, default=0.04, help="Warmup ratio of total steps") parser.add_argument("--eval_interval", type=int, default=25, help="Validation evaluation step interval") parser.add_argument("--push_to_hf", action="store_true", default=True, help="Auto-upload checkpoint to Hugging Face") parser.add_argument("--hf_token", type=str, default=None, help="Hugging Face API token") args = parser.parse_args() # Determine Project Paths root_dir = os.path.abspath(os.path.join(cur_dir, "..")) data_dir = args.data_dir or os.path.join(root_dir, "tokenized_data") output_dir = args.output_dir or os.path.join(root_dir, "sft_checkpoints", "sft_v15") os.makedirs(output_dir, exist_ok=True) stage_subfolder = "sft_v15_stage1" if args.stage == "stage1" else "sft_v15_stage2" stage_data_dir = os.path.join(data_dir, stage_subfolder) # Default Checkpoint Loading Path if args.init_ckpt: init_ckpt = args.init_ckpt elif args.stage == "stage1": init_ckpt = os.path.join(root_dir, "checkpoints", "ckpt_latest.pt") else: init_ckpt = os.path.join(output_dir, "sft_v15_stage1.pt") if not os.path.exists(init_ckpt): init_ckpt = os.path.join(root_dir, "checkpoints", "ckpt_latest.pt") # Cloud Sync ensure_cloud_data_and_checkpoint(args.stage, data_dir, init_ckpt, args.hf_token) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print("=" * 80) print(f"🚀 ViuAI Sarus-500M — SFT v15 Training Runner ({args.stage.upper()})") print("=" * 80) print(f" • Stage: {args.stage.upper()} ({'Pure English Foundation' if args.stage == 'stage1' else 'Hinglish Adaptation'})") print(f" • Device: {device} ({torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'CPU'})") print(f" • Data Folder: {stage_data_dir}") print(f" • Init Checkpoint: {init_ckpt}") print(f" • Output Checkpoint:{output_dir}") print(f" • Micro Batch Size: {args.batch_size} (Grad Accum {args.grad_accum} -> Effective Batch {args.batch_size * args.grad_accum})") print(f" • Epochs: {args.epochs}") print(f" • Max / Min LR: {args.max_lr} / {args.min_lr} (Cosine Schedule)") print(f" • Shuffling: Standard Epoch Shuffle (shuffle=True)") print("=" * 80) # 1. Load Datasets train_dataset = SFTDataset( ids_path=os.path.join(stage_data_dir, "train_tokens.npy"), labels_path=os.path.join(stage_data_dir, "train_labels.npy"), offsets_path=os.path.join(stage_data_dir, "train_offsets.npy"), domains_path=os.path.join(stage_data_dir, "train_domains.npy") ) val_dataset = SFTDataset( ids_path=os.path.join(stage_data_dir, "val_tokens.npy"), labels_path=os.path.join(stage_data_dir, "val_labels.npy"), offsets_path=os.path.join(stage_data_dir, "val_offsets.npy"), domains_path=os.path.join(stage_data_dir, "val_domains.npy") ) print(f"✅ Loaded Datasets: {len(train_dataset):,} Train Samples | {len(val_dataset):,} Val Samples") # Standard Uniform DataLoader train_loader = DataLoader( train_dataset, batch_size=args.batch_size, shuffle=True, collate_fn=collate_fn, drop_last=True, num_workers=2 if torch.cuda.is_available() else 0, pin_memory=torch.cuda.is_available() ) val_loader = DataLoader( val_dataset, batch_size=args.batch_size, shuffle=False, collate_fn=collate_fn, drop_last=False ) # 2. Initialize Model & Load Weights config = ViuAIConfig(vocab_size=64003, use_checkpoint=True) model = ViuAI(config).to(device) print(f" 📂 Loading weights from: {init_ckpt}...") ckpt = torch.load(init_ckpt, map_location=device, weights_only=False) state_dict = ckpt.get("model_state_dict", ckpt.get("model", ckpt)) # Clean prefix if needed cleaned_sd = {} for k, v in state_dict.items(): k = k.replace("_orig_mod.", "").replace("module.", "") cleaned_sd[k] = v model.load_state_dict(cleaned_sd, strict=True) print("✅ Checkpoint Weights Loaded Perfectly!") # 3. Optimizer & Schedulers decay_params = [] no_decay_params = [] for name, param in model.named_parameters(): if not param.requires_grad: continue if "norm" in name.lower() or "bias" in name.lower(): no_decay_params.append(param) else: decay_params.append(param) optimizer_grouped_parameters = [ {"params": decay_params, "weight_decay": args.weight_decay}, {"params": no_decay_params, "weight_decay": 0.0} ] optimizer = torch.optim.AdamW(optimizer_grouped_parameters, lr=args.max_lr, betas=(0.9, 0.95), eps=1e-8) steps_per_epoch = len(train_loader) // args.grad_accum total_steps = steps_per_epoch * args.epochs warmup_steps = max(10, int(total_steps * args.warmup_ratio)) print(f"📊 Training Steps: {steps_per_epoch} steps/epoch | Total: {total_steps} steps | Warmup: {warmup_steps} steps") # Mixed Precision Setup dtype = torch.bfloat16 if torch.cuda.is_available() and torch.cuda.is_bf16_supported() else (torch.float16 if torch.cuda.is_available() else torch.float32) autocast_ctx = torch.amp.autocast(device_type="cuda", dtype=dtype) if torch.cuda.is_available() else torch.amp.autocast(device_type="cpu", dtype=torch.bfloat16) print(f"⚡ Mixed Precision: {dtype}") # Evaluation Helper @torch.no_grad() def evaluate(): model.eval() total_val_loss = 0.0 val_tokens = 0 for inps, lbls, _ in val_loader: inps = inps.to(device, non_blocking=True) lbls = lbls.to(device, non_blocking=True) with autocast_ctx: logits = model(inps) shift_logits = logits[..., :-1, :].contiguous() shift_labels = lbls[..., 1:].contiguous() loss = F.cross_entropy(shift_logits.view(-1, 64003), shift_labels.view(-1), ignore_index=-100, reduction="sum") num_active = (shift_labels != -100).sum().item() total_val_loss += loss.item() val_tokens += num_active model.train() avg_loss = total_val_loss / max(1, val_tokens) ppl = math.exp(min(avg_loss, 20.0)) return avg_loss, ppl # Initial Validation print(" 🔍 Running initial pre-training validation...") val_loss, val_ppl = evaluate() print(f"📊 Initial Validation Loss: {val_loss:.4f} | Perplexity: {val_ppl:.2f}") # Training Loop global_step = 0 best_val_loss = float("inf") start_time = time.time() model.train() stage_ckpt_name = "sft_v15_stage1.pt" if args.stage == "stage1" else "sft_v15_final.pt" save_path = os.path.join(output_dir, stage_ckpt_name) print(" " + "=" * 80) print(f"🏁 STARTING SFT v15 {args.stage.upper()} TRAINING") print("=" * 80) for epoch in range(1, args.epochs + 1): print(f" --- Epoch {epoch}/{args.epochs} ---") epoch_loss = 0.0 epoch_batches = 0 accum_loss = 0.0 optimizer.zero_grad(set_to_none=True) for micro_idx, (inputs, labels, _) in enumerate(train_loader): inputs = inputs.to(device, non_blocking=True) labels = labels.to(device, non_blocking=True) with autocast_ctx: logits = model(inputs) shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() loss = F.cross_entropy(shift_logits.view(-1, 64003), shift_labels.view(-1), ignore_index=-100) loss_scaled = loss / args.grad_accum loss_scaled.backward() accum_loss += loss.item() epoch_loss += loss.item() epoch_batches += 1 if (micro_idx + 1) % args.grad_accum == 0: # Step Optimizer torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) lr = get_lr(global_step, warmup_steps, total_steps, args.max_lr, args.min_lr) for param_group in optimizer.param_groups: param_group["lr"] = lr optimizer.step() optimizer.zero_grad(set_to_none=True) global_step += 1 step_avg_loss = accum_loss / args.grad_accum accum_loss = 0.0 # Logging if global_step % 5 == 0 or global_step == 1: elapsed = time.time() - start_time tokens_processed = global_step * args.batch_size * args.grad_accum * 512 # rough avg seq speed = tokens_processed / max(1, elapsed) print(f" Step {global_step:4d}/{total_steps} | Epoch {epoch} | Loss: {step_avg_loss:.4f} | LR: {lr:.2e} | Speed: {speed:,.0f} tok/s | Elapsed: {elapsed/60:.1f}m") # Validation & Checkpointing if global_step % args.eval_interval == 0 or global_step == total_steps: val_loss, val_ppl = evaluate() is_best = val_loss < best_val_loss if is_best: best_val_loss = val_loss print(f" ⭐ [EVAL Step {global_step}] Val Loss: {val_loss:.4f} | Val PPL: {val_ppl:.2f} | Best Val: {best_val_loss:.4f} {'(NEW BEST!)' if is_best else ''} ") # Save Final Checkpoint print(f" 💾 Saving {args.stage.upper()} Final Checkpoint to: {save_path}...") torch.save({ "model_state_dict": model.state_dict(), "config": config.__dict__, "stage": args.stage, "global_step": global_step, "best_val_loss": best_val_loss, "timestamp": datetime.now(timezone.utc).isoformat() }, save_path) print(f"✅ Saved Checkpoint ({os.path.getsize(save_path)/(1024**3):.2f} GB)") # Push to Hugging Face if args.push_to_hf: token = args.hf_token or os.environ.get("HF_TOKEN") if token: print(f" 🚀 Uploading {stage_ckpt_name} to HF ViuAI/ViuAI-500M...") api = HfApi(token=token) api.upload_file( path_or_fileobj=save_path, path_in_repo=f"sft_checkpoints/sft_v15/{stage_ckpt_name}", repo_id="ViuAI/ViuAI-500M", repo_type="model" ) print("🎉 Upload to Hugging Face Completed Successfully!") print(" " + "=" * 80) print(f"🎉 SFT v15 {args.stage.upper()} TRAINING RUN COMPLETE!") print("=" * 80) if __name__ == "__main__": train()