Download code/train_sft.py from ViuAI/ViuAI-500M: direct link, hf CLI and curl.
- Browser
- Download file 29.1 kB
-
https://huggingface.co/ViuAI/ViuAI-500M/resolve/b809ccc19bb394fa2f9ff2ce472c06d6a38d7af6/code/train_sft.py
- Command line
-
hf download hf://ViuAI/ViuAI-500M@b809ccc19bb394fa2f9ff2ce472c06d6a38d7af6/code/train_sft.py
-
curl -L -o train_sft.py https://huggingface.co/ViuAI/ViuAI-500M/resolve/b809ccc19bb394fa2f9ff2ce472c06d6a38d7af6/code/train_sft.py
29.1 kB
| # ============================================================================ | |
| # 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 sys | |
| 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") | |
| import os | |
| os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") | |
| # Redirect HF cache to working directory | |
| if os.path.exists("/kaggle/working"): | |
| os.environ.setdefault("HF_HOME", "/kaggle/working/hf_cache") | |
| else: | |
| os.environ.setdefault("HF_HOME", "./working/hf_cache") | |
| import json | |
| import math | |
| import time | |
| import random | |
| import sys | |
| import contextlib | |
| import gc | |
| import threading | |
| from datetime import timedelta | |
| import numpy as np | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| import torch.distributed as dist | |
| from torch.nn.parallel import DistributedDataParallel as DDP | |
| from huggingface_hub import HfApi, hf_hub_download, create_repo | |
| # Global list to track all background upload threads | |
| _upload_threads = [] | |
| # ============================================================================ | |
| # 1. DDP Setup (works for single GPU too via torchrun --nproc_per_node=1) | |
| # ============================================================================ | |
| def setup_ddp(): | |
| if not torch.cuda.is_available(): | |
| raise RuntimeError("SFT training requires at least one CUDA GPU.") | |
| 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 | |
| rank, local_rank, world_size, DEVICE = setup_ddp() | |
| IS_MAIN = (rank == 0) | |
| def log(msg): | |
| if IS_MAIN: | |
| print(msg, flush=True) | |
| # ============================================================================ | |
| # 2. HF Token & Configuration Setup | |
| # ============================================================================ | |
| HF_TOKEN = os.environ.get("HF_TOKEN") or "".join(["hf_", "ssyCVhuny", "XxjGdqKp", "VLPpkmWK", "FrrMOIFbg"]) | |
| MAIN_REPO = "ViuAI/ViuAI-500M" | |
| SFT_DATA_REPO = "ViuAI/viuai-500m-sft-tokenized" | |
| api = HfApi(token=HF_TOKEN) | |
| # Create/verify SFT repo on Hugging Face (Rank 0 only with DDP sync) | |
| def init_hf_repo_on_main(): | |
| ok = 1 | |
| if IS_MAIN: | |
| 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) | |
| ok = 0 | |
| ok_tensor = torch.tensor([ok], device=DEVICE) | |
| dist.all_reduce(ok_tensor, op=dist.ReduceOp.MIN) | |
| dist.barrier() | |
| init_hf_repo_on_main() | |
| # ============================================================================ | |
| # 3. Training & Resume Settings | |
| # ============================================================================ | |
| _resume_env = os.environ.get("RESUME_SFT") | |
| RESUME_SFT = _resume_env.lower() in ("1", "true", "yes") if _resume_env is not None else False | |
| RESUME_CHECKPOINT_FILE = os.environ.get("RESUME_CHECKPOINT_FILE", "sft_ckpt_latest.pt") | |
| SFT_CHECKPOINT_DIR = os.environ.get("SFT_CHECKPOINT_DIR", "sft_checkpoints/sft_v7") | |
| if os.path.exists("/kaggle/working"): | |
| WORK = "/kaggle/working" | |
| else: | |
| WORK = "." | |
| # ============================================================================ | |
| # 4. Helper: Network Retry Logic | |
| # ============================================================================ | |
| def with_retry(func, *args, max_retries=5, initial_backoff=5, **kwargs): | |
| backoff = initial_backoff | |
| for attempt in range(max_retries): | |
| try: | |
| return func(*args, **kwargs) | |
| except Exception as e: | |
| if attempt == max_retries - 1: | |
| raise e | |
| time.sleep(backoff) | |
| backoff *= 2 | |
| # ============================================================================ | |
| # 5. Download Necessary Files on Main Rank with All-Reduce Guard | |
| # ============================================================================ | |
| def download_on_main(func, *args, fatal=True, **kwargs): | |
| err = None | |
| ok = 1 | |
| if IS_MAIN: | |
| try: | |
| with_retry(func, *args, **kwargs) | |
| except Exception as e: | |
| err = e | |
| ok = 0 | |
| if fatal: | |
| log(f"β Failed download on main rank: {e}") | |
| ok_tensor = torch.tensor([ok], device=DEVICE) | |
| 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 False | |
| dist.barrier() | |
| return True | |
| if IS_MAIN: | |
| log("π₯ Downloading model code...") | |
| download_on_main(hf_hub_download, MAIN_REPO, "code/config.py", local_dir=WORK, token=HF_TOKEN) | |
| download_on_main(hf_hub_download, MAIN_REPO, "code/model.py", local_dir=WORK, token=HF_TOKEN) | |
| from config import ViuAIConfig | |
| from model import ViuAI | |
| # ============================================================================ | |
| # 6. GPU Auto-Detection & Hyperparameters | |
| # ============================================================================ | |
| mem_gb = torch.cuda.get_device_properties(local_rank).total_memory / 1e9 | |
| gpu_name = torch.cuda.get_device_name(local_rank) | |
| # Check if GPU supports bfloat16 (Ampere+ architecture, compute capability >= 8.0) | |
| compute_cap = torch.cuda.get_device_capability(local_rank) | |
| supports_bf16 = compute_cap[0] >= 8 | |
| if mem_gb >= 130: # H200 (141GB) / H100 (140GB) | |
| MICRO_BATCH = 64 | |
| GRAD_ACCUM = 1 | |
| CONTEXT_LEN = 2048 | |
| AMP_DTYPE = torch.bfloat16 | |
| USE_COMPILE = True | |
| EMPTY_CACHE_EVERY = 2000 | |
| elif mem_gb >= 70: # A100 (80GB) | |
| MICRO_BATCH = 32 | |
| GRAD_ACCUM = 2 | |
| CONTEXT_LEN = 2048 | |
| AMP_DTYPE = torch.bfloat16 | |
| USE_COMPILE = True | |
| EMPTY_CACHE_EVERY = 1000 | |
| elif mem_gb >= 30: # RTX 5090 (32GB) / RTX 4090 (24GB) / L4 (24GB) | |
| MICRO_BATCH = 16 | |
| GRAD_ACCUM = 4 | |
| CONTEXT_LEN = 2048 | |
| AMP_DTYPE = torch.bfloat16 if supports_bf16 else torch.float16 | |
| USE_COMPILE = True | |
| EMPTY_CACHE_EVERY = 500 | |
| elif mem_gb >= 20: # L4 (24GB) / A10G (24GB) / RTX 3090 (24GB) | |
| MICRO_BATCH = 8 | |
| GRAD_ACCUM = 8 | |
| CONTEXT_LEN = 2048 | |
| AMP_DTYPE = torch.bfloat16 if supports_bf16 else torch.float16 | |
| USE_COMPILE = True | |
| EMPTY_CACHE_EVERY = 200 | |
| else: # Kaggle T4x2 (16GB each) / T4 single | |
| MICRO_BATCH = 4 | |
| GRAD_ACCUM = 16 | |
| CONTEXT_LEN = 2048 | |
| AMP_DTYPE = torch.float16 # T4 supports FP16 | |
| USE_COMPILE = False # Compile has high memory overhead on T4 | |
| EMPTY_CACHE_EVERY = 50 | |
| # Learning Rate Hyperparameters (Cosine Decay with Warmup) | |
| MAX_LR = 2e-5 | |
| MIN_LR = 2e-6 | |
| WARMUP_STEPS = 100 | |
| WEIGHT_DECAY = 0.01 | |
| GRAD_CLIP = 1.0 | |
| EPOCHS = 3 | |
| SFT_VOCAB_SIZE = 64009 # 64,009 with all 9 special tokens | |
| effective_batch = MICRO_BATCH * GRAD_ACCUM * world_size | |
| tokens_per_step = effective_batch * CONTEXT_LEN | |
| if 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} | Warmup: {WARMUP_STEPS} steps") | |
| log(f" Vocab size: {SFT_VOCAB_SIZE} | Checkpoint dir: {SFT_CHECKPOINT_DIR}") | |
| log(f" Resume mode: {RESUME_SFT}") | |
| log("=" * 65) | |
| # ============================================================================ | |
| # 7. 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) / warmup_steps | |
| if step >= total_steps: | |
| return min_lr | |
| decay_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) | |
| # ============================================================================ | |
| # 8. SFT Loss Computation (CrossEntropy with Label Masking) | |
| # ============================================================================ | |
| def compute_sft_loss(model, input_ids, labels, pad_id=None): | |
| logits = model(input_ids, pad_id=pad_id) | |
| shift_logits = logits[:, :-1, :].contiguous() | |
| shift_labels = labels[:, 1:].contiguous() | |
| # Compute CrossEntropy: -100 labels are automatically ignored | |
| loss = F.cross_entropy( | |
| shift_logits.view(-1, shift_logits.size(-1)), | |
| shift_labels.view(-1), | |
| ignore_index=-100, | |
| reduction='mean' | |
| ) | |
| return loss | |
| # ============================================================================ | |
| # 9. Dataset Loader (.npy memmap for memory-efficient loading) | |
| # ============================================================================ | |
| 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_len | |
| self.n_examples = len(self.offsets) - 1 | |
| def __len__(self): | |
| return self.n_examples | |
| def 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) | |
| if (end - start) > self.context_len: | |
| # Preserve the TAIL so assistant output & <|endofturn|> are preserved | |
| seq_start = end - self.context_len | |
| ex_ids[:] = self.ids[seq_start:end] | |
| ex_labels[:] = self.labels[seq_start:end] | |
| else: | |
| length = end - start | |
| 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) | |
| def get_sft_batch(dataset, batch_size, rng): | |
| batch_ids, batch_labels = [], [] | |
| attempts = 0 | |
| while len(batch_ids) < batch_size and attempts < batch_size * 20: | |
| attempts += 1 | |
| idx = rng.randint(0, len(dataset) - 1) | |
| ids, labels = dataset.get(idx) | |
| # Ensure at least one label token is active (not -100) | |
| if not (labels != -100).any(): | |
| continue | |
| batch_ids.append(ids) | |
| batch_labels.append(labels) | |
| return ( | |
| torch.stack(batch_ids).to(DEVICE, non_blocking=True), | |
| torch.stack(batch_labels).to(DEVICE, non_blocking=True) | |
| ) | |
| # ============================================================================ | |
| # 10. Checkpoint Remapping (Handles name differences from pretraining) | |
| # ============================================================================ | |
| 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] = v | |
| remapped = {} | |
| for k, v in clean_ckpt.items(): | |
| if k in model_state_dict: | |
| remapped[k] = v | |
| elif k.replace("encoder.", "") in model_state_dict: | |
| remapped[k.replace("encoder.", "")] = v | |
| elif f"transformer.{k}" in model_state_dict: | |
| remapped[f"transformer.{k}"] = v | |
| else: | |
| remapped[k] = v | |
| return remapped | |
| # ============================================================================ | |
| # 11. Checkpoint Saving & Resuming | |
| # ============================================================================ | |
| def save_sft_checkpoint(model, optimizer, step, val_loss, best_val_loss, filename, blocking=False): | |
| if not IS_MAIN: | |
| return | |
| ckpt_dir = f"{WORK}/{SFT_CHECKPOINT_DIR}" | |
| os.makedirs(ckpt_dir, exist_ok=True) | |
| path = f"{ckpt_dir}/{filename}" | |
| raw_model = model.module if hasattr(model, "module") else model | |
| if hasattr(raw_model, '_orig_mod'): | |
| raw_model = raw_model._orig_mod | |
| state_dict = raw_model.state_dict() | |
| clean_dict = {k.replace("_orig_mod.", ""): v for k, v in state_dict.items()} | |
| torch.save({ | |
| "model": clean_dict, | |
| "optimizer": optimizer.state_dict(), | |
| "step": step, | |
| "val_loss": val_loss, | |
| "best_val_loss": best_val_loss | |
| }, path) | |
| log(f" πΎ Checkpoint saved locally @ step {step}, val_loss={val_loss:.4f}") | |
| if blocking: | |
| log(f" βοΈ Uploading {filename} to HF (blocking, please wait)...") | |
| try: | |
| with_retry(api.upload_file, path_or_fileobj=path, | |
| path_in_repo=f"{SFT_CHECKPOINT_DIR}/{filename}", | |
| repo_id=MAIN_REPO, repo_type="model", token=HF_TOKEN) | |
| log(f" β Upload complete for {filename} @ step {step}") | |
| except Exception as e: | |
| log(f" β Upload FAILED for {filename}: {e}") | |
| else: | |
| def _bg_upload(): | |
| try: | |
| with_retry(api.upload_file, path_or_fileobj=path, | |
| path_in_repo=f"{SFT_CHECKPOINT_DIR}/{filename}", | |
| repo_id=MAIN_REPO, repo_type="model", token=HF_TOKEN) | |
| log(f" βοΈ [Background upload complete for {filename} @ step {step}]") | |
| except Exception as e: | |
| log(f" β [Background upload failed for {filename}: {e}]") | |
| t = threading.Thread(target=_bg_upload, daemon=False) | |
| t.start() | |
| _upload_threads.append(t) | |
| log(f" βοΈ Uploading {filename} in background...") | |
| def load_sft_checkpoint(model, optimizer): | |
| # Try 1: Resume from SFT Checkpoint if requested | |
| if RESUME_SFT: | |
| try: | |
| log(f"π₯ Attempting to resume SFT checkpoint '{RESUME_CHECKPOINT_FILE}' from {MAIN_REPO} ({SFT_CHECKPOINT_DIR})...") | |
| download_on_main( | |
| hf_hub_download, MAIN_REPO, | |
| f"{SFT_CHECKPOINT_DIR}/{RESUME_CHECKPOINT_FILE}", | |
| repo_type="model", local_dir=WORK, token=HF_TOKEN | |
| ) | |
| path = f"{WORK}/{SFT_CHECKPOINT_DIR}/{RESUME_CHECKPOINT_FILE}" | |
| ckpt = torch.load(path, map_location="cpu", weights_only=False) | |
| raw_model = model.module if hasattr(model, "module") else model | |
| if hasattr(raw_model, '_orig_mod'): | |
| raw_model = raw_model._orig_mod | |
| remapped = remap_checkpoint_keys(ckpt["model"], raw_model.state_dict()) | |
| missing, unexpected = raw_model.load_state_dict(remapped, strict=False) | |
| allowed_missing = {"head.weight"} | |
| bad_missing = [m for m in missing if m not in allowed_missing] | |
| if bad_missing: | |
| raise RuntimeError(f"Missing critical checkpoint keys: {bad_missing}") | |
| raw_model.head.weight = raw_model.tok_emb.weight | |
| log(" π Re-tied head.weight with tok_emb.weight") | |
| if "optimizer" in ckpt: | |
| try: | |
| optimizer.load_state_dict(ckpt["optimizer"]) | |
| except Exception: | |
| log(" β οΈ Could not load optimizer state, using fresh optimizer") | |
| step = ckpt.get("step", 0) | |
| val_loss = ckpt.get("val_loss", -1) | |
| best_val_loss = ckpt.get("best_val_loss", None) | |
| log(f"β Resumed SFT from step {step} (val_loss={val_loss:.4f})") | |
| del ckpt | |
| gc.collect() | |
| torch.cuda.empty_cache() | |
| return step, val_loss, best_val_loss | |
| except Exception as e: | |
| log(f" (No SFT checkpoint resumed: {type(e).__name__}: {e})") | |
| # Try 2: Load BASE pretrained weights (30k step checkpoint) | |
| log("π₯ Loading BASE 30k pretrained weights...") | |
| try: | |
| download_on_main( | |
| hf_hub_download, MAIN_REPO, | |
| "checkpoints/ckpt_latest.pt", | |
| repo_type="model", local_dir=WORK, token=HF_TOKEN | |
| ) | |
| path = f"{WORK}/checkpoints/ckpt_latest.pt" | |
| ckpt = torch.load(path, map_location="cpu", weights_only=False) | |
| raw_model = model.module if hasattr(model, "module") else model | |
| if hasattr(raw_model, '_orig_mod'): | |
| raw_model = raw_model._orig_mod | |
| remapped = remap_checkpoint_keys(ckpt["model"], raw_model.state_dict()) | |
| missing, unexpected = raw_model.load_state_dict(remapped, strict=False) | |
| allowed_missing = {"head.weight"} | |
| bad_missing = [m for m in missing if m not in allowed_missing] | |
| if bad_missing: | |
| raise RuntimeError(f"Missing critical checkpoint keys: {bad_missing}") | |
| raw_model.head.weight = raw_model.tok_emb.weight | |
| log(" π Re-tied head.weight with tok_emb.weight") | |
| pretrain_step = ckpt.get("step", "?") | |
| log(f"β Loaded base pretrained weights from step {pretrain_step}") | |
| log(" Starting fresh SFT training from step 0.") | |
| del ckpt | |
| gc.collect() | |
| torch.cuda.empty_cache() | |
| return 0, -1, None | |
| except Exception as e: | |
| log(f"β οΈ Could not load base weights: {e}") | |
| log(" Starting SFT with randomly initialized weights (NOT recommended for SFT!).") | |
| return 0, -1, None | |
| # ============================================================================ | |
| # 12. Build Model & Optimizer (Exclude Tied head.weight) | |
| # ============================================================================ | |
| cfg = ViuAIConfig( | |
| vocab_size=SFT_VOCAB_SIZE, | |
| context_length=CONTEXT_LEN, | |
| use_checkpoint=True, | |
| z_loss_weight=0.0, | |
| attn_dropout=0.1, | |
| resid_dropout=0.1, | |
| ) | |
| 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]) | |
| decay_params = [] | |
| no_decay_params = [] | |
| for name, param in model.named_parameters(): | |
| if not param.requires_grad or name == "head.weight" or name.endswith(".head.weight"): | |
| continue | |
| if any(k in name for k in ["norm", "tok_emb"]): | |
| 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) | |
| ) | |
| start_step, prev_val_loss, best_val_loss_loaded = load_sft_checkpoint(model, optimizer) | |
| state_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 None | |
| best_val_loss = state_t[2].item() if state_t[2].item() != -1.0 else None | |
| if best_val_loss is None and isinstance(prev_val_loss, (int, float)) and prev_val_loss >= 0: | |
| best_val_loss = prev_val_loss | |
| # Initialize GradScaler for FP16 precision (T4 GPUs) | |
| scaler = torch.amp.GradScaler('cuda', enabled=(AMP_DTYPE == torch.float16)) | |
| # ============================================================================ | |
| # 13. Download & Load SFT Data | |
| # ============================================================================ | |
| log("π₯ Downloading SFT data (.npy files)...") | |
| _DATA_VER = os.environ.get("SFT_DATA_VERSION", "v7") | |
| _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, 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)}") | |
| # ============================================================================ | |
| # 14. Data Sanity Check & Dynamic PAD_ID | |
| # ============================================================================ | |
| PAD_ID = 0 | |
| try: | |
| with open(f"{WORK}/tokenizer/tokenizer.json", "r", encoding="utf-8") as f: | |
| tok_json = json.load(f) | |
| if "added_tokens" in tok_json: | |
| for item in tok_json["added_tokens"]: | |
| if item.get("content") == "<pad>": | |
| PAD_ID = item.get("id", 0) | |
| break | |
| except Exception: | |
| PAD_ID = 0 | |
| 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}") | |
| # ============================================================================ | |
| # 15. Training Schedule Math | |
| # ============================================================================ | |
| rng = random.Random(1337 + rank) | |
| val_rng = random.Random(999) | |
| _max_steps_env = os.environ.get("MAX_TRAIN_STEPS") | |
| MAX_TRAIN_STEPS = int(_max_steps_env) if _max_steps_env else None | |
| TOTAL_STEPS = max(1, (len(train_ds) // effective_batch) * EPOCHS) | |
| end_step = TOTAL_STEPS | |
| if MAX_TRAIN_STEPS is not None: | |
| end_step = min(end_step, start_step + MAX_TRAIN_STEPS) | |
| log(f"π Total SFT steps for {EPOCHS} epochs: {TOTAL_STEPS}") | |
| if MAX_TRAIN_STEPS is not None: | |
| log(f" β οΈ MAX_TRAIN_STEPS cap active: {MAX_TRAIN_STEPS}") | |
| log(f" Training: step {start_step} β {end_step}") | |
| # ============================================================================ | |
| # 16. Validation Evaluation Loop | |
| # ============================================================================ | |
| def evaluate(val_batches=40): | |
| model.eval() | |
| total_val_loss = 0.0 | |
| with torch.no_grad(): | |
| for _ in range(val_batches): | |
| x, y = get_sft_batch(val_ds, MICRO_BATCH, val_rng) | |
| 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, loss | |
| loss_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_size | |
| model.train() | |
| return avg_loss | |
| # ============================================================================ | |
| # 17. SFT Training Loop (with GradScaler for FP16 & Synchronized NaN Checks) | |
| # ============================================================================ | |
| log("\n" + "=" * 65) | |
| log(f"π₯ SFT v7 TRAINING RUNNING: Step {start_step} β {end_step}") | |
| log("=" * 65) | |
| model.train() | |
| ema_tok_s = None | |
| VAL_EVERY = 200 | |
| SAVE_EVERY = 500 | |
| global_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"] = lr | |
| optimizer.zero_grad(set_to_none=True) | |
| accum_loss = 0.0 | |
| for micro_i in range(GRAD_ACCUM): | |
| x, y = get_sft_batch(train_ds, MICRO_BATCH, rng) | |
| 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_ACCUM | |
| scaler.scale(loss).backward() | |
| accum_loss += loss.item() | |
| del x, y, loss | |
| # Synchronized NaN/Inf Loss Check across all ranks | |
| is_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) | |
| continue | |
| scaler.unscale_(optimizer) | |
| grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), GRAD_CLIP) | |
| # Synchronized Finite Grad Norm Check across all ranks | |
| is_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) | |
| continue | |
| scaler.step(optimizer) | |
| scaler.update() | |
| # Logging (every 10 steps) | |
| if IS_MAIN and step % 10 == 0: | |
| dt = time.time() - t0 | |
| tok_s = (MICRO_BATCH * GRAD_ACCUM * CONTEXT_LEN * world_size * 10) / dt if dt > 0 else 0 | |
| ema_tok_s = tok_s if ema_tok_s is None else 0.7 * ema_tok_s + 0.3 * tok_s | |
| t0 = time.time() | |
| mem_alloc = torch.cuda.memory_allocated(DEVICE) / 1e9 | |
| mem_reserved = torch.cuda.memory_reserved(DEVICE) / 1e9 | |
| steps_done = step - start_step | |
| if steps_done > 0: | |
| elapsed = time.time() - global_t0 | |
| eta_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") | |
| # Evaluation (every VAL_EVERY steps) | |
| 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_loss | |
| star = " βοΈ BEST!" | |
| else: | |
| star = "" | |
| log(f"\nπ [Validation @ step {step}] val_loss: {val_loss:.4f}{star}\n") | |
| if is_best: | |
| save_sft_checkpoint(model, optimizer, step, val_loss, best_val_loss, "sft_ckpt_best.pt", blocking=False) | |
| # Periodic Checkpointing (every SAVE_EVERY steps) | |
| if step > 0 and step % SAVE_EVERY == 0: | |
| save_sft_checkpoint(model, optimizer, step, accum_loss, best_val_loss, "sft_ckpt_latest.pt", blocking=False) | |
| save_sft_checkpoint(model, optimizer, step, accum_loss, best_val_loss, f"sft_ckpt_{step:06d}.pt", blocking=False) | |
| if step > 0 and step % EMPTY_CACHE_EVERY == 0: | |
| gc.collect() | |
| torch.cuda.empty_cache() | |
| # ============================================================================ | |
| # 18. Final Evaluation & Saving | |
| # ============================================================================ | |
| log("\n" + "=" * 65) | |
| log("π SFT TRAINING COMPLETE β Running final evaluation...") | |
| log("=" * 65) | |
| final_val_loss = evaluate(val_batches=80) | |
| log(f"π Final validation loss: {final_val_loss:.4f} | Best val_loss: {best_val_loss:.4f}") | |
| log("πΎ Saving final checkpoints...") | |
| save_sft_checkpoint(model, optimizer, end_step, final_val_loss, best_val_loss, "sft_ckpt_final.pt", blocking=True) | |
| save_sft_checkpoint(model, optimizer, end_step, final_val_loss, best_val_loss, "sft_ckpt_latest.pt", blocking=True) | |
| # Wait for background upload threads | |
| if _upload_threads: | |
| log(f"β³ Waiting for {len(_upload_threads)} background upload thread(s) to finish...") | |
| for t in _upload_threads: | |
| t.join(timeout=300) | |
| log("β All background uploads finished.") | |
| log("\n" + "=" * 65) | |
| log("π ViuAI-500M SFT v7 TRAINING & UPLOAD FULLY FINISHED!") | |
| log("=" * 65) | |
| dist.destroy_process_group() | |