Upload code/train_sft.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834# ============================================================================# ViuAI 500M β Supervised Fine-Tuning (SFT) Script (v7 Cognitive & RAG)# ============================================================================# Universal script: works on H200(140GB), 5090(32GB), L4(24GB), T4x2(16GBx2)# Works on: Kaggle, Rental GPU, Any cloud provider## Run commands:# Kaggle T4x2: torchrun --nproc_per_node=2 train_sft.py# Single GPU: torchrun --nproc_per_node=1 train_sft.py# Multi-GPU: torchrun --nproc_per_node=<N> train_sft.py# ============================================================================import sysif 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")import osos.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")# Redirect HF cache to working directoryif os.path.exists("/kaggle/working"):os.environ.setdefault("HF_HOME", "/kaggle/working/hf_cache")else:os.environ.setdefault("HF_HOME", "./working/hf_cache")import jsonimport mathimport timeimport randomimport contextlibimport gcimport threadingfrom datetime import timedeltaimport numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as Fimport torch.distributed as distfrom torch.nn.parallel import DistributedDataParallel as DDPfrom huggingface_hub import HfApi, hf_hub_download, create_repofrom transformers import PreTrainedTokenizerFast# Global list to track all background upload threads_upload_threads = []# Special tokens defined for ViuAI v7SPECIAL_TOKENS = ["<|user|>", "<|assistant|>", "<|endofturn|>","[THINK]", "[/THINK]","<search>", "</search>", "<search_result>", "</search_result>"]SFT_VOCAB_SIZE = 64009# ============================================================================# 1. DDP Setup (works for multi-GPU & single GPU via torchrun)# ============================================================================def setup_ddp():if not torch.cuda.is_available():raise RuntimeError("SFT training requires at least one CUDA GPU.")# Standalone execution fallback (if not launched via torchrun)if "RANK" not in os.environ or "WORLD_SIZE" not in os.environ:os.environ["RANK"] = "0"os.environ["LOCAL_RANK"] = "0"os.environ["WORLD_SIZE"] = "1"os.environ["MASTER_ADDR"] = "127.0.0.1"os.environ["MASTER_PORT"] = str(random.randint(29100, 29900))if not dist.is_initialized():dist.init_process_group(backend="nccl", timeout=timedelta(minutes=30))rank = dist.get_rank()local_rank = int(os.environ.get("LOCAL_RANK", 0))world_size = dist.get_world_size()torch.cuda.set_device(local_rank)device = torch.device(f"cuda:{local_rank}")return rank, local_rank, world_size, device# ============================================================================# 2. HF Token & Configuration Setup# ============================================================================HF_TOKEN = os.environ.get("HF_TOKEN")if not HF_TOKEN:# Check fallback environment variables or prompt notice_alt_token = os.environ.get("HUGGING_FACE_HUB_TOKEN")if _alt_token:HF_TOKEN = _alt_tokenelse:print("β οΈ Warning: HF_TOKEN environment variable is not set. Private repo uploads will require authentication.", flush=True)MAIN_REPO = "ViuAI/ViuAI-500M"SFT_DATA_REPO = "ViuAI/viuai-500m-sft-tokenized"SFT_CHECKPOINT_DIR = os.environ.get("SFT_CHECKPOINT_DIR", "sft_checkpoints/sft_v8")api = HfApi(token=HF_TOKEN) if HF_TOKEN else HfApi()# ============================================================================# 3. Helper: Network Retry & DDP Download Logic# ============================================================================def with_retry(func, *args, max_retries=5, initial_backoff=5, **kwargs):backoff = initial_backofffor attempt in range(max_retries):try:return func(*args, **kwargs)except Exception as e:if attempt == max_retries - 1:raise etime.sleep(backoff)backoff *= 2def download_on_main(func, *args, fatal=True, is_main=True, device=None, **kwargs):err = Noneok = 1if is_main:try:with_retry(func, *args, **kwargs)except Exception as e:err = eok = 0if fatal:print(f"β Failed download on main rank: {e}", flush=True)if dist.is_initialized():ok_tensor = torch.tensor([ok], device=device or "cuda")dist.all_reduce(ok_tensor, op=dist.ReduceOp.MIN)if ok_tensor.item() == 0:if fatal:raise RuntimeError(f"Download failed on main rank: {err}")return Falsedist.barrier()return True# ============================================================================# 4. Learning Rate Schedule (Cosine with Linear Warmup)# ============================================================================def get_lr(step, warmup_steps, total_steps, max_lr, min_lr):if step < warmup_steps:return max_lr * (step + 1) / max(1, warmup_steps)if step >= total_steps:return min_lrdecay_ratio = (step - 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)# Memory allocator optimization & TF32 accelerationos.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")if torch.cuda.is_available():torch.set_float32_matmul_precision('high')# ============================================================================# 5. SFT Loss Computation (Chunked Memory-Efficient CrossEntropy)# ============================================================================def compute_sft_loss(model, input_ids, labels, pad_id=None):out = model(input_ids, pad_id=pad_id)logits = out[0] if isinstance(out, tuple) else outshift_logits = logits[:, :-1, :].reshape(-1, logits.size(-1))shift_labels = labels[:, 1:].reshape(-1)# Process cross-entropy in chunks to cap peak VRAM allocation to <1.5GBchunk_size = 16384total_tokens = shift_logits.size(0)if total_tokens > chunk_size:total_loss = torch.tensor(0.0, device=shift_logits.device, dtype=shift_logits.dtype)total_valid = 0for i in range(0, total_tokens, chunk_size):end = min(i + chunk_size, total_tokens)l_chunk = shift_logits[i:end]y_chunk = shift_labels[i:end]valid_mask = (y_chunk != -100)n_valid = int(valid_mask.sum().item())if n_valid > 0:loss_chunk = F.cross_entropy(l_chunk, y_chunk, ignore_index=-100, reduction='sum')total_loss = total_loss + loss_chunktotal_valid += n_validif total_valid > 0:return total_loss / total_validelse:return F.cross_entropy(shift_logits[:1], shift_labels[:1], ignore_index=-100)else:return F.cross_entropy(shift_logits, shift_labels, ignore_index=-100, reduction='mean')# ============================================================================# 6. Dataset Loader & Shuffled Epoch Sampler (.npy memmap)# ============================================================================class NpySFTDataset:def __init__(self, ids_path, labels_path, offsets_path, context_len):self.ids = np.load(ids_path, mmap_mode="r")self.labels = np.load(labels_path, mmap_mode="r")self.offsets = np.load(offsets_path)self.context_len = context_lenself.n_examples = len(self.offsets) - 1def __len__(self):return self.n_examplesdef get(self, idx):start = int(self.offsets[idx])end = int(self.offsets[idx + 1])ex_ids = np.zeros(self.context_len, dtype=np.int64)ex_labels = np.full(self.context_len, -100, dtype=np.int64)length = min(end - start, self.context_len)ex_ids[:length] = self.ids[start:start + length]ex_labels[:length] = self.labels[start:start + length]return torch.from_numpy(ex_ids), torch.from_numpy(ex_labels)class ShuffledEpochSampler:"""True epoch-based shuffling without replacement across DDP ranks.Ensures every training example is seen exactly once per epoch, precisely honoring EPOCHS.Seamlessly advances across epochs and supports resuming from any step without duplicating data."""def __init__(self, dataset_len, rank=0, world_size=1, seed=1337, initial_step=0, effective_batch=1):self.dataset_len = dataset_lenself.rank = rankself.world_size = world_sizeself.base_seed = seedself.effective_batch = effective_batchself.epoch = 0self.indices = []self.ptr = 0self._new_epoch()# Exact mathematical stride fast-forward if resuming from a specific stepif initial_step > 0:calls_per_rank = initial_step * (effective_batch // world_size)rank_samples_per_epoch = max(1, dataset_len // world_size)epochs_to_skip = calls_per_rank // rank_samples_per_epochfor _ in range(epochs_to_skip):self._new_epoch()calls_remaining = calls_per_rank % rank_samples_per_epochself.ptr = self.rank + (calls_remaining * self.world_size)def _new_epoch(self):rng = random.Random(self.base_seed + self.epoch * 1000)perm = list(range(self.dataset_len))rng.shuffle(perm)self.indices = permself.ptr = self.rankself.epoch += 1def next_index(self):if self.ptr >= len(self.indices):self._new_epoch()idx = self.indices[self.ptr]self.ptr += self.world_sizereturn idxdef get_sft_batch(dataset, batch_size, sampler_or_rng, device="cuda"):batch_ids, batch_labels = [], []attempts = 0max_attempts = batch_size * 25while len(batch_ids) < batch_size and attempts < max_attempts:attempts += 1if hasattr(sampler_or_rng, "next_index"):idx = sampler_or_rng.next_index()elif hasattr(sampler_or_rng, "randint"):idx = sampler_or_rng.randint(0, len(dataset) - 1)else:idx = random.randint(0, len(dataset) - 1)ids, labels = dataset.get(idx)if not (labels != -100).any():continuebatch_ids.append(ids)batch_labels.append(labels)if len(batch_ids) == 0:ids, labels = dataset.get(0)batch_ids = [ids] * batch_sizebatch_labels = [labels] * batch_sizereturn (torch.stack(batch_ids).to(device, non_blocking=True),torch.stack(batch_labels).to(device, non_blocking=True))# ============================================================================# 7. Checkpoint Remapping & Serialization# ============================================================================def remap_checkpoint_keys(ckpt_state_dict, model_state_dict):clean_ckpt = {}for k, v in ckpt_state_dict.items():k = k.replace("_orig_mod.", "").replace("module.", "")clean_ckpt[k] = vremapped = {}for model_key in model_state_dict.keys():clean_key = model_key.replace("_orig_mod.", "").replace("module.", "")if model_key in clean_ckpt:remapped[model_key] = clean_ckpt[model_key]elif clean_key in clean_ckpt:remapped[model_key] = clean_ckpt[clean_key]else:print(f"β οΈ Unmapped key: {model_key}", flush=True)return remappeddef save_sft_checkpoint(model, optimizer, step, val_loss, best_val_loss, fname, scaler=None, is_main=True, work=".", blocking=False):if not is_main:returnlocal_path = os.path.join(work, fname)raw_model = model.module if hasattr(model, "module") else modelcheckpoint = {"step": step,"model_state_dict": raw_model.state_dict(),"optimizer_state_dict": optimizer.state_dict(),"scaler_state_dict": scaler.state_dict() if scaler is not None else None,"val_loss": val_loss,"best_val_loss": best_val_loss,"timestamp": time.time(),}torch.save(checkpoint, local_path)print(f"πΎ Saved checkpoint to {local_path} (step {step}, val_loss: {val_loss:.4f})", flush=True)def _async_upload():if not HF_TOKEN:returntry:with_retry(api.upload_file,path_or_fileobj=local_path,path_in_repo=f"{SFT_CHECKPOINT_DIR}/{fname}",repo_id=MAIN_REPO,repo_type="model")print(f"βοΈ Uploaded {fname} to Hugging Face successfully.", flush=True)except Exception as e:print(f"β οΈ Failed to upload checkpoint {fname}: {e}", flush=True)if blocking:_async_upload()else:thread = threading.Thread(target=_async_upload, daemon=True)thread.start()_upload_threads.append(thread)def load_sft_checkpoint(model, optimizer, scaler=None, resume_sft=False, resume_checkpoint_file="sft_ckpt_latest.pt", is_main=True, work=".", device="cuda"):"""Deadlock-free checkpoint loader across all DDP ranks:1. All ranks participate collectively in download_on_main() (Rank 0 downloads, all ranks wait at barrier).2. Every rank loads weights locally from shared disk, remaps prefixes (_orig_mod/module), and resizes vocab."""if resume_sft:if is_main:print(f"π Resuming SFT training from {resume_checkpoint_file}...", flush=True)try:download_on_main(hf_hub_download, MAIN_REPO, f"{SFT_CHECKPOINT_DIR}/{resume_checkpoint_file}",local_dir=work, is_main=is_main, device=device, token=HF_TOKEN)ckpt_path = os.path.join(work, SFT_CHECKPOINT_DIR, resume_checkpoint_file)ckpt = torch.load(ckpt_path, map_location=device)raw_model = model.module if hasattr(model, "module") else model# Robust key remapping & strict=False for cross-GPU resume (e.g. torch.compile <-> standard)remapped_sd = remap_checkpoint_keys(ckpt["model_state_dict"], raw_model.state_dict())# Resize embedding and head if neededmodel_sd = raw_model.state_dict()for k in ["tok_emb.weight", "head.weight"]:if k in remapped_sd and k in model_sd and remapped_sd[k].shape != model_sd[k].shape:old_w = remapped_sd[k]new_w = model_sd[k].clone()min_v = min(old_w.shape[0], new_w.shape[0])new_w[:min_v] = old_w[:min_v]remapped_sd[k] = new_wif is_main:print(f" Resized parameter '{k}' from {old_w.shape} to {new_w.shape}", flush=True)raw_model.load_state_dict(remapped_sd, strict=False)if "optimizer_state_dict" in ckpt:try:optimizer.load_state_dict(ckpt["optimizer_state_dict"])except Exception as e_opt:if is_main:print(f"β οΈ Optimizer state load warning (optimizer re-initialized): {e_opt}", flush=True)if scaler is not None and "scaler_state_dict" in ckpt and ckpt["scaler_state_dict"] is not None:try:scaler.load_state_dict(ckpt["scaler_state_dict"])except Exception as e_sc:if is_main:print(f"β οΈ Scaler state load notice: {e_sc}", flush=True)step = ckpt.get("step", 0)val_loss = ckpt.get("val_loss", None)best_val_loss = ckpt.get("best_val_loss", None)if is_main:print(f"β SFT checkpoint loaded! Resuming from step {step} (val_loss: {val_loss})", flush=True)return step, val_loss, best_val_lossexcept Exception as e:if is_main:print(f"β οΈ Failed to load SFT resume checkpoint: {e}", flush=True)print(" Falling back to loading base pre-trained weights...", flush=True)if is_main:print("π₯ Loading base pre-trained checkpoint (ckpt_latest.pt)...", flush=True)try:download_on_main(hf_hub_download, MAIN_REPO, "checkpoints/ckpt_latest.pt",local_dir=work, is_main=is_main, device=device, token=HF_TOKEN)ckpt_path = os.path.join(work, "checkpoints", "ckpt_latest.pt")ckpt = torch.load(ckpt_path, map_location=device)if "model_state_dict" in ckpt:state_dict = ckpt["model_state_dict"]elif "model" in ckpt:state_dict = ckpt["model"]else:state_dict = ckptraw_model = model.module if hasattr(model, "module") else modelremapped_sd = remap_checkpoint_keys(state_dict, raw_model.state_dict())# Resize embedding and head if vocab grew (e.g. 64000 -> 64009)model_sd = raw_model.state_dict()for k in ["tok_emb.weight", "head.weight", "_orig_mod.tok_emb.weight", "_orig_mod.head.weight"]:if k in remapped_sd and k in model_sd and remapped_sd[k].shape != model_sd[k].shape:old_w = remapped_sd[k]new_w = model_sd[k].clone()min_v = min(old_w.shape[0], new_w.shape[0])new_w[:min_v] = old_w[:min_v]remapped_sd[k] = new_wif is_main:print(f" Resized parameter '{k}' from {old_w.shape} to {new_w.shape}", flush=True)raw_model.load_state_dict(remapped_sd, strict=False)if is_main:print(f"β Base pre-trained weights ({len(remapped_sd)} tensors) successfully loaded into SFT model!", flush=True)del ckptgc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()return 0, -1, Noneexcept Exception as e:if is_main:print(f"β οΈ Could not load base weights: {e}", flush=True)print(" Starting SFT with randomly initialized weights.", flush=True)return 0, -1, None# ============================================================================# 8. Main Execution Function# ============================================================================def main():rank, local_rank, world_size, DEVICE = setup_ddp()IS_MAIN = (rank == 0)def log(msg):if IS_MAIN:print(msg, flush=True)# Initialize HF repo on Rank 0 if token is presentif IS_MAIN and HF_TOKEN:try:create_repo(repo_id=MAIN_REPO, repo_type="model", exist_ok=True, token=HF_TOKEN)except Exception as e:print(f"β οΈ Warning during repo creation: {e}", flush=True)dist.barrier()_resume_env = os.environ.get("RESUME_SFT")RESUME_SFT = _resume_env.lower() in ("1", "true", "yes") if _resume_env is not None else FalseRESUME_CHECKPOINT_FILE = os.environ.get("RESUME_CHECKPOINT_FILE", "sft_ckpt_latest.pt")global SFT_CHECKPOINT_DIRSFT_CHECKPOINT_DIR = os.environ.get("SFT_CHECKPOINT_DIR", "sft_checkpoints/sft_v8")WORK = "/kaggle/working" if os.path.exists("/kaggle/working") else "."log("π₯ Downloading tokenizer & model architecture code...")download_on_main(hf_hub_download, MAIN_REPO, "tokenizer/tokenizer.json", local_dir=WORK, is_main=IS_MAIN, device=DEVICE, token=HF_TOKEN)download_on_main(hf_hub_download, MAIN_REPO, "code/config.py", local_dir=WORK, is_main=IS_MAIN, device=DEVICE, token=HF_TOKEN)download_on_main(hf_hub_download, MAIN_REPO, "code/model.py", local_dir=WORK, is_main=IS_MAIN, device=DEVICE, token=HF_TOKEN)# Add WORK and code dirs to sys.pathif WORK not in sys.path:sys.path.insert(0, WORK)from config import ViuAIConfigfrom model import ViuAI# GPU Auto-Detection & Hyperparametersmem_gb = torch.cuda.get_device_properties(local_rank).total_memory / 1e9gpu_name = torch.cuda.get_device_name(local_rank)compute_cap = torch.cuda.get_device_capability(local_rank)supports_bf16 = compute_cap[0] >= 8if mem_gb >= 130: # H200 (141GB) / H100 (140GB)MICRO_BATCH = 32GRAD_ACCUM = 4CONTEXT_LEN = 2048AMP_DTYPE = torch.bfloat16USE_COMPILE = TrueEMPTY_CACHE_EVERY = 2000elif mem_gb >= 70: # A100 (80GB)MICRO_BATCH = 32GRAD_ACCUM = 2CONTEXT_LEN = 2048AMP_DTYPE = torch.bfloat16USE_COMPILE = TrueEMPTY_CACHE_EVERY = 1000elif mem_gb >= 30: # RTX 5090 (32GB) / RTX 4090 (24GB) / L4 (24GB)MICRO_BATCH = 16GRAD_ACCUM = 4CONTEXT_LEN = 2048AMP_DTYPE = torch.bfloat16 if supports_bf16 else torch.float16USE_COMPILE = TrueEMPTY_CACHE_EVERY = 500elif mem_gb >= 20: # RTX 3090 (24GB) / RTX 4090 (24GB) / L4 (24GB) / A10G (24GB)MICRO_BATCH = 8GRAD_ACCUM = 8CONTEXT_LEN = 2048AMP_DTYPE = torch.bfloat16 if supports_bf16 else torch.float16USE_COMPILE = TrueEMPTY_CACHE_EVERY = 200else: # Kaggle T4x2 (16GB each) / T4 singleMICRO_BATCH = 4GRAD_ACCUM = 16CONTEXT_LEN = 2048AMP_DTYPE = torch.float16USE_COMPILE = FalseEMPTY_CACHE_EVERY = 50# Allow custom environment overridesif "MICRO_BATCH" in os.environ:MICRO_BATCH = int(os.environ["MICRO_BATCH"])if "GRAD_ACCUM" in os.environ:GRAD_ACCUM = int(os.environ["GRAD_ACCUM"])MAX_LR = 2e-5MIN_LR = 2e-6WEIGHT_DECAY = 0.01GRAD_CLIP = 1.0EPOCHS = 3effective_batch = MICRO_BATCH * GRAD_ACCUM * world_sizetokens_per_step = effective_batch * CONTEXT_LENif IS_MAIN:log("=" * 65)log(f"π ViuAI-500M SFT v7 Training Initialized")log(f" GPU: {gpu_name} ({mem_gb:.1f} GB) x {world_size}")log(f" Micro batch: {MICRO_BATCH} | Grad accum: {GRAD_ACCUM} | Effective batch: {effective_batch}")log(f" Context length: {CONTEXT_LEN} | Tokens/step: {tokens_per_step:,}")log(f" Precision: {AMP_DTYPE} | Torch compile: {USE_COMPILE}")log(f" Max LR: {MAX_LR:.2e} | Min LR: {MIN_LR:.2e}")log(f" Vocab size: {SFT_VOCAB_SIZE} | Checkpoint dir: {SFT_CHECKPOINT_DIR}")log(f" Resume mode: {RESUME_SFT}")log("=" * 65)# Build Model & Optimizercfg = ViuAIConfig(vocab_size=SFT_VOCAB_SIZE,context_length=CONTEXT_LEN,use_checkpoint=True,z_loss_weight=0.0,attn_dropout=0.0,resid_dropout=0.0,)raw_model = ViuAI(cfg).to(DEVICE)if IS_MAIN:log(f"π§ Model params: {raw_model.num_params()/1e6:.1f}M | vocab_size={SFT_VOCAB_SIZE}")if USE_COMPILE:log("β‘ Compiling model with torch.compile...")raw_model = torch.compile(raw_model)model = DDP(raw_model, device_ids=[local_rank])# Bulletproof parameter grouping: handles weight tying without duplicate param errordecay_params = []no_decay_params = []seen_param_ids = set()for name, param in model.named_parameters():if not param.requires_grad:continueif id(param) in seen_param_ids:continueseen_param_ids.add(id(param))if any(k in name for k in ["norm", "tok_emb", "head"]):no_decay_params.append(param)else:decay_params.append(param)optimizer = torch.optim.AdamW([{"params": decay_params, "weight_decay": WEIGHT_DECAY},{"params": no_decay_params, "weight_decay": 0.0},],lr=MAX_LR,betas=(0.9, 0.95))scaler = torch.amp.GradScaler('cuda', enabled=(AMP_DTYPE == torch.float16))# 1. Collective Checkpoint Loading on all Ranksstart_step, prev_val_loss, best_val_loss_loaded = load_sft_checkpoint(model, optimizer, scaler=scaler, resume_sft=RESUME_SFT, resume_checkpoint_file=RESUME_CHECKPOINT_FILE,is_main=IS_MAIN, work=WORK, device=DEVICE)# 2. Defensive Model & Buffer Broadcast to ensure 100% parameter equalityfor param in raw_model.parameters():dist.broadcast(param.data, src=0)for buf in raw_model.buffers():dist.broadcast(buf.data, src=0)# Broadcast training scalar states across all ranksstate_t = torch.tensor([start_step,prev_val_loss if isinstance(prev_val_loss, (int, float)) else -1.0,best_val_loss_loaded if isinstance(best_val_loss_loaded, (int, float)) else -1.0], dtype=torch.float32, device=DEVICE)dist.broadcast(state_t, src=0)start_step = int(state_t[0].item())prev_val_loss = state_t[1].item() if state_t[1].item() != -1.0 else Nonebest_val_loss = state_t[2].item() if state_t[2].item() != -1.0 else Noneif best_val_loss is None and isinstance(prev_val_loss, (int, float)) and prev_val_loss >= 0:best_val_loss = prev_val_loss# Download & Load SFT Datalog("π₯ Downloading SFT data (.npy files)...")_DATA_VER = os.environ.get("SFT_DATA_VERSION", "v8")_PFX = f"sft_{_DATA_VER}_" if _DATA_VER != "v1_legacy" else "sft_"if _DATA_VER == "v1":_PFX = "sft_"SFT_DATA_FILES = [f"{_PFX}train_ids.npy", f"{_PFX}train_labels.npy", f"{_PFX}train_offsets.npy",f"{_PFX}val_ids.npy", f"{_PFX}val_labels.npy", f"{_PFX}val_offsets.npy",]log(f"π SFT data version: {_DATA_VER} | prefix: '{_PFX}'")for fname in SFT_DATA_FILES:download_on_main(hf_hub_download, SFT_DATA_REPO, fname, repo_type="dataset", local_dir=WORK, is_main=IS_MAIN, device=DEVICE, token=HF_TOKEN)log("β SFT data ready.")train_ds = NpySFTDataset(f"{WORK}/{_PFX}train_ids.npy", f"{WORK}/{_PFX}train_labels.npy",f"{WORK}/{_PFX}train_offsets.npy", CONTEXT_LEN)val_ds = NpySFTDataset(f"{WORK}/{_PFX}val_ids.npy", f"{WORK}/{_PFX}val_labels.npy",f"{WORK}/{_PFX}val_offsets.npy", CONTEXT_LEN)if IS_MAIN:log(f"π Train examples: {len(train_ds)}, Val examples: {len(val_ds)}")# Validate PAD_ID & Special Tokens against downloaded tokenizerPAD_ID = 0tok_json_path = os.path.join(WORK, "tokenizer", "tokenizer.json")if not os.path.exists(tok_json_path):tok_json_path = os.path.join(WORK, "tokenizer.json")if os.path.exists(tok_json_path):try:_loaded_tok = PreTrainedTokenizerFast(tokenizer_file=tok_json_path, pad_token="<pad>", bos_token="<bos>", eos_token="<eos>", unk_token="<unk>")_loaded_tok.add_tokens(SPECIAL_TOKENS, special_tokens=True)assert len(_loaded_tok) == SFT_VOCAB_SIZE, f"Tokenizer vocab size mismatch: {len(_loaded_tok)} != {SFT_VOCAB_SIZE}"assert _loaded_tok.pad_token_id == 0, f"Expected pad_token_id=0, got {_loaded_tok.pad_token_id}"PAD_ID = _loaded_tok.pad_token_idif IS_MAIN:log(f"β Verified tokenizer vocab size={len(_loaded_tok)} and PAD_ID={PAD_ID}")except Exception as e:if IS_MAIN:log(f"βΉοΈ Tokenizer check notice: {e}. Using PAD_ID={PAD_ID}")if IS_MAIN:_s_ids, _s_labels = train_ds.get(0)_has_active = (_s_labels != -100).any()assert _has_active, "SFT FATAL: All tokens are masked (-100)! Check data pipeline."log(f"β Data sanity check passed. Using PAD_ID={PAD_ID}")# Training Schedule Math & True Shuffled Epoch Samplertrain_sampler = ShuffledEpochSampler(len(train_ds), rank=rank, world_size=world_size,seed=1337, initial_step=start_step, effective_batch=effective_batch)val_rng = random.Random(999 + rank)# AUTO MAX STEPS: Exactly 3 full epochs automatically calculated from dataset size & effective batchTOTAL_STEPS = max(1, math.ceil(len(train_ds) / effective_batch) * EPOCHS)_max_steps_env = os.environ.get("MAX_TRAIN_STEPS")if _max_steps_env:MAX_TRAIN_STEPS = int(_max_steps_env)end_step = min(TOTAL_STEPS, start_step + MAX_TRAIN_STEPS)else:MAX_TRAIN_STEPS = TOTAL_STEPSend_step = TOTAL_STEPSWARMUP_STEPS = min(100, max(10, int(TOTAL_STEPS * 0.03)))log(f"π [AUTO-MAX] SFT Total Steps for {EPOCHS} epochs: {TOTAL_STEPS} | Effective Batch: {effective_batch}")log(f" Warmup: {WARMUP_STEPS} steps | Training Schedule: step {start_step} β {end_step} (Single save at step {end_step})")def evaluate(val_batches=40):model.eval()total_val_loss = 0.0with torch.no_grad():for _ in range(val_batches):x, y = get_sft_batch(val_ds, MICRO_BATCH, val_rng, device=DEVICE)with torch.autocast(device_type="cuda", dtype=AMP_DTYPE):loss = compute_sft_loss(model, x, y, pad_id=PAD_ID)total_val_loss += loss.item()del x, y, lossloss_tensor = torch.tensor([total_val_loss / val_batches], device=DEVICE)dist.all_reduce(loss_tensor, op=dist.ReduceOp.SUM)avg_loss = loss_tensor.item() / world_sizemodel.train()return avg_loss# SFT Training Looplog("\n" + "=" * 65)log(f"π₯ SFT v7 TRAINING RUNNING: Step {start_step} β {end_step}")log("=" * 65)model.train()ema_tok_s = NoneVAL_EVERY = 200SAVE_EVERY = 500global_t0 = time.time()t0 = time.time()for step in range(start_step, end_step):lr = get_lr(step, WARMUP_STEPS, TOTAL_STEPS, MAX_LR, MIN_LR)for g in optimizer.param_groups:g["lr"] = lroptimizer.zero_grad(set_to_none=True)accum_loss = 0.0for micro_i in range(GRAD_ACCUM):x, y = get_sft_batch(train_ds, MICRO_BATCH, train_sampler, device=DEVICE)sync_ctx = model.no_sync() if micro_i < GRAD_ACCUM - 1 else contextlib.nullcontext()with sync_ctx:with torch.autocast(device_type="cuda", dtype=AMP_DTYPE):loss = compute_sft_loss(model, x, y, pad_id=PAD_ID)loss = loss / GRAD_ACCUMscaler.scale(loss).backward()accum_loss += loss.item()del x, y, loss# Synchronized NaN/Inf Loss Checkis_nan = torch.tensor([0 if math.isfinite(accum_loss) else 1], device=DEVICE)dist.all_reduce(is_nan, op=dist.ReduceOp.MAX)if is_nan.item() > 0:if IS_MAIN:log(f"β οΈ NaN/Inf loss at step {step}! Skipping optimizer step.")optimizer.zero_grad(set_to_none=True)scaler.update()continuescaler.unscale_(optimizer)grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), GRAD_CLIP)# Synchronized Finite Grad Norm Checkis_finite_grad = torch.tensor([1 if torch.isfinite(grad_norm) else 0], device=DEVICE)dist.all_reduce(is_finite_grad, op=dist.ReduceOp.MIN)if is_finite_grad.item() == 0 or not torch.isfinite(grad_norm):if IS_MAIN:log(f"β οΈ Non-finite grad norm at step {step}. Skipping optimizer step.")optimizer.zero_grad(set_to_none=True)scaler.update()continuescaler.step(optimizer)scaler.update()# Loggingif IS_MAIN and step % 10 == 0:dt = time.time() - t0tok_s = (MICRO_BATCH * GRAD_ACCUM * CONTEXT_LEN * world_size * 10) / dt if dt > 0 else 0ema_tok_s = tok_s if ema_tok_s is None else 0.7 * ema_tok_s + 0.3 * tok_st0 = time.time()mem_alloc = torch.cuda.memory_allocated(DEVICE) / 1e9mem_reserved = torch.cuda.memory_reserved(DEVICE) / 1e9steps_done = step - start_stepif steps_done > 0:elapsed = time.time() - global_t0eta_s = elapsed / steps_done * (end_step - step)eta_str = f"{eta_s/60:.0f}min" if eta_s < 3600 else f"{eta_s/3600:.1f}hr"else:eta_str = "..."log(f"SFT step {step:5d}/{end_step} | loss {accum_loss:.4f} | lr {lr:.2e} | "f"{ema_tok_s:.0f} tok/s | ETA {eta_str} | "f"VRAM {mem_alloc:.1f}/{mem_reserved:.1f}GB")# Periodic Evaluation (Calculated only for metrics - No mid-training saving)if step > 0 and step % VAL_EVERY == 0:val_loss = evaluate()is_best = (best_val_loss is None) or (val_loss < best_val_loss)if is_best:best_val_loss = val_lossstar = " βοΈ BEST!"else:star = ""log(f"\nπ [Validation @ step {step}] val_loss: {val_loss:.4f}{star}\n")# Periodic Memory Defragmentationif step > 0 and step % EMPTY_CACHE_EVERY == 0:torch.cuda.empty_cache()# Final Checkpoints & Training Wrap-uplog("\n" + "=" * 65)log("π SFT v8 TRAINING COMPLETE!")log("=" * 65)final_val_loss = evaluate()best_str = f"{best_val_loss:.4f}" if best_val_loss is not None else f"{final_val_loss:.4f}"log(f"π Final validation loss: {final_val_loss:.4f} (Best achieved: {best_str})")log("πΎ Saving final SFT model checkpoint at max step...")save_sft_checkpoint(model, optimizer, end_step, final_val_loss, best_val_loss, "sft_ckpt_final.pt", scaler=scaler, is_main=IS_MAIN, work=WORK, blocking=True)save_sft_checkpoint(model, optimizer, end_step, final_val_loss, best_val_loss, "sft_ckpt_latest.pt", scaler=scaler, is_main=IS_MAIN, work=WORK, blocking=True)log("β³ Waiting for all background upload threads to complete...")for t in _upload_threads:t.join(timeout=300)log("β All checkpoints uploaded to Hugging Face successfully!")dist.destroy_process_group()if __name__ == "__main__":main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337# ==============================================================================# ViuAI-500M β Master SFT Domain-Balanced Cognitive Reasoning Training Engine# ==============================================================================# - Domain-Balanced Batch Sampling: Stratified gradient updates across all 8 domains# - Full Production Training Loop: Mixed Precision (bf16/fp16), Grad Accum, Cosine LR# - Periodic Validation Loss Evaluation & Best/Final Checkpointing + HF Auto-Sync# - Works seamlessly on Windows, Linux (Kaggle/Colab), and Rental Cloud GPUs (H100/H200)# ==============================================================================import osimport sysimport mathimport timeimport jsonimport globimport randomimport argparsefrom datetime import datetime, timezoneimport numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch.utils.data import Dataset, DataLoader, Samplerfrom huggingface_hub import HfApi, hf_hub_downloadif 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 reproducibilityrandom.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 pathsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from config import ViuAIConfigfrom 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 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. 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_arrayself.num_samples = total_samples or len(domains_array)self.rng = random.Random(seed)# Group indices by domain IDself.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: Math & Reasoning get 2.0x, Identity gets 2.5x, Translation gets 1.5xdefault_weights = {0: 2.0, # math1: 2.0, # reasoning2: 1.5, # translation3: 2.5, # identity4: 1.0, # chit_chat5: 1.0, # friends_persona6: 1.0, # boyfriend_persona7: 1.0 # girlfriend_persona}self.weights = domain_weights or default_weightsself.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 int(self.rng.choice(indices_pool))def __len__(self):return self.num_samples# --- 3. Dynamic Collate Function ---def collate_fn(batch):input_ids_list, labels_list, _ = zip(*batch)max_len = max(len(x) for x in input_ids_list)# Pad to multiple of 8 for tensor core performancepad_len = min(((max_len + 7) // 8) * 8, 2048)batch_size = len(batch)batch_input_ids = torch.zeros((batch_size, pad_len), dtype=torch.long)batch_labels = torch.full((batch_size, pad_len), -100, dtype=torch.long)for i, (ids, lbls, _) in enumerate(batch):cur_len = min(len(ids), pad_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 from Hugging Face."""candidate_dirs = [data_dir,os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "data", "sft_v9")),"data/sft_v9","sft_v9_data","/kaggle/working/sft_v9_data"]found_dir = Nonefor cdir in candidate_dirs:if os.path.exists(cdir) and os.path.exists(os.path.join(cdir, "sft_v9_train_ids.npy")):found_dir = cdirbreakif found_dir:print(f"π Found local SFT dataset in: {found_dir}")return {"train_ids": os.path.join(found_dir, "sft_v9_train_ids.npy"),"train_labels": os.path.join(found_dir, "sft_v9_train_labels.npy"),"train_offsets": os.path.join(found_dir, "sft_v9_train_offsets.npy"),"train_domains": os.path.join(found_dir, "sft_v9_train_domains.npy"),"val_ids": os.path.join(found_dir, "sft_v9_val_ids.npy"),"val_labels": os.path.join(found_dir, "sft_v9_val_labels.npy"),"val_offsets": os.path.join(found_dir, "sft_v9_val_offsets.npy"),"val_domains": os.path.join(found_dir, "sft_v9_val_domains.npy"),}# Auto-download from Hugging Face if not found locallyprint(f"π₯ Local dataset not found, downloading from Hugging Face: {data_repo_id}...")dl_dir = "sft_v9_data"os.makedirs(dl_dir, exist_ok=True)files = ["sft_v9_train_ids.npy", "sft_v9_train_labels.npy", "sft_v9_train_offsets.npy", "sft_v9_train_domains.npy","sft_v9_val_ids.npy", "sft_v9_val_labels.npy", "sft_v9_val_offsets.npy", "sft_v9_val_domains.npy"]paths = {}for f in files:paths[f.replace("sft_v9_", "").replace(".npy", "")] = hf_hub_download(repo_id=data_repo_id,filename=f"sft_v9/{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 Training Engine")parser.add_argument("--data_dir", type=str, default="data/sft_v9", 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=3.0e-5, help="Peak learning rate")parser.add_argument("--epochs", type=int, default=2, help="Number of training epochs")parser.add_argument("--eval_every", type=int, default=100, help="Evaluate validation loss every N steps")parser.add_argument("--output_dir", type=str, default="checkpoints/sft_v9", 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)print("=" * 80)print(f"π ViuAI-500M SFT Domain-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} | Epochs: {args.epochs}")print("=" * 80)# 1. Resolve Dataset Pathspaths = 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 & Loaderssampler = 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. Model Architecture & Weightscfg = ViuAIConfig(vocab_size=64009, use_checkpoint=False)model = ViuAI(cfg).to(DEVICE)# Look for base pretrained weightsbase_candidates = ["checkpoints/ckpt_latest.pt","checkpoints/sft_v8/sft_ckpt_final.pt",os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "checkpoints", "ckpt_latest.pt"))]base_ckpt_path = Nonefor cand in base_candidates:if os.path.exists(cand):base_ckpt_path = candbreakif not base_ckpt_path:print("π₯ Downloading base checkpoint from Hugging Face...")try:base_ckpt_path = hf_hub_download(repo_id="ViuAI/ViuAI-500M", filename="checkpoints/ckpt_latest.pt", token=args.hf_token)except Exception:base_ckpt_path = hf_hub_download(repo_id="ViuAI/ViuAI-500M", filename="sft_checkpoints/sft_v8/sft_ckpt_final.pt", token=args.hf_token)print(f"π₯ Loading base model weights from: {base_ckpt_path}")base_sd = torch.load(base_ckpt_path, map_location=DEVICE, weights_only=False)clean_sd = {k.replace("module._orig_mod.", "").replace("_orig_mod.", "").replace("module.", ""): v for k, v in base_sd.get("model_state_dict", base_sd).items()}model.load_state_dict(clean_sd, strict=False)if hasattr(model, "head") and hasattr(model, "tok_emb"):model.head.weight = model.tok_emb.weight# 4. Optimizer, Scheduler & Loss Criteriontotal_steps = (len(train_loader) // args.grad_accum) * args.epochsoptimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=0.01, betas=(0.9, 0.95))scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=total_steps, eta_min=args.lr * 0.1)criterion = nn.CrossEntropyLoss(ignore_index=-100)print(f"β Training Configuration Ready: Total Optimizer Steps = {total_steps:,}")print("=" * 80)# 5. FULL PRODUCTION TRAINING LOOPbest_val_loss = float("inf")global_step = 0start_time = time.time()api = HfApi(token=args.hf_token)for epoch in range(args.epochs):epoch_loss = 0.0optimizer.zero_grad()model.train()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 torch.cuda.is_bf16_supported() else torch.float16):logits = model(input_ids)[0]loss = criterion(logits.view(-1, logits.size(-1)), labels.view(-1))loss = loss / args.grad_accumloss.backward()epoch_loss += loss.item() * args.grad_accumif (step + 1) % args.grad_accum == 0:torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)optimizer.step()scheduler.step()optimizer.zero_grad()global_step += 1# Logging every 20 stepsif global_step % 20 == 0:current_lr = scheduler.get_last_lr()[0]elapsed = time.time() - start_timetok_sec = (args.batch_size * args.grad_accum * 1024) / (elapsed / max(global_step, 1))print(f"Epoch {epoch+1}/{args.epochs} | Step {global_step}/{total_steps} | Loss: {loss.item()*args.grad_accum:.4f} | LR: {current_lr:.2e} | Elapsed: {elapsed/60:.1f}m")# Periodic Validationif global_step % args.eval_every == 0 or global_step == total_steps:model.eval()val_loss = 0.0val_steps = 0with 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 torch.cuda.is_bf16_supported() else torch.float16):v_logits = model(v_ids)[0]v_l = criterion(v_logits.view(-1, v_logits.size(-1)), v_lbls.view(-1))val_loss += v_l.item()val_steps += 1if val_steps >= 50:breakval_loss = val_loss / val_stepsprint(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_lossbest_ckpt_path = os.path.join(args.output_dir, "sft_ckpt_best.pt")torch.save({"model_state_dict": model.state_dict(), "step": global_step, "val_loss": val_loss}, best_ckpt_path)print(f"β Saved New Best Checkpoint (Val Loss: {val_loss:.4f})\n")model.train()# 6. Save Final Checkpoint & Uploadfinal_ckpt_path = os.path.join(args.output_dir, "sft_ckpt_final.pt")torch.save({"model_state_dict": model.state_dict(), "step": global_step, "val_loss": best_val_loss}, final_ckpt_path)print(f"\nπΎ Final SFT Checkpoint Saved: {final_ckpt_path}")if args.hf_upload:print("π Uploading SFT Checkpoint to Hugging Face (ViuAI/ViuAI-500M)...")api.upload_file(path_or_fileobj=final_ckpt_path,path_in_repo="sft_checkpoints/sft_v9/sft_ckpt_final.pt",repo_id="ViuAI/ViuAI-500M",repo_type="model")print("π Checkpoint Synced to Hugging Face Successfully!")print("\n" + "=" * 80)print(f"π SFT TRAINING COMPLETED SUCCESSFULLY!")print(f" Best Val Loss: {best_val_loss:.4f} | Total Steps: {global_step}")print("=" * 80)if __name__ == "__main__":main()
code/train_sft.py+291-788