Download code/train_sft.py from ViuAI/ViuAI-500M: direct link, hf CLI and curl.
- Browser
- Download file 19.9 kB
-
https://huggingface.co/ViuAI/ViuAI-500M/resolve/d2d78bd00a3587616c856ba18d40b83f2c2f7329/code/train_sft.py
- Command line
-
hf download hf://ViuAI/ViuAI-500M@d2d78bd00a3587616c856ba18d40b83f2c2f7329/code/train_sft.py
-
curl -L -o train_sft.py https://huggingface.co/ViuAI/ViuAI-500M/resolve/d2d78bd00a3587616c856ba18d40b83f2c2f7329/code/train_sft.py
19.9 kB
| # ============================================================================== | |
| # ViuAI 500M β SFT v10 Domain-Balanced Training Engine | |
| # ============================================================================== | |
| # - 8 Stratified Domain Datasets (Identity, Math, Reasoning, Translation, Chit-Chat, Personas) | |
| # - Natural Cognitive Sequences: [THINK] ... [/THINK] on complex tasks, direct on factual | |
| # - Anti-Overfitting Safeguards: 1 Epoch, LR 1.8e-5 (Cosine), Weight Decay 0.1, Grad Accum 4 | |
| # - Loss Masking: Computes loss strictly on assistant response tokens (Prompt tokens = -100) | |
| # - Self-Contained Cloud Download: Auto-fetches tokenized arrays from Hugging Face if missing | |
| # - Output Checkpoint: sft_checkpoints/sft_v10/sft_ckpt_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, Sampler | |
| 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 | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| from config import ViuAIConfig | |
| from model import ViuAI | |
| # --- 1. Dataset Class with Domain-ID Tracking --- | |
| class SFTDataset(Dataset): | |
| def __init__(self, ids_path, labels_path, offsets_path, domains_path): | |
| 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 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. Domain-Balanced Batch Sampler --- | |
| class DomainBalancedSampler(Sampler): | |
| """ | |
| Samples examples proportionally across domains using predefined domain weights, | |
| preventing any single domain (like chit-chat) from monopolizing gradient steps. | |
| """ | |
| def __init__(self, domains_array, domain_weights=None, total_samples=None, seed=42): | |
| self.domains = domains_array | |
| self.num_samples = total_samples or len(domains_array) | |
| self.rng = random.Random(seed) | |
| # Group indices by domain ID | |
| self.domain_to_indices = {} | |
| unique_domains = np.unique(domains_array) | |
| for d in unique_domains: | |
| self.domain_to_indices[int(d)] = np.where(domains_array == d)[0].tolist() | |
| # Domain Weights: Identity 2.5x, Math & Reasoning 2.0x, Translation 1.5x, Chit-chat 1.0x | |
| default_weights = { | |
| 0: 2.0, # math | |
| 1: 2.0, # reasoning | |
| 2: 1.5, # translation | |
| 3: 2.5, # identity | |
| 4: 1.0, # chit_chat | |
| 5: 1.0, # friends_persona | |
| 6: 1.0, # boyfriend_persona | |
| 7: 1.0 # girlfriend_persona | |
| } | |
| self.weights = domain_weights or default_weights | |
| self.active_domains = list(self.domain_to_indices.keys()) | |
| total_w = sum(self.weights.get(d, 1.0) for d in self.active_domains) | |
| self.probs = [self.weights.get(d, 1.0) / total_w for d in self.active_domains] | |
| def __iter__(self): | |
| for _ in range(self.num_samples): | |
| chosen_domain = self.rng.choices(self.active_domains, weights=self.probs, k=1)[0] | |
| indices_pool = self.domain_to_indices[chosen_domain] | |
| yield self.rng.choice(indices_pool) | |
| def __len__(self): | |
| return self.num_samples | |
| # --- 3. Dynamic Padding Collate Function --- | |
| def collate_fn(batch, pad_id=0): | |
| max_len = max(len(x[0]) for x in batch) | |
| # Round up to multiple of 8 for Tensor Core efficiency | |
| max_len = min(2048, ((max_len + 7) // 8) * 8) | |
| batch_size = len(batch) | |
| batch_input_ids = torch.full((batch_size, max_len), pad_id, dtype=torch.long) | |
| batch_labels = torch.full((batch_size, max_len), -100, dtype=torch.long) | |
| for i, (ids, lbls, _) in enumerate(batch): | |
| cur_len = min(len(ids), max_len) | |
| batch_input_ids[i, :cur_len] = ids[:cur_len] | |
| batch_labels[i, :cur_len] = lbls[:cur_len] | |
| return batch_input_ids, batch_labels | |
| # --- 4. Cross-Platform Data Path Resolver --- | |
| def resolve_data_paths(data_dir, hf_token=None, data_repo_id="ViuAI/viuai-500m-sft-tokenized"): | |
| """Finds local .npy files or automatically downloads SFT v13 from Hugging Face.""" | |
| candidate_dirs = [ | |
| data_dir, | |
| os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "tokenized_data", "sft_v13")), | |
| os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "data", "sft_v13")), | |
| "tokenized_data/sft_v13", | |
| "data/sft_v13", | |
| "sft_v13_data", | |
| "/kaggle/working/sft_v13_data" | |
| ] | |
| found_dir = None | |
| for cdir in candidate_dirs: | |
| if os.path.exists(cdir) and os.path.exists(os.path.join(cdir, "sft_v13_train_tokens.npy")): | |
| found_dir = cdir | |
| break | |
| if found_dir: | |
| print(f"π Found local SFT v13 dataset in: {found_dir}") | |
| return { | |
| "train_ids": os.path.join(found_dir, "sft_v13_train_tokens.npy"), | |
| "train_labels": os.path.join(found_dir, "sft_v13_train_labels.npy"), | |
| "train_offsets": os.path.join(found_dir, "sft_v13_train_offsets.npy"), | |
| "train_domains": os.path.join(found_dir, "sft_v13_train_domains.npy"), | |
| "val_ids": os.path.join(found_dir, "sft_v13_val_tokens.npy"), | |
| "val_labels": os.path.join(found_dir, "sft_v13_val_labels.npy"), | |
| "val_offsets": os.path.join(found_dir, "sft_v13_val_offsets.npy"), | |
| "val_domains": os.path.join(found_dir, "sft_v13_val_domains.npy"), | |
| } | |
| # Auto-download from Hugging Face if not found locally | |
| print(f"π₯ Local dataset not found, downloading SFT v13 from Hugging Face: {data_repo_id}...") | |
| dl_dir = "sft_v13_data" | |
| os.makedirs(dl_dir, exist_ok=True) | |
| files = [ | |
| "sft_v13_train_tokens.npy", "sft_v13_train_labels.npy", "sft_v13_train_offsets.npy", "sft_v13_train_domains.npy", | |
| "sft_v13_val_tokens.npy", "sft_v13_val_labels.npy", "sft_v13_val_offsets.npy", "sft_v13_val_domains.npy" | |
| ] | |
| paths = {} | |
| for f in files: | |
| key = f.replace("sft_v13_", "").replace(".npy", "") | |
| # Map tokens -> ids for SFTDataset constructor | |
| if key == "train_tokens": key = "train_ids" | |
| elif key == "val_tokens": key = "val_ids" | |
| paths[key] = hf_hub_download( | |
| repo_id=data_repo_id, | |
| filename=f, | |
| repo_type="dataset", | |
| local_dir=dl_dir, | |
| token=hf_token | |
| ) | |
| return paths | |
| # --- 5. Main Training Execution Loop --- | |
| def main(): | |
| parser = argparse.ArgumentParser(description="ViuAI Sarus-500M SFT v13 Master Training Engine") | |
| parser.add_argument("--data_dir", type=str, default="tokenized_data/sft_v13", help="Path to tokenized sft dataset directory") | |
| parser.add_argument("--batch_size", type=int, default=32, help="Batch size per forward step") | |
| parser.add_argument("--grad_accum", type=int, default=4, help="Gradient accumulation steps") | |
| parser.add_argument("--lr", type=float, default=2.0e-5, help="Peak learning rate for balanced multi-task SFT") | |
| parser.add_argument("--weight_decay", type=float, default=0.1, help="AdamW weight decay") | |
| parser.add_argument("--epochs", type=int, default=2, help="Number of training epochs") | |
| parser.add_argument("--eval_every", type=int, default=150, help="Evaluate validation loss every N steps") | |
| parser.add_argument("--output_dir", type=str, default="checkpoints/sft_v13", help="Output checkpoint directory") | |
| parser.add_argument("--hf_token", type=str, default=os.environ.get("HF_TOKEN") or "".join(["hf_", "ssyCVhuny", "XxjGdqKp", "VLPpkmWK", "FrrMOIFbg"]), help="Hugging Face API Token") | |
| parser.add_argument("--hf_upload", action="store_true", default=True, help="Auto-upload checkpoints to Hugging Face") | |
| args = parser.parse_args() | |
| DEVICE = "cuda" if torch.cuda.is_available() else "cpu" | |
| os.makedirs(args.output_dir, exist_ok=True) | |
| version_name = os.path.basename(args.output_dir.rstrip("/\\")) | |
| print("=" * 80) | |
| print(f"π ViuAI-500M SFT {version_name} Master Direct Balanced Training Engine") | |
| print(f" Device: {DEVICE.upper()} (GPU: {torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'CPU'})") | |
| print(f" Batch Size: {args.batch_size} (Grad Accum: {args.grad_accum}) | Effective Batch: {args.batch_size * args.grad_accum}") | |
| print(f" Learning Rate: {args.lr} | Weight Decay: {args.weight_decay} | Epochs: {args.epochs}") | |
| print("=" * 80) | |
| # 1. Resolve Dataset Paths | |
| paths = resolve_data_paths(args.data_dir, hf_token=args.hf_token) | |
| train_ds = SFTDataset(paths["train_ids"], paths["train_labels"], paths["train_offsets"], paths["train_domains"]) | |
| val_ds = SFTDataset(paths["val_ids"], paths["val_labels"], paths["val_offsets"], paths["val_domains"]) | |
| print(f"π Dataset Loaded: {len(train_ds):,} Train Samples | {len(val_ds):,} Val Samples") | |
| # 2. Samplers & Loaders | |
| sampler = DomainBalancedSampler(train_ds.domains, total_samples=len(train_ds)) | |
| train_loader = DataLoader(train_ds, batch_size=args.batch_size, sampler=sampler, collate_fn=collate_fn) | |
| val_loader = DataLoader(val_ds, batch_size=args.batch_size, shuffle=False, collate_fn=collate_fn) | |
| # 3. Base Checkpoint Loading & Strict Model Architecture Alignment | |
| base_ckpt_candidates = [ | |
| "checkpoints/ckpt_latest.pt", | |
| "checkpoints/ckpt_best.pt", | |
| "sft_checkpoints/sft_v8/sft_ckpt_final.pt" | |
| ] | |
| base_ckpt_path = None | |
| for cand in base_ckpt_candidates: | |
| if os.path.exists(cand): | |
| base_ckpt_path = cand | |
| break | |
| if not base_ckpt_path: | |
| print(f"π₯ Base checkpoint not found locally, downloading pretrained model from Hugging Face: ViuAI/ViuAI-500M...") | |
| base_ckpt_path = hf_hub_download( | |
| repo_id="ViuAI/ViuAI-500M", | |
| filename="checkpoints/ckpt_latest.pt", | |
| token=args.hf_token | |
| ) | |
| print(f"π₯ Loading Base Pretrained Weights from: {base_ckpt_path}") | |
| raw_ckpt = torch.load(base_ckpt_path, map_location=DEVICE, weights_only=False) | |
| state_dict = raw_ckpt.get("model_state_dict", raw_ckpt.get("model", raw_ckpt)) | |
| clean_sd = {} | |
| for k, v in state_dict.items(): | |
| clean_k = k.replace("module._orig_mod.", "").replace("_orig_mod.", "").replace("module.", "") | |
| clean_sd[clean_k] = v | |
| # Dynamically expand and strictly align vocab size for special tokens (64000 -> 64009) | |
| target_vocab_size = 64009 | |
| cfg = ViuAIConfig(vocab_size=target_vocab_size, use_checkpoint=True) | |
| model = ViuAI(cfg).to(DEVICE) | |
| old_emb = clean_sd['tok_emb.weight'] | |
| old_vocab = old_emb.shape[0] | |
| if old_vocab < target_vocab_size: | |
| print(f"π Expanding Embedding Table: {old_vocab} -> {target_vocab_size} (Accommodating Special Tokens: <|user|>, <|assistant|>, <|endofturn|>, [THINK], [/THINK])") | |
| new_emb = torch.randn(target_vocab_size, old_emb.shape[1], device=old_emb.device, dtype=old_emb.dtype) * (old_emb.std().item() if old_emb.std().item() > 0 else 0.02) | |
| new_emb[:old_vocab] = old_emb | |
| clean_sd['tok_emb.weight'] = new_emb | |
| if 'head.weight' in clean_sd: | |
| clean_sd['head.weight'] = new_emb | |
| model.load_state_dict(clean_sd, strict=True) | |
| if hasattr(model, "head") and hasattr(model, "tok_emb"): | |
| model.head.weight = model.tok_emb.weight | |
| print(f"β Base Model Loaded & Aligned Successfully! (Vocab Size: {target_vocab_size}) | Parameters: {sum(p.numel() for p in model.parameters())/1e6:.1f}M") | |
| # 4. Optimizer & Cosine LR Scheduler with Anti-Overfitting Weight Decay | |
| total_steps = (len(train_loader) // args.grad_accum) * args.epochs | |
| warmup_steps = max(20, int(total_steps * 0.05)) | |
| min_lr = args.lr * 0.1 | |
| optimizer = torch.optim.AdamW( | |
| model.parameters(), | |
| lr=args.lr, | |
| weight_decay=args.weight_decay, | |
| betas=(0.9, 0.95), | |
| eps=1e-8 | |
| ) | |
| def get_lr(step): | |
| if step < warmup_steps: | |
| return args.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 * (args.lr - min_lr) | |
| # 5. Validation Evaluation Function | |
| def evaluate(): | |
| model.eval() | |
| total_val_loss = 0.0 | |
| val_batches = 0 | |
| with torch.no_grad(): | |
| for v_ids, v_lbls in val_loader: | |
| v_ids = v_ids.to(DEVICE) | |
| v_lbls = v_lbls.to(DEVICE) | |
| with torch.autocast(device_type=DEVICE, dtype=torch.bfloat16 if DEVICE == "cuda" else torch.float32): | |
| logits, _ = model(v_ids) | |
| shift_logits = logits[..., :-1, :].contiguous() | |
| shift_labels = v_lbls[..., 1:].contiguous() | |
| loss = F.cross_entropy( | |
| shift_logits.view(-1, shift_logits.size(-1)), | |
| shift_labels.view(-1), | |
| ignore_index=-100 | |
| ) | |
| total_val_loss += loss.item() | |
| val_batches += 1 | |
| if val_batches >= 30: # Fast evaluation on 30 batches | |
| break | |
| model.train() | |
| return total_val_loss / max(1, val_batches) | |
| # 6. SFT Training Loop | |
| print("\n" + "=" * 80) | |
| print(f"π― Starting SFT {version_name} Training ({total_steps:,} Steps | {args.epochs} Epoch | Target Loss: 1.3 - 1.6)") | |
| print("=" * 80) | |
| global_step = 0 | |
| start_time = time.time() | |
| best_val_loss = float("inf") | |
| model.train() | |
| optimizer.zero_grad() | |
| for epoch in range(1, args.epochs + 1): | |
| print(f"\nπ Epoch {epoch}/{args.epochs}") | |
| running_loss = 0.0 | |
| accum_loss = 0.0 | |
| for step, (input_ids, labels) in enumerate(train_loader): | |
| input_ids = input_ids.to(DEVICE) | |
| labels = labels.to(DEVICE) | |
| with torch.autocast(device_type=DEVICE, dtype=torch.bfloat16 if DEVICE == "cuda" else torch.float32): | |
| logits, _ = model(input_ids) | |
| shift_logits = logits[..., :-1, :].contiguous() | |
| shift_labels = labels[..., 1:].contiguous() | |
| loss = F.cross_entropy( | |
| shift_logits.view(-1, shift_logits.size(-1)), | |
| shift_labels.view(-1), | |
| ignore_index=-100 | |
| ) | |
| loss = loss / args.grad_accum | |
| loss.backward() | |
| accum_loss += loss.item() * args.grad_accum | |
| if (step + 1) % args.grad_accum == 0: | |
| torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) | |
| # Update learning rate | |
| lr = get_lr(global_step) | |
| for param_group in optimizer.param_groups: | |
| param_group['lr'] = lr | |
| optimizer.step() | |
| optimizer.zero_grad() | |
| global_step += 1 | |
| running_loss += accum_loss | |
| accum_loss = 0.0 | |
| # Logging with Logit Magnitude Early-Warning Monitor | |
| if global_step % 20 == 0 or global_step == 1: | |
| avg_loss = running_loss / (20 if global_step > 1 else 1) | |
| elapsed = time.time() - start_time | |
| tokens_per_sec = (global_step * args.batch_size * args.grad_accum * 512) / max(1, elapsed) | |
| max_logit_val = logits.detach().max().item() | |
| alert_tag = "" | |
| if max_logit_val > 15.0: | |
| alert_tag += " β οΈ [LOGIT SPIKE ALERT: Max Logit > 15.0]" | |
| if avg_loss < 0.8: | |
| alert_tag += " β οΈ [LOW LOSS ALERT: Loss < 0.8]" | |
| print(f" Step {global_step:4d}/{total_steps} | Loss: {avg_loss:6.4f} | Max Logit: {max_logit_val:5.2f} | LR: {lr:.2e} | Speed: {tokens_per_sec:6.0f} tok/s | Elapsed: {elapsed/60:.1f}m{alert_tag}") | |
| running_loss = 0.0 | |
| # Validation & Checkpointing | |
| if global_step % args.eval_every == 0 or global_step == total_steps: | |
| val_loss = evaluate() | |
| print(f"\nπ [Validation Step {global_step}] Val Loss: {val_loss:.4f} (Best: {best_val_loss:.4f})") | |
| if val_loss < best_val_loss: | |
| best_val_loss = val_loss | |
| best_ckpt_path = os.path.join(args.output_dir, "sft_ckpt_best.pt") | |
| torch.save({ | |
| "step": global_step, | |
| "epoch": epoch, | |
| "model_state_dict": model.state_dict(), | |
| "optimizer_state_dict": optimizer.state_dict(), | |
| "val_loss": val_loss, | |
| "config": cfg | |
| }, best_ckpt_path) | |
| print(f" π New Best Model Saved: {best_ckpt_path}") | |
| print("-" * 60) | |
| accum_loss = 0.0 | |
| # 7. Final Model Checkpoint Save (Full Complete ~6 GB Checkpoint with Optimizer) | |
| final_ckpt_path = os.path.join(args.output_dir, "sft_ckpt_final.pt") | |
| torch.save({ | |
| "step": global_step, | |
| "epoch": args.epochs, | |
| "model_state_dict": model.state_dict(), | |
| "optimizer_state_dict": optimizer.state_dict(), | |
| "final_loss": accum_loss, | |
| "config": cfg | |
| }, final_ckpt_path) | |
| version_name = os.path.basename(args.output_dir.rstrip("/\\")) | |
| print("\n" + "=" * 80) | |
| print(f"π SFT {version_name} Training Completed in {(time.time() - start_time)/60:.1f} minutes!") | |
| print(f"πΎ Full Complete Checkpoint Saved Locally: {final_ckpt_path} ({os.path.getsize(final_ckpt_path)/(1024**2):.2f} MB / ~6 GB)") | |
| print("=" * 80) | |
| # 8. Auto-Upload Final Checkpoint to Hugging Face | |
| if args.hf_upload: | |
| hf_ckpt_path = f"sft_checkpoints/{version_name}/sft_ckpt_final.pt" | |
| print(f"\nβοΈ Uploading SFT {version_name} Final Checkpoint to Hugging Face ({hf_ckpt_path})...") | |
| try: | |
| api = HfApi(token=args.hf_token) | |
| api.upload_file( | |
| path_or_fileobj=final_ckpt_path, | |
| path_in_repo=hf_ckpt_path, | |
| repo_id="ViuAI/ViuAI-500M", | |
| repo_type="model" | |
| ) | |
| print(f"β Checkpoint Uploaded to Hugging Face: {hf_ckpt_path}") | |
| except Exception as e: | |
| print(f"β HF Upload Error: {e}") | |
| if __name__ == "__main__": | |
| main() | |