Upload folder using huggingface_hub
Browse filesFiles changed (2)
- code/build_sft_v15_dataset.py+47-28
- code/train_sft.py+123-110
4 unmodified lines5678910111 unmodified line1314151617189 unmodified lines28293031323334353622 unmodified lines59606162636465220 unmodified lines2862872882892902912921 unmodified line2942952962972982993003013023033043053 unmodified lines3093103113123133143153163173184 unmodified lines32332432532632732832933033120 unmodified lines3523533543553563577 unmodified lines3653663673683693709 unmodified lines38038138238338438538638738838939039139239339439539639739839940040140240340440540611 unmodified lines4184194204214224234244 unmodified linesArchitecture:- Stage 1: 25,000 Pure English Foundation (Reasoning, Code, Math, Instructions, Identity & Natural Chat)- Stage 2: 25,000 Hinglish Adaptation (80% Hinglish/Hindi + 20% English Anchor)- Identity Ingestion: 2,213 dedicated Sarus / ViuAI Identity samples (final_viuai_dataset_identity.json)- Thinking: 100% [THINK] ... [/THINK] Chain-of-Thought- Natural Warm Greetings: Hand-crafted conversational greetings (Zero Robotic Tone)- Sequence Length: MAX_SEQ_LEN = 2048 (Zero Truncation)1 unmodified line1. .jsonl format (Standard Hugging Face / TRL SFTTrainer / LLaMA-Factory)2. .npy packed format (Zero-overhead mmap arrays for ViuAI custom PyTorch engine)- Cross-Platform: 100% Linux & Windows compatible (Zero hardcoded OS paths)================================================================================"""9 unmodified linesfrom transformers import PreTrainedTokenizerFastif hasattr(sys.stdout, "reconfigure"):sys.stdout.reconfigure(encoding="utf-8")if hasattr(sys.stderr, "reconfigure"):sys.stderr.reconfigure(encoding="utf-8")# ------------------------------------------------------------------------------# 1. Configuration & Paths (100% Cross-Platform)22 unmodified linesnp.random.seed(SEED)print("=" * 80)print("π ViuAI Sarus-500M β SFT v15 Master 50k Dataset Builder (with Identity Ingestion)")print("=" * 80)HF_TOKEN = os.environ.get("HF_TOKEN")220 unmodified lineshindi_pool.insert(0, g)# ------------------------------------------------------------------------------# 6. Compose Stage 1 & Stage 2 Datasets# ------------------------------------------------------------------------------print("\n" + "=" * 80)print("π¦ COMPOSING STAGE 1 & STAGE 2 MASTER SETS")1 unmodified line# Stage 1: 25,000 Pure English Foundation (including English Identity)random.shuffle(english_pool)stage1_core = english_pool[: TARGET_STAGE1_SAMPLES - len(en_identity)]stage1_data = stage1_core + en_identityrandom.shuffle(stage1_data)print(f"π― Stage 1 (Pure English Foundation): {len(stage1_data):,} samples")print(f" β’ English Core: {len(stage1_core):,}")print(f" β’ English Identity: {len(en_identity):,} (~2.9%)")# Stage 2: 25,000 Hinglish & Hindi Adaptation (80% Hinglish/Hindi + 20% English Anchor)random.shuffle(hinglish_pool)3 unmodified linestarget_hindi_count = 6000target_anchor_count = 5000stage2_hinglish_core = hinglish_pool[: target_hinglish_count - len(hinglish_identity)]stage2_hinglish = stage2_hinglish_core + hinglish_identitystage2_hindi_core = hindi_pool[: target_hindi_count - len(hindi_identity)]stage2_hindi = stage2_hindi_core + hindi_identitystage2_anchor = english_pool[TARGET_STAGE1_SAMPLES : TARGET_STAGE1_SAMPLES + target_anchor_count]4 unmodified linesrandom.shuffle(stage2_data)print(f"π― Stage 2 (Hinglish Adaptation): {len(stage2_data):,} samples")print(f" β’ Hinglish (Core + Identity): {len(stage2_hinglish):,} (56%) [Identity: {len(hinglish_identity):,}]")print(f" β’ Hindi (Core + Identity): {len(stage2_hindi):,} (24%) [Identity: {len(hindi_identity):,}]")print(f" β’ English Anchor: {len(stage2_anchor):,} (20%)")# ------------------------------------------------------------------------------# 7. Tokenization & Packing Engine (Exports both .jsonl and .npy)20 unmodified linesjsonl_path = os.path.join(output_dir, f"{split_name}.jsonl")jsonl_entries = []for item in tqdm(dataset, desc=f"Processing {split_name} ({len(dataset):,})"):inst = item["instruction"]7 unmodified linesthought_str = f"[THINK]\n{th}\n[/THINK]\n"response_str = f"{resp}<|endofturn|>"full_text = f"{prompt_str}{thought_str}{response_str}"# JSONL Entry for TRL SFTTrainer / Hugging Face / LLaMA-Factory9 unmodified lines{"role": "assistant", "content": f"[THINK]\n{th}\n[/THINK]\n{resp}"}]})# Binary Tokenizationprompt_ids = tokenizer.encode(prompt_str, add_special_tokens=False)target_ids = tokenizer.encode(thought_str + response_str, add_special_tokens=False)full_ids = prompt_ids + target_idsif len(full_ids) > MAX_SEQ_LEN:full_ids = full_ids[:MAX_SEQ_LEN]end_id = tokenizer.encode("<|endofturn|>")[-1]full_ids[-1] = end_idlabels = [-100] * min(len(prompt_ids), len(full_ids))remaining = len(full_ids) - len(labels)if remaining > 0:labels.extend(full_ids[len(labels):])token_list.extend(full_ids)label_list.extend(labels)offsets.append(len(token_list))domain_ids.append(d_id)# Save JSONLwith open(jsonl_path, "w", encoding="utf-8") as f:for entry in jsonl_entries:11 unmodified linesnp.save(os.path.join(output_dir, f"{split_name}_offsets.npy"), off_arr)np.save(os.path.join(output_dir, f"{split_name}_domains.npy"), dom_arr)print(f" β Saved {split_name.upper()} NPY: {len(dataset):,} samples | {len(tok_arr):,} total tokens.")metadata = {"stage": stage_name,4 unmodified lines5678910111 unmodified line131415161718199 unmodified lines29303132333435363722 unmodified lines60616263646566220 unmodified lines2872882892902912922931 unmodified line2952962972982993003013023033043053063073 unmodified lines3113123133143153163173183193203213224 unmodified lines32732832933033133233333433520 unmodified lines3563573583593603613627 unmodified lines3703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004019 unmodified lines41141241341441541641741841942042142242342442511 unmodified lines4374384394404414424434 unmodified linesArchitecture:- Stage 1: 25,000 Pure English Foundation (Reasoning, Code, Math, Instructions, Identity & Natural Chat)- Stage 2: 25,000 Hinglish Adaptation (80% Hinglish/Hindi + 20% English Anchor)- Identity Ingestion: Dedicated Sarus / ViuAI Identity samples (final_viuai_dataset_identity.json)- Thinking: 100% [THINK] ... [/THINK] Chain-of-Thought- Natural Warm Greetings: Hand-crafted conversational greetings (Zero Robotic Tone)- Sequence Length: MAX_SEQ_LEN = 2048 (Zero Truncation)1 unmodified line1. .jsonl format (Standard Hugging Face / TRL SFTTrainer / LLaMA-Factory)2. .npy packed format (Zero-overhead mmap arrays for ViuAI custom PyTorch engine)- Cross-Platform: 100% Linux & Windows compatible (Zero hardcoded OS paths)- Production Robustness: Zero negative slicing bug & strict prompt-length validation================================================================================"""9 unmodified linesfrom transformers import PreTrainedTokenizerFastif 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")# ------------------------------------------------------------------------------# 1. Configuration & Paths (100% Cross-Platform)22 unmodified linesnp.random.seed(SEED)print("=" * 80)print("π ViuAI Sarus-500M β SFT v15 Master 50k Dataset Builder (Production Ready)")print("=" * 80)HF_TOKEN = os.environ.get("HF_TOKEN")220 unmodified lineshindi_pool.insert(0, g)# ------------------------------------------------------------------------------# 6. Compose Stage 1 & Stage 2 Datasets (Negative Slicing Safeguarded)# ------------------------------------------------------------------------------print("\n" + "=" * 80)print("π¦ COMPOSING STAGE 1 & STAGE 2 MASTER SETS")1 unmodified line# Stage 1: 25,000 Pure English Foundation (including English Identity)random.shuffle(english_pool)need_stage1 = max(0, TARGET_STAGE1_SAMPLES - len(en_identity))stage1_core = english_pool[:need_stage1]stage1_data = stage1_core + en_identityrandom.shuffle(stage1_data)print(f"π― Stage 1 (Pure English Foundation): {len(stage1_data):,} samples")print(f" β’ English Core: {len(stage1_core):,}")print(f" β’ English Identity: {len(en_identity):,} (~{len(en_identity)/len(stage1_data)*100:.1f}%)")# Stage 2: 25,000 Hinglish & Hindi Adaptation (80% Hinglish/Hindi + 20% English Anchor)random.shuffle(hinglish_pool)3 unmodified linestarget_hindi_count = 6000target_anchor_count = 5000need_hinglish = max(0, target_hinglish_count - len(hinglish_identity))stage2_hinglish_core = hinglish_pool[:need_hinglish]stage2_hinglish = stage2_hinglish_core + hinglish_identityneed_hindi = max(0, target_hindi_count - len(hindi_identity))stage2_hindi_core = hindi_pool[:need_hindi]stage2_hindi = stage2_hindi_core + hindi_identitystage2_anchor = english_pool[TARGET_STAGE1_SAMPLES : TARGET_STAGE1_SAMPLES + target_anchor_count]4 unmodified linesrandom.shuffle(stage2_data)print(f"π― Stage 2 (Hinglish Adaptation): {len(stage2_data):,} samples")print(f" β’ Hinglish (Core + Identity): {len(stage2_hinglish):,} ({len(stage2_hinglish)/len(stage2_data)*100:.1f}%) [Identity: {len(hinglish_identity):,}]")print(f" β’ Hindi (Core + Identity): {len(stage2_hindi):,} ({len(stage2_hindi)/len(stage2_data)*100:.1f}%) [Identity: {len(hindi_identity):,}]")print(f" β’ English Anchor: {len(stage2_anchor):,} ({len(stage2_anchor)/len(stage2_data)*100:.1f}%)")# ------------------------------------------------------------------------------# 7. Tokenization & Packing Engine (Exports both .jsonl and .npy)20 unmodified linesjsonl_path = os.path.join(output_dir, f"{split_name}.jsonl")jsonl_entries = []skipped_long_prompts = 0for item in tqdm(dataset, desc=f"Processing {split_name} ({len(dataset):,})"):inst = item["instruction"]7 unmodified linesthought_str = f"[THINK]\n{th}\n[/THINK]\n"response_str = f"{resp}<|endofturn|>"# Binary Tokenizationprompt_ids = tokenizer.encode(prompt_str, add_special_tokens=False)# SAFEGUARD 1: Skip if prompt itself fills or exceeds context windowif len(prompt_ids) >= MAX_SEQ_LEN:skipped_long_prompts += 1continuetarget_ids = tokenizer.encode(thought_str + response_str, add_special_tokens=False)full_ids = prompt_ids + target_idsif len(full_ids) > MAX_SEQ_LEN:full_ids = full_ids[:MAX_SEQ_LEN]end_id = tokenizer.encode("<|endofturn|>")[-1]full_ids[-1] = end_idlabels = [-100] * min(len(prompt_ids), len(full_ids))remaining = len(full_ids) - len(labels)# SAFEGUARD 2: Skip if no target tokens left after truncationif remaining <= 0:skipped_long_prompts += 1continuelabels.extend(full_ids[len(labels):])full_text = f"{prompt_str}{thought_str}{response_str}"# JSONL Entry for TRL SFTTrainer / Hugging Face / LLaMA-Factory9 unmodified lines{"role": "assistant", "content": f"[THINK]\n{th}\n[/THINK]\n{resp}"}]})token_list.extend(full_ids)label_list.extend(labels)offsets.append(len(token_list))domain_ids.append(d_id)if skipped_long_prompts > 0:print(f" β οΈ Skipped {skipped_long_prompts} samples with prompt >= {MAX_SEQ_LEN}")# Save JSONLwith open(jsonl_path, "w", encoding="utf-8") as f:for entry in jsonl_entries:11 unmodified linesnp.save(os.path.join(output_dir, f"{split_name}_offsets.npy"), off_arr)np.save(os.path.join(output_dir, f"{split_name}_domains.npy"), dom_arr)print(f" β Saved {split_name.upper()} NPY: {len(jsonl_entries):,} samples | {len(tok_arr):,} total tokens.")metadata = {"stage": stage_name,
1234567891011126 unmodified lines19202122232415 unmodified lines4041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581 unmodified line1601611621631641651661671681691701715 unmodified lines17717817918018118218318418518618718818919019119219319419519619719819932 unmodified lines23223323423523623717 unmodified lines25525625725825926026116 unmodified lines27827928028128228328428523 unmodified lines30931031131231331431531631731831932032132220 unmodified lines3433443453463473483493501 unmodified line3523533543553563573583593603613623633643653663673683693703 unmodified lines37437537637737837926 unmodified lines4064074084094104114124132 unmodified lines4164174184194204214224234244254264274284 unmodified lines4334344354364374384394404414424434441 unmodified line446447448449450451452453454455456457# ==============================================================================# π 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# ==============================================================================6 unmodified linesimport jsonimport randomimport argparsefrom datetime import datetime, timezoneimport numpy as np15 unmodified linesif torch.cuda.is_available():torch.cuda.manual_seed_all(42)# Add code directory to path and auto-fetch companion files if missingcur_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 ViuAIConfigfrom model import ViuAIexcept 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:passtry:from config import ViuAIConfigfrom model import ViuAIexcept 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 ViuAIConfigfrom 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 Noneself.n_samples = len(self.offsets) - 1def __len__(self):return self.n_samplesdef __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 0return 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] = inppadded_labels[i, :length] = lblreturn 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_stepsif step > total_steps:return min_lrdecay_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 Datasetstage_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 Checkpointif 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",1 unmodified linetoken=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:5 unmodified linestoken=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()32 unmodified linesprint(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 Datasets17 unmodified linesbatch_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())16 unmodified lines)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))23 unmodified lines]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_accumtotal_steps = steps_per_epoch * args.epochswarmup_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 Setupdtype = 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 Helper20 unmodified linesreturn avg_loss, ppl# Initial Validationprint("π Running initial pre-training validation...")val_loss, val_ppl = evaluate()print(f"π Initial Validation Loss: {val_loss:.4f} | Perplexity: {val_ppl:.2f}")1 unmodified lineglobal_step = 0best_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.0epoch_batches = 0accum_loss = 0.03 unmodified linesfor 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:out = model(inputs)26 unmodified lines# Loggingif global_step % 5 == 0 or global_step == 1:elapsed = time.time() - start_timetokens_processed = global_step * args.batch_size * args.grad_accum * 512 # rough avg seqspeed = 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 & Checkpointing2 unmodified linesis_best = val_loss < best_val_lossif is_best:best_val_loss = val_lossprint(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 Checkpointprint(f"πΎ Saving {args.stage.upper()} Final Checkpoint to: {save_path}...")torch.save({"model_state_dict": model.state_dict(),"config": config.__dict__,4 unmodified lines}, save_path)print(f"β Saved Checkpoint ({os.path.getsize(save_path)/(1024**3):.2f} GB)")# Push to Hugging Faceif 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,1 unmodified linerepo_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()1234567891011121314156 unmodified lines2223242526272815 unmodified lines44454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551 unmodified line1571581591601611621631641651661675 unmodified lines17317417517617717817918018118218318418518618718818919019119219319419519619719832 unmodified lines23123223323423523623717 unmodified lines25525625725825926026116 unmodified lines27827928028128228328423 unmodified lines30830931031131231331431531631731831932032132232332432520 unmodified lines3463473483493503513521 unmodified line3543553563573583593603613623633643653663673683693703713 unmodified lines37537637737837938038126 unmodified lines4084094104114124134142 unmodified lines4174184194204214224234244254264274284294304314324334344354364374384394404 unmodified lines4454464474484494504514524534544551 unmodified line457458459460461462463464465466467468469470# ==============================================================================# π ViuAI Sarus-500M β SFT v15 Master 2-Stage Training Engine (Production Ready)# ==============================================================================# 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 (or auto-detected)# - Hardware Adaptability: Auto-detects VRAM & auto-tunes batch_size & grad_accum (Default 8 for 24GB)# - Gradient Accumulation Cleanup: Zero leftover micro-batch loss at epoch boundaries# - Dynamic Speed Tracking: Precise real-time tokens/sec calculation# - 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# ==============================================================================6 unmodified linesimport jsonimport randomimport argparseimport contextlibfrom datetime import datetime, timezoneimport numpy as np15 unmodified linesif torch.cuda.is_available():torch.cuda.manual_seed_all(42)# Import ViuAI Architecturecur_dir = os.path.dirname(os.path.abspath(__file__))if cur_dir not in sys.path:sys.path.insert(0, cur_dir)from config import ViuAIConfigfrom model import ViuAI# --- 1. Memory-Mapped Dataset for Zero-Overhead Token Streaming ---class SFTDataset(Dataset):def __init__(self, ids_path, labels_path, offsets_path, domains_path=None):super().__init__()self.offsets = np.load(offsets_path, mmap_mode="r")self.num_samples = len(self.offsets) - 1self.ids = np.load(ids_path, mmap_mode="r")self.labels = np.load(labels_path, mmap_mode="r")self.domains = np.load(domains_path, mmap_mode="r") if (domains_path and os.path.exists(domains_path)) else Nonedef __len__(self):return self.num_samplesdef __getitem__(self, idx):start = int(self.offsets[idx])end = int(self.offsets[idx + 1])seq_ids = torch.from_numpy(self.ids[start:end].astype(np.int64))seq_labels = torch.from_numpy(self.labels[start:end].astype(np.int64))domain_id = int(self.domains[idx]) if self.domains is not None else 0return seq_ids, seq_labels, domain_id# --- 2. Dynamic Padding Collate Function ---def collate_fn(batch, pad_token_id=0, ignore_index=-100):inputs, labels, domain_ids = zip(*batch)max_len = max(x.size(0) for x in inputs)# Align to multiple of 8 for Tensor Core efficiencymax_len = ((max_len + 7) // 8) * 8batch_inputs = torch.full((len(batch), max_len), pad_token_id, dtype=torch.long)batch_labels = torch.full((len(batch), max_len), ignore_index, dtype=torch.long)for i, (inp, lbl) in enumerate(zip(inputs, labels)):batch_inputs[i, :inp.size(0)] = inpbatch_labels[i, :lbl.size(0)] = lblreturn batch_inputs, batch_labels, torch.tensor(domain_ids, dtype=torch.long)# --- 3. Cosine Learning Rate Schedule with Warmup ---def get_lr(it, warmup_steps, total_steps, max_lr, min_lr):if it < warmup_steps:return max_lr * (it + 1) / max(1, warmup_steps)if it > total_steps:return min_lrdecay_ratio = (it - warmup_steps) / max(1, total_steps - warmup_steps)coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio))return min_lr + coeff * (max_lr - min_lr)# --- 4. Auto-detect Optimal Batch Size by Hardware VRAM ---def auto_detect_batch_params():if not torch.cuda.is_available():return 4, 16vram_gb = torch.cuda.get_device_properties(0).total_memory / (1024 ** 3)if vram_gb >= 70: # H100, H200, A100-80GBreturn 32, 4 # 32 micro batch * 4 accum = 128 effectiveelif vram_gb >= 35: # A100-40GB, A6000return 16, 8 # 16 micro batch * 8 accum = 128 effectiveelif vram_gb >= 20: # RTX 3090, RTX 4090, L4, A10G (24GB)return 8, 16 # 8 micro batch * 16 accum = 128 effectiveelse: # T4, V100 (16GB)return 4, 32 # 4 micro batch * 32 accum = 128 effective# --- 5. Self-Contained Cloud Download Helper ---def ensure_cloud_data_and_checkpoint(stage: str, data_dir: str, ckpt_path: str, token: str = None):stage_subfolder = "sft_v15_stage1" if stage == "stage1" else "sft_v15_stage2"target_data_folder = os.path.join(data_dir, stage_subfolder)needed_data_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"]missing_data = any(not os.path.exists(os.path.join(target_data_folder, f)) for f in needed_data_files)if missing_data:print(f"\nπ Dataset missing locally for {stage_subfolder}. Downloading from Hugging Face Hub (ViuAI/viuai-500m-sft-tokenized)...")os.makedirs(target_data_folder, exist_ok=True)for f in needed_data_files + ["train.jsonl", "val.jsonl", "metadata.json"]:try:hf_hub_download(repo_id="ViuAI/viuai-500m-sft-tokenized",subfolder=stage_subfolder,filename=f,local_dir=data_dir,repo_type="dataset",token=token)except Exception as e:passprint(f"β Downloaded {stage_subfolder} dataset successfully!")if not os.path.exists(ckpt_path):print(f"\nπ Initial Checkpoint missing at {ckpt_path}. Downloading from Hugging Face Hub (ViuAI/ViuAI-500M)...")os.makedirs(os.path.dirname(ckpt_path), exist_ok=True)if stage == "stage1":hf_hub_download(repo_id="ViuAI/ViuAI-500M",filename="checkpoints/ckpt_latest.pt",1 unmodified linetoken=token)else: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(os.path.dirname(ckpt_path))),token=token)except Exception:5 unmodified linestoken=token)# --- 6. Main Training Pipeline ---def train():auto_b, auto_ga = auto_detect_batch_params()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=auto_b, help=f"Micro batch size (Auto-detected: {auto_b})")parser.add_argument("--grad_accum", type=int, default=auto_ga, help=f"Gradient accumulation steps (Auto-detected: {auto_ga})")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=False, help="Auto-upload checkpoint to Hugging Face (Default: False)")parser.add_argument("--hf_token", type=str, default=None, help="Hugging Face API token")args = parser.parse_args()32 unmodified linesprint(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(f" β’ Push to HF: {args.push_to_hf}")print("=" * 80)# 1. Load Datasets17 unmodified linesbatch_size=args.batch_size,shuffle=True,collate_fn=collate_fn,drop_last=False,num_workers=2 if torch.cuda.is_available() else 0,pin_memory=torch.cuda.is_available())16 unmodified lines)model = ViuAI(config).to(device)print(f"\nπ 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))23 unmodified lines]optimizer = torch.optim.AdamW(optimizer_grouped_parameters, lr=args.max_lr, betas=(0.9, 0.95), eps=1e-8)steps_per_epoch = math.ceil(len(train_loader) / args.grad_accum)total_steps = steps_per_epoch * args.epochswarmup_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 (Clean dtype mapping)if torch.cuda.is_available():dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16autocast_ctx = torch.amp.autocast(device_type="cuda", dtype=dtype)else:dtype = torch.float32autocast_ctx = contextlib.nullcontext()print(f"β‘ Mixed Precision: {dtype}")# Evaluation Helper20 unmodified linesreturn avg_loss, ppl# Initial Validationprint("\nπ Running initial pre-training validation...")val_loss, val_ppl = evaluate()print(f"π Initial Validation Loss: {val_loss:.4f} | Perplexity: {val_ppl:.2f}")1 unmodified lineglobal_step = 0best_val_loss = float("inf")start_time = time.time()total_tokens_trained = 0model.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("\n" + "=" * 80)print(f"π STARTING SFT v15 {args.stage.upper()} TRAINING")print("=" * 80)for epoch in range(1, args.epochs + 1):print(f"\n--- Epoch {epoch}/{args.epochs} ---")epoch_loss = 0.0epoch_batches = 0accum_loss = 0.03 unmodified linesfor micro_idx, (inputs, labels, _) in enumerate(train_loader):inputs = inputs.to(device, non_blocking=True)labels = labels.to(device, non_blocking=True)total_tokens_trained += inputs.numel()with autocast_ctx:out = model(inputs)26 unmodified lines# Loggingif global_step % 5 == 0 or global_step == 1:elapsed = time.time() - start_timespeed = total_tokens_trained / max(1e-5, 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 & Checkpointing2 unmodified linesis_best = val_loss < best_val_lossif is_best:best_val_loss = val_lossprint(f"\n β [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 ''}\n")# CRITICAL FIX 2: Flush leftover gradient accumulation at epoch boundaryif (micro_idx + 1) % args.grad_accum != 0: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"] = lroptimizer.step()optimizer.zero_grad(set_to_none=True)global_step += 1leftover_count = (micro_idx + 1) % args.grad_accumstep_avg_loss = accum_loss / max(1, leftover_count)accum_loss = 0.0print(f" [Epoch {epoch} Boundary Step {global_step}] Flushed {leftover_count} micro-batches | Loss: {step_avg_loss:.4f}")# Save Final Checkpointprint(f"\nπΎ Saving {args.stage.upper()} Final Checkpoint to: {save_path}...")torch.save({"model_state_dict": model.state_dict(),"config": config.__dict__,4 unmodified lines}, save_path)print(f"β Saved Checkpoint ({os.path.getsize(save_path)/(1024**3):.2f} GB)")# Push to Hugging Face (Only if explicitly enabled with --push_to_hf)if args.push_to_hf:token = args.hf_token or os.environ.get("HF_TOKEN")if token:print(f"\nπ Uploading {stage_ckpt_name} to Hugging Face Model Hub (ViuAI/ViuAI-500M)...")api = HfApi(token=token)api.upload_file(path_or_fileobj=save_path,1 unmodified linerepo_id="ViuAI/ViuAI-500M",repo_type="model")print("π Checkpoint Uploaded to Hugging Face Successfully!")else:print("β οΈ Skipping HF upload: No HF_TOKEN provided.")print("\n" + "=" * 80)print(f"π SFT v15 {args.stage.upper()} COMPLETED SUCCESSFULLY!")print("=" * 80)if __name__ == "__main__":train()
code/build_sft_v15_dataset.py+47-28
code/train_sft.py+123-110