Upload code/train_sft_v5.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197"""ViuAI-500M SFT V5 Trainer (50k Dataset)========================================Fine-tunes Sarus 500M on the V5 dataset (50,000 clean companion & RAG examples).Checkpoint dir: sft_checkpoints/sft_v5"""import osos.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
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, math, time, random, sys, contextlib, gc, threadingimport 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 datetime import timedelta
# DDP Setupdef 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) return rank, local_rank, world_size
rank, local_rank, world_size = setup_ddp()DEVICE = f"cuda:{local_rank}"IS_MAIN = rank == 0
def log(msg): if IS_MAIN: print(msg, flush=True)
# AuthenticationHF_TOKEN = os.environ.get("HF_TOKEN")if not HF_TOKEN: try: from kaggle_secrets import UserSecretsClient HF_TOKEN = UserSecretsClient().get_secret("HF_TOKEN") os.environ["HF_TOKEN"] = HF_TOKEN except Exception: passif not HF_TOKEN: raise RuntimeError("HF_TOKEN not found! Please set HF_TOKEN.")api = HfApi(token=HF_TOKEN)
# ReposMAIN_REPO = os.environ.get("VIUAI_MODEL_REPO", "ViuAI/ViuAI-500M")SFT_DATA_REPO = os.environ.get("VIUAI_SFT_DATA_REPO", "ViuAI/viuai-500m-sft-tokenized")SFT_CHECKPOINT_DIR = "sft_checkpoints/sft_v5"
if IS_MAIN: create_repo(MAIN_REPO, repo_type="model", token=HF_TOKEN, exist_ok=True, private=True)dist.barrier()
# Model & Config Importsfrom config import ViuAIConfigfrom model import ViuAI
def strip_training_prefixes(state_dict): cleaned = {} for key, value in state_dict.items(): for prefix in ("module._orig_mod.", "_orig_mod.", "module."): if key.startswith(prefix): key = key[len(prefix):] break cleaned[key] = value return cleaned
# Download V5 Tokenized Datadef download_data(): log("๐ฅ Downloading SFT V5 dataset from HF...") files = {} for prefix in ["sft_v5_train", "sft_v5_val"]: for suffix in ["ids", "labels", "offsets"]: filename = f"{prefix}_{suffix}.npy" path = hf_hub_download(repo_id=SFT_DATA_REPO, repo_type="dataset", filename=filename, token=HF_TOKEN) files[f"{prefix}_{suffix}"] = path return files
data_files = download_data()
# Data Loader Classclass SFTDataset(torch.utils.data.Dataset): def __init__(self, ids_path, labels_path, offsets_path, max_len=2048): 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.max_len = max_len self.num_samples = len(self.offsets) - 1
def __len__(self): return self.num_samples
def __getitem__(self, idx): start = self.offsets[idx] end = self.offsets[idx + 1] seq_ids = self.ids[start:end][:self.max_len] seq_labels = self.labels[start:end][:self.max_len]
return torch.from_numpy(seq_ids.astype(np.int64)), torch.from_numpy(seq_labels.astype(np.int64))
train_ds = SFTDataset(data_files["sft_v5_train_ids"], data_files["sft_v5_train_labels"], data_files["sft_v5_train_offsets"])val_ds = SFTDataset(data_files["sft_v5_val_ids"], data_files["sft_v5_val_labels"], data_files["sft_v5_val_offsets"])
def collate_fn(batch): ids_list, labels_list = zip(*batch) max_len = max(len(x) for x in ids_list) padded_ids = torch.full((len(batch), max_len), fill_value=64000, dtype=torch.long) padded_labels = torch.full((len(batch), max_len), fill_value=-100, dtype=torch.long) for i, (seq_ids, seq_labels) in enumerate(zip(ids_list, labels_list)): padded_ids[i, :len(seq_ids)] = seq_ids padded_labels[i, :len(seq_labels)] = seq_labels return padded_ids, padded_labels
train_sampler = torch.utils.data.distributed.DistributedSampler(train_ds, shuffle=True)train_loader = torch.utils.data.DataLoader(train_ds, batch_size=2, sampler=train_sampler, collate_fn=collate_fn)
# Load Model Base Weightslog("๐ Initializing ViuAI-500M Model for V5 Training...")try: ckpt_path = hf_hub_download(repo_id=MAIN_REPO, filename="sft_checkpoints/sft_v4/sft_ckpt_latest.pt", token=HF_TOKEN)except: ckpt_path = hf_hub_download(repo_id=MAIN_REPO, filename="checkpoints/ckpt_latest.pt", token=HF_TOKEN)
checkpoint = torch.load(ckpt_path, map_location="cpu", weights_only=False)state_dict = strip_training_prefixes(checkpoint["model"])
ckpt_vocab_size = state_dict['tok_emb.weight'].shape[0]cfg = ViuAIConfig(vocab_size=ckpt_vocab_size, use_checkpoint=True)model = ViuAI(cfg).to(DEVICE)model.load_state_dict(state_dict, strict=True)model.head.weight = model.tok_emb.weight
model = DDP(model, device_ids=[local_rank])log(f"โ
Model loaded successfully on DDP (Rank {rank})!")
# Optimizeroptimizer = torch.optim.AdamW(model.parameters(), lr=2e-4, betas=(0.9, 0.95), weight_decay=0.01)
# Training Loop (2 Epochs)NUM_EPOCHS = 2log(f"๐ฅ Starting V5 SFT Training for {NUM_EPOCHS} Epochs...")
for epoch in range(NUM_EPOCHS): train_sampler.set_epoch(epoch) model.train() total_loss = 0.0 for step, (x, y) in enumerate(train_loader): x, y = x.to(DEVICE), y.to(DEVICE) optimizer.zero_grad() logits = model(x) # Loss calculation (ignoring -100) loss = F.cross_entropy(logits.view(-1, ckpt_vocab_size), y.view(-1), ignore_index=-100) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) optimizer.step() total_loss += loss.item() if step % 50 == 0: log(f"Epoch [{epoch+1}/{NUM_EPOCHS}] | Step [{step}/{len(train_loader)}] | Loss: {loss.item():.4f}")
# Save Final Checkpointif IS_MAIN: log("๐พ Saving Final V5 Checkpoint...") os.makedirs("v5_checkpoints", exist_ok=True) ckpt_save_path = f"v5_checkpoints/sft_ckpt_latest.pt" unwrapped = model.module if hasattr(model, "module") else model torch.save({"model": unwrapped.state_dict(), "optimizer": optimizer.state_dict()}, ckpt_save_path) log("โ๏ธ Uploading V5 Checkpoint to HF...") api.upload_file( path_or_fileobj=ckpt_save_path, path_in_repo=f"{SFT_CHECKPOINT_DIR}/sft_ckpt_latest.pt", repo_id=MAIN_REPO, repo_type="model" ) log("๐ V5 Training and Upload COMPLETE!")code/train_sft_v5.pyAdded+197