Upload folder using huggingface_hub
Browse filesFiles changed (2)
- code/build_sft_v15_dataset.py+47-28
- code/train_sft.py+123-110
4 unmodified lines56788910111 unmodified line131415161718199 unmodified lines293031313233333435363722 unmodified lines6061626263646566220 unmodified lines2872882892892902912922931 unmodified line2952962972972982993003013023033023043053063073 unmodified lines3113123133123143153163173153183193203213224 unmodified lines32732832932632732833033133233333433520 unmodified lines3563573583593603613627 unmodified lines3703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004019 unmodified lines41141241338338438538638738838939039139239339439539639741441541641741841942042142242342442511 unmodified lines4374384394214404414424434 unmodified linesArchitecture:
- Stage 1: 25,000 Pure English Foundation (Reasoning, Code, Math, Instructions, Identity & Natural Chat)
- Stage 2: 25,000 Hinglish Adaptation (80% Hinglish/Hindi + 20% English Anchor)
- Identity Ingestion: 2,213 dedicated Sarus / ViuAI Identity samples (final_viuai_dataset_identity.json)
- Identity Ingestion: Dedicated Sarus / ViuAI Identity samples (final_viuai_dataset_identity.json)
- Thinking: 100% [THINK] ... [/THINK] Chain-of-Thought
- Natural Warm Greetings: Hand-crafted conversational greetings (Zero Robotic Tone)
- Sequence Length: MAX_SEQ_LEN = 2048 (Zero Truncation)1 unmodified line 1. .jsonl format (Standard Hugging Face / TRL SFTTrainer / LLaMA-Factory)
2. .npy packed format (Zero-overhead mmap arrays for ViuAI custom PyTorch engine)
- Cross-Platform: 100% Linux & Windows compatible (Zero hardcoded OS paths)
- Production Robustness: Zero negative slicing bug & strict prompt-length validation
================================================================================
"""
9 unmodified linesfrom transformers import PreTrainedTokenizerFast
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
if hasattr(sys.stderr, "reconfigure"):
sys.stderr.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
# ------------------------------------------------------------------------------
# 1. Configuration & Paths (100% Cross-Platform)22 unmodified linesnp.random.seed(SEED)
print("=" * 80)
print("π ViuAI Sarus-500M β SFT v15 Master 50k Dataset Builder (with Identity Ingestion)")
print("π ViuAI Sarus-500M β SFT v15 Master 50k Dataset Builder (Production Ready)")
print("=" * 80)
HF_TOKEN = os.environ.get("HF_TOKEN")220 unmodified lines hindi_pool.insert(0, g)
# ------------------------------------------------------------------------------
# 6. Compose Stage 1 & Stage 2 Datasets
# 6. Compose Stage 1 & Stage 2 Datasets (Negative Slicing Safeguarded)
# ------------------------------------------------------------------------------
print("\n" + "=" * 80)
print("π¦ COMPOSING STAGE 1 & STAGE 2 MASTER SETS")1 unmodified line
# Stage 1: 25,000 Pure English Foundation (including English Identity)
random.shuffle(english_pool)
stage1_core = english_pool[: TARGET_STAGE1_SAMPLES - len(en_identity)]
need_stage1 = max(0, TARGET_STAGE1_SAMPLES - len(en_identity))
stage1_core = english_pool[:need_stage1]
stage1_data = stage1_core + en_identity
random.shuffle(stage1_data)
print(f"π― Stage 1 (Pure English Foundation): {len(stage1_data):,} samples")
print(f" β’ English Core: {len(stage1_core):,}")
print(f" β’ English Identity: {len(en_identity):,} (~2.9%)")
print(f" β’ English Identity: {len(en_identity):,} (~{len(en_identity)/len(stage1_data)*100:.1f}%)")
# Stage 2: 25,000 Hinglish & Hindi Adaptation (80% Hinglish/Hindi + 20% English Anchor)
random.shuffle(hinglish_pool)3 unmodified linestarget_hindi_count = 6000
target_anchor_count = 5000
stage2_hinglish_core = hinglish_pool[: target_hinglish_count - len(hinglish_identity)]
need_hinglish = max(0, target_hinglish_count - len(hinglish_identity))
stage2_hinglish_core = hinglish_pool[:need_hinglish]
stage2_hinglish = stage2_hinglish_core + hinglish_identity
stage2_hindi_core = hindi_pool[: target_hindi_count - len(hindi_identity)]
need_hindi = max(0, target_hindi_count - len(hindi_identity))
stage2_hindi_core = hindi_pool[:need_hindi]
stage2_hindi = stage2_hindi_core + hindi_identity
stage2_anchor = english_pool[TARGET_STAGE1_SAMPLES : TARGET_STAGE1_SAMPLES + target_anchor_count]4 unmodified linesrandom.shuffle(stage2_data)
print(f"π― Stage 2 (Hinglish Adaptation): {len(stage2_data):,} samples")
print(f" β’ Hinglish (Core + Identity): {len(stage2_hinglish):,} (56%) [Identity: {len(hinglish_identity):,}]")
print(f" β’ Hindi (Core + Identity): {len(stage2_hindi):,} (24%) [Identity: {len(hindi_identity):,}]")
print(f" β’ English Anchor: {len(stage2_anchor):,} (20%)")
print(f" β’ Hinglish (Core + Identity): {len(stage2_hinglish):,} ({len(stage2_hinglish)/len(stage2_data)*100:.1f}%) [Identity: {len(hinglish_identity):,}]")
print(f" β’ Hindi (Core + Identity): {len(stage2_hindi):,} ({len(stage2_hindi)/len(stage2_data)*100:.1f}%) [Identity: {len(hindi_identity):,}]")
print(f" β’ English Anchor: {len(stage2_anchor):,} ({len(stage2_anchor)/len(stage2_data)*100:.1f}%)")
# ------------------------------------------------------------------------------
# 7. Tokenization & Packing Engine (Exports both .jsonl and .npy)20 unmodified lines
jsonl_path = os.path.join(output_dir, f"{split_name}.jsonl")
jsonl_entries = []
skipped_long_prompts = 0
for item in tqdm(dataset, desc=f"Processing {split_name} ({len(dataset):,})"):
inst = item["instruction"]7 unmodified lines thought_str = f"[THINK]\n{th}\n[/THINK]\n"
response_str = f"{resp}<|endofturn|>"
# Binary Tokenization
prompt_ids = tokenizer.encode(prompt_str, add_special_tokens=False)
# SAFEGUARD 1: Skip if prompt itself fills or exceeds context window
if len(prompt_ids) >= MAX_SEQ_LEN:
skipped_long_prompts += 1
continue
target_ids = tokenizer.encode(thought_str + response_str, add_special_tokens=False)
full_ids = prompt_ids + target_ids
if len(full_ids) > MAX_SEQ_LEN:
full_ids = full_ids[:MAX_SEQ_LEN]
end_id = tokenizer.encode("<|endofturn|>")[-1]
full_ids[-1] = end_id
labels = [-100] * min(len(prompt_ids), len(full_ids))
remaining = len(full_ids) - len(labels)
# SAFEGUARD 2: Skip if no target tokens left after truncation
if remaining <= 0:
skipped_long_prompts += 1
continue
labels.extend(full_ids[len(labels):])
full_text = f"{prompt_str}{thought_str}{response_str}"
# JSONL Entry for TRL SFTTrainer / Hugging Face / LLaMA-Factory9 unmodified lines {"role": "assistant", "content": f"[THINK]\n{th}\n[/THINK]\n{resp}"}
]
})
# Binary Tokenization
prompt_ids = tokenizer.encode(prompt_str, add_special_tokens=False)
target_ids = tokenizer.encode(thought_str + response_str, add_special_tokens=False)
full_ids = prompt_ids + target_ids
if len(full_ids) > MAX_SEQ_LEN:
full_ids = full_ids[:MAX_SEQ_LEN]
end_id = tokenizer.encode("<|endofturn|>")[-1]
full_ids[-1] = end_id
labels = [-100] * min(len(prompt_ids), len(full_ids))
remaining = len(full_ids) - len(labels)
if remaining > 0:
labels.extend(full_ids[len(labels):])
token_list.extend(full_ids)
label_list.extend(labels)
offsets.append(len(token_list))
domain_ids.append(d_id)
if skipped_long_prompts > 0:
print(f" β οΈ Skipped {skipped_long_prompts} samples with prompt >= {MAX_SEQ_LEN}")
# Save JSONL
with open(jsonl_path, "w", encoding="utf-8") as f:
for entry in jsonl_entries:11 unmodified lines np.save(os.path.join(output_dir, f"{split_name}_offsets.npy"), off_arr)
np.save(os.path.join(output_dir, f"{split_name}_domains.npy"), dom_arr)
print(f" β
Saved {split_name.upper()} NPY: {len(dataset):,} samples | {len(tok_arr):,} total tokens.")
print(f" β
Saved {split_name.upper()} NPY: {len(jsonl_entries):,} samples | {len(tok_arr):,} total tokens.")
metadata = {
"stage": stage_name,122345678991011121314156 unmodified lines2223242526272815 unmodified lines44454643474849505148495051525354555657585960616263646566676869707172737452535455565758596061626379806481656684676869878889909192939495969798991001011021031041051061071087071727374757677787980818283848586878889909192939495111112113114969798991001161011021031041201211221231241251051061071081091101111121131141151161171181191201211221231241251291261271311281291331301311321361331341381351361371381421391401411421431441451481491461471481511491501511521551531541551 unmodified line1571581591631601611621631681641651661675 unmodified lines17317417517618017717817918018118218318418518618818918718818919019119219319419619519619719832 unmodified lines23123223323423523623717 unmodified lines25525625725825825926026116 unmodified lines27827928028128228128228328423 unmodified lines30830931031231131231331431531731831931631731831932032132232332432520 unmodified lines3463473483463473493503513521 unmodified line3543553563573583593603613623603613633643653663673663673683693703713 unmodified lines37537637737837938038126 unmodified lines4084094104094104114124134142 unmodified lines4174184194194204214204214224234244254264274284294304314324334344354364244254374384394404 unmodified lines4454464474364484494504514404414524534544551 unmodified line457458459449460461462463451452453464465466467468469470# ==============================================================================
# π ViuAI Sarus-500M β SFT v15 Master 2-Stage Training Engine
# π ViuAI Sarus-500M β SFT v15 Master 2-Stage Training Engine (Production Ready)
# ==============================================================================
# Architecture:
# - Stage 1: Pure English Foundation (25k samples: Reasoning, Code, Math, Instructions, Natural Chat)
# - Stage 2: Hinglish Adaptation (25k samples: 80% Hinglish/Hindi + 20% English Anchor)
# - Shuffling: Standard Uniform Epoch Shuffle (shuffle=True) β Zero Domain Hijack
# - Reasoning: 100% [THINK] ... [/THINK] Loss Masking on Assistant Tokens
# - Anti-Overfitting Safeguards: Cosine LR Decay, Weight Decay 0.1, Grad Accum 4
# - Anti-Overfitting Safeguards: Cosine LR Decay, Weight Decay 0.1, Grad Accum 4 (or auto-detected)
# - Hardware Adaptability: Auto-detects VRAM & auto-tunes batch_size & grad_accum (Default 8 for 24GB)
# - Gradient Accumulation Cleanup: Zero leftover micro-batch loss at epoch boundaries
# - Dynamic Speed Tracking: Precise real-time tokens/sec calculation
# - Self-Contained Cloud Sync: Auto-downloads tokenized datasets and base checkpoints from HF
# - Output Checkpoint: sft_checkpoints/sft_v15/sft_v15_stage1.pt & sft_v15_final.pt
# ==============================================================================6 unmodified linesimport json
import random
import argparse
import contextlib
from datetime import datetime, timezone
import numpy as np15 unmodified linesif torch.cuda.is_available():
torch.cuda.manual_seed_all(42)
# Add code directory to path and auto-fetch companion files if missing
# Import ViuAI Architecture
cur_dir = os.path.dirname(os.path.abspath(__file__))
if cur_dir not in sys.path:
sys.path.insert(0, cur_dir)
try:
from config import ViuAIConfig
from model import ViuAI
except ImportError:
for dep in ["config.py", "model.py"]:
dep_path = os.path.join(cur_dir, dep)
if not os.path.exists(dep_path):
try:
hf_hub_download(
repo_id="ViuAI/ViuAI-500M",
filename=f"code/{dep}",
local_dir=cur_dir if os.path.basename(cur_dir) == "code" else os.path.join(cur_dir, "code"),
token=os.environ.get("HF_TOKEN")
)
except Exception:
pass
try:
from config import ViuAIConfig
from model import ViuAI
except ImportError:
p_dir = os.path.abspath(os.path.join(cur_dir, "code"))
if os.path.exists(p_dir) and p_dir not in sys.path:
sys.path.insert(0, p_dir)
from config import ViuAIConfig
from model import ViuAI
# --- 1. Dataset Class ---
from config import ViuAIConfig
from model import ViuAI
# --- 1. Memory-Mapped Dataset for Zero-Overhead Token Streaming ---
class SFTDataset(Dataset):
def __init__(self, ids_path, labels_path, offsets_path, domains_path=None):
super().__init__()
self.offsets = np.load(offsets_path, mmap_mode="r")
self.num_samples = len(self.offsets) - 1
self.ids = np.load(ids_path, mmap_mode="r")
self.labels = np.load(labels_path, mmap_mode="r")
self.offsets = np.load(offsets_path)
self.domains = np.load(domains_path) if (domains_path and os.path.exists(domains_path)) else None
self.domains = np.load(domains_path, mmap_mode="r") if (domains_path and os.path.exists(domains_path)) else None
self.n_samples = len(self.offsets) - 1
def __len__(self):
return self.n_samples
return self.num_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. Dynamic Padding Batch Collate Function ---
def collate_fn(batch, pad_token_id=0):
input_ids_list, labels_list, domain_list = zip(*batch)
max_len = max(x.size(0) for x in input_ids_list)
batch_size = len(input_ids_list)
padded_inputs = torch.full((batch_size, max_len), pad_token_id, dtype=torch.int64)
padded_labels = torch.full((batch_size, max_len), -100, dtype=torch.int64)
for i, (inp, lbl) in enumerate(zip(input_ids_list, labels_list)):
length = inp.size(0)
padded_inputs[i, :length] = inp
padded_labels[i, :length] = lbl
return padded_inputs, padded_labels, torch.tensor(domain_list, dtype=torch.uint8)
start = int(self.offsets[idx])
end = int(self.offsets[idx + 1])
seq_ids = torch.from_numpy(self.ids[start:end].astype(np.int64))
seq_labels = torch.from_numpy(self.labels[start:end].astype(np.int64))
domain_id = int(self.domains[idx]) if self.domains is not None else 0
return seq_ids, seq_labels, domain_id
# --- 2. Dynamic Padding Collate Function ---
def collate_fn(batch, pad_token_id=0, ignore_index=-100):
inputs, labels, domain_ids = zip(*batch)
max_len = max(x.size(0) for x in inputs)
# Align to multiple of 8 for Tensor Core efficiency
max_len = ((max_len + 7) // 8) * 8
batch_inputs = torch.full((len(batch), max_len), pad_token_id, dtype=torch.long)
batch_labels = torch.full((len(batch), max_len), ignore_index, dtype=torch.long)
for i, (inp, lbl) in enumerate(zip(inputs, labels)):
batch_inputs[i, :inp.size(0)] = inp
batch_labels[i, :lbl.size(0)] = lbl
return batch_inputs, batch_labels, torch.tensor(domain_ids, dtype=torch.long)
# --- 3. Cosine Learning Rate Schedule with Warmup ---
def get_lr(step, warmup_steps, total_steps, max_lr, min_lr):
if step < warmup_steps:
return max_lr * (step + 1) / warmup_steps
if step > total_steps:
def get_lr(it, warmup_steps, total_steps, max_lr, min_lr):
if it < warmup_steps:
return max_lr * (it + 1) / max(1, warmup_steps)
if it > total_steps:
return min_lr
decay_ratio = (step - warmup_steps) / (total_steps - warmup_steps)
decay_ratio = (it - warmup_steps) / max(1, total_steps - warmup_steps)
coeff = 0.5 * (1.0 + math.cos(math.pi * decay_ratio))
return min_lr + coeff * (max_lr - min_lr)
# --- 4. Remote Cloud Downloader ---
def ensure_cloud_data_and_checkpoint(stage: str, data_dir: str, ckpt_path: str, hf_token: str = None):
"""Auto-downloads tokenized datasets and starting checkpoints if missing."""
token = hf_token or os.environ.get("HF_TOKEN")
# 1. Ensure Dataset
# --- 4. Auto-detect Optimal Batch Size by Hardware VRAM ---
def auto_detect_batch_params():
if not torch.cuda.is_available():
return 4, 16
vram_gb = torch.cuda.get_device_properties(0).total_memory / (1024 ** 3)
if vram_gb >= 70: # H100, H200, A100-80GB
return 32, 4 # 32 micro batch * 4 accum = 128 effective
elif vram_gb >= 35: # A100-40GB, A6000
return 16, 8 # 16 micro batch * 8 accum = 128 effective
elif vram_gb >= 20: # RTX 3090, RTX 4090, L4, A10G (24GB)
return 8, 16 # 8 micro batch * 16 accum = 128 effective
else: # T4, V100 (16GB)
return 4, 32 # 4 micro batch * 32 accum = 128 effective
# --- 5. Self-Contained Cloud Download Helper ---
def ensure_cloud_data_and_checkpoint(stage: str, data_dir: str, ckpt_path: str, token: str = None):
stage_subfolder = "sft_v15_stage1" if stage == "stage1" else "sft_v15_stage2"
target_data_folder = os.path.join(data_dir, stage_subfolder)
required_files = [
needed_data_files = [
"train_tokens.npy", "train_labels.npy", "train_offsets.npy", "train_domains.npy",
"val_tokens.npy", "val_labels.npy", "val_offsets.npy", "val_domains.npy", "metadata.json"
"val_tokens.npy", "val_labels.npy", "val_offsets.npy", "val_domains.npy"
]
missing_data = any(not os.path.exists(os.path.join(target_data_folder, f)) for f in required_files)
missing_data = any(not os.path.exists(os.path.join(target_data_folder, f)) for f in needed_data_files)
if missing_data:
print(f"π₯ Downloading dataset {stage_subfolder} from HF ViuAI/viuai-500m-sft-tokenized...")
print(f"\nπ Dataset missing locally for {stage_subfolder}. Downloading from Hugging Face Hub (ViuAI/viuai-500m-sft-tokenized)...")
os.makedirs(target_data_folder, exist_ok=True)
for f in required_files:
for f in needed_data_files + ["train.jsonl", "val.jsonl", "metadata.json"]:
try:
hf_hub_download(
repo_id="ViuAI/viuai-500m-sft-tokenized",
filename=f"{stage_subfolder}/{f}",
subfolder=stage_subfolder,
filename=f,
local_dir=data_dir,
repo_type="dataset",
token=token
)
except Exception as e:
print(f" β οΈ Note on {f}: {e}")
print(f"β
Dataset {stage_subfolder} ready at {target_data_folder}")
pass
print(f"β
Downloaded {stage_subfolder} dataset successfully!")
# 2. Ensure Starting Checkpoint
if not os.path.exists(ckpt_path):
print(f"\nπ Initial Checkpoint missing at {ckpt_path}. Downloading from Hugging Face Hub (ViuAI/ViuAI-500M)...")
os.makedirs(os.path.dirname(ckpt_path), exist_ok=True)
if stage == "stage1":
print(f"π₯ Downloading base checkpoint from HF ViuAI/ViuAI-500M (checkpoints/ckpt_latest.pt)...")
hf_hub_download(
repo_id="ViuAI/ViuAI-500M",
filename="checkpoints/ckpt_latest.pt",1 unmodified line token=token
)
else:
print(f"π₯ Downloading Stage 1 checkpoint from HF ViuAI/ViuAI-500M (sft_checkpoints/sft_v15/sft_v15_stage1.pt)...")
try:
hf_hub_download(
repo_id="ViuAI/ViuAI-500M",
filename="sft_checkpoints/sft_v15/sft_v15_stage1.pt",
local_dir=os.path.dirname(os.path.dirname(ckpt_path)),
local_dir=os.path.dirname(os.path.dirname(os.path.dirname(ckpt_path))),
token=token
)
except Exception:5 unmodified lines token=token
)
# --- 5. Main Training Pipeline ---
# --- 6. Main Training Pipeline ---
def train():
auto_b, auto_ga = auto_detect_batch_params()
parser = argparse.ArgumentParser(description="ViuAI Sarus-500M β SFT v15 Master Training Engine")
parser.add_argument("--stage", type=str, choices=["stage1", "stage2"], default="stage1",
help="Training curriculum stage: 'stage1' (Pure English) or 'stage2' (Hinglish Adaptation)")
parser.add_argument("--data_dir", type=str, default=None, help="Root directory containing tokenized_data")
parser.add_argument("--init_ckpt", type=str, default=None, help="Initial checkpoint path")
parser.add_argument("--output_dir", type=str, default=None, help="Directory to save checkpoints")
parser.add_argument("--batch_size", type=int, default=32, help="Micro batch size per forward pass")
parser.add_argument("--grad_accum", type=int, default=4, help="Gradient accumulation steps (effective batch = 128)")
parser.add_argument("--batch_size", type=int, default=auto_b, help=f"Micro batch size (Auto-detected: {auto_b})")
parser.add_argument("--grad_accum", type=int, default=auto_ga, help=f"Gradient accumulation steps (Auto-detected: {auto_ga})")
parser.add_argument("--epochs", type=int, default=2, help="Number of training epochs per stage")
parser.add_argument("--max_lr", type=float, default=1.8e-5, help="Peak learning rate for Cosine Schedule")
parser.add_argument("--min_lr", type=float, default=1.8e-6, help="Minimum learning rate")
parser.add_argument("--weight_decay", type=float, default=0.1, help="AdamW weight decay")
parser.add_argument("--warmup_ratio", type=float, default=0.04, help="Warmup ratio of total steps")
parser.add_argument("--eval_interval", type=int, default=25, help="Validation evaluation step interval")
parser.add_argument("--push_to_hf", action="store_true", default=True, help="Auto-upload checkpoint to Hugging Face")
parser.add_argument("--push_to_hf", action="store_true", default=False, help="Auto-upload checkpoint to Hugging Face (Default: False)")
parser.add_argument("--hf_token", type=str, default=None, help="Hugging Face API token")
args = parser.parse_args()
32 unmodified lines print(f" β’ Epochs: {args.epochs}")
print(f" β’ Max / Min LR: {args.max_lr} / {args.min_lr} (Cosine Schedule)")
print(f" β’ Shuffling: Standard Epoch Shuffle (shuffle=True)")
print(f" β’ Push to HF: {args.push_to_hf}")
print("=" * 80)
# 1. Load Datasets17 unmodified lines batch_size=args.batch_size,
shuffle=True,
collate_fn=collate_fn,
drop_last=True,
drop_last=False,
num_workers=2 if torch.cuda.is_available() else 0,
pin_memory=torch.cuda.is_available()
)16 unmodified lines )
model = ViuAI(config).to(device)
print(f"
π Loading weights from: {init_ckpt}...")
print(f"\nπ Loading weights from: {init_ckpt}...")
ckpt = torch.load(init_ckpt, map_location=device, weights_only=False)
state_dict = ckpt.get("model_state_dict", ckpt.get("model", ckpt))
23 unmodified lines ]
optimizer = torch.optim.AdamW(optimizer_grouped_parameters, lr=args.max_lr, betas=(0.9, 0.95), eps=1e-8)
steps_per_epoch = len(train_loader) // args.grad_accum
steps_per_epoch = math.ceil(len(train_loader) / args.grad_accum)
total_steps = steps_per_epoch * args.epochs
warmup_steps = max(10, int(total_steps * args.warmup_ratio))
print(f"π Training Steps: {steps_per_epoch} steps/epoch | Total: {total_steps} steps | Warmup: {warmup_steps} steps")
# Mixed Precision Setup
dtype = torch.bfloat16 if torch.cuda.is_available() and torch.cuda.is_bf16_supported() else (torch.float16 if torch.cuda.is_available() else torch.float32)
autocast_ctx = torch.amp.autocast(device_type="cuda", dtype=dtype) if torch.cuda.is_available() else torch.amp.autocast(device_type="cpu", dtype=torch.bfloat16)
# Mixed Precision Setup (Clean dtype mapping)
if torch.cuda.is_available():
dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
autocast_ctx = torch.amp.autocast(device_type="cuda", dtype=dtype)
else:
dtype = torch.float32
autocast_ctx = contextlib.nullcontext()
print(f"β‘ Mixed Precision: {dtype}")
# Evaluation Helper20 unmodified lines return avg_loss, ppl
# Initial Validation
print("
π Running initial pre-training validation...")
print("\nπ Running initial pre-training validation...")
val_loss, val_ppl = evaluate()
print(f"π Initial Validation Loss: {val_loss:.4f} | Perplexity: {val_ppl:.2f}")
1 unmodified line global_step = 0
best_val_loss = float("inf")
start_time = time.time()
total_tokens_trained = 0
model.train()
stage_ckpt_name = "sft_v15_stage1.pt" if args.stage == "stage1" else "sft_v15_final.pt"
save_path = os.path.join(output_dir, stage_ckpt_name)
print("
" + "=" * 80)
print("\n" + "=" * 80)
print(f"π STARTING SFT v15 {args.stage.upper()} TRAINING")
print("=" * 80)
for epoch in range(1, args.epochs + 1):
print(f"
--- Epoch {epoch}/{args.epochs} ---")
print(f"\n--- Epoch {epoch}/{args.epochs} ---")
epoch_loss = 0.0
epoch_batches = 0
accum_loss = 0.03 unmodified lines for micro_idx, (inputs, labels, _) in enumerate(train_loader):
inputs = inputs.to(device, non_blocking=True)
labels = labels.to(device, non_blocking=True)
total_tokens_trained += inputs.numel()
with autocast_ctx:
out = model(inputs)26 unmodified lines # Logging
if global_step % 5 == 0 or global_step == 1:
elapsed = time.time() - start_time
tokens_processed = global_step * args.batch_size * args.grad_accum * 512 # rough avg seq
speed = tokens_processed / max(1, elapsed)
speed = total_tokens_trained / max(1e-5, elapsed)
print(f" Step {global_step:4d}/{total_steps} | Epoch {epoch} | Loss: {step_avg_loss:.4f} | LR: {lr:.2e} | Speed: {speed:,.0f} tok/s | Elapsed: {elapsed/60:.1f}m")
# Validation & Checkpointing2 unmodified lines is_best = val_loss < best_val_loss
if is_best:
best_val_loss = val_loss
print(f"
β [EVAL Step {global_step}] Val Loss: {val_loss:.4f} | Val PPL: {val_ppl:.2f} | Best Val: {best_val_loss:.4f} {'(NEW BEST!)' if is_best else ''}
")
print(f"\n β [EVAL Step {global_step}] Val Loss: {val_loss:.4f} | Val PPL: {val_ppl:.2f} | Best Val: {best_val_loss:.4f} {'(NEW BEST!)' if is_best else ''}\n")
# CRITICAL FIX 2: Flush leftover gradient accumulation at epoch boundary
if (micro_idx + 1) % args.grad_accum != 0:
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
lr = get_lr(global_step, warmup_steps, total_steps, args.max_lr, args.min_lr)
for param_group in optimizer.param_groups:
param_group["lr"] = lr
optimizer.step()
optimizer.zero_grad(set_to_none=True)
global_step += 1
leftover_count = (micro_idx + 1) % args.grad_accum
step_avg_loss = accum_loss / max(1, leftover_count)
accum_loss = 0.0
print(f" [Epoch {epoch} Boundary Step {global_step}] Flushed {leftover_count} micro-batches | Loss: {step_avg_loss:.4f}")
# Save Final Checkpoint
print(f"
πΎ Saving {args.stage.upper()} Final Checkpoint to: {save_path}...")
print(f"\nπΎ Saving {args.stage.upper()} Final Checkpoint to: {save_path}...")
torch.save({
"model_state_dict": model.state_dict(),
"config": config.__dict__,4 unmodified lines }, save_path)
print(f"β
Saved Checkpoint ({os.path.getsize(save_path)/(1024**3):.2f} GB)")
# Push to Hugging Face
# Push to Hugging Face (Only if explicitly enabled with --push_to_hf)
if args.push_to_hf:
token = args.hf_token or os.environ.get("HF_TOKEN")
if token:
print(f"
π Uploading {stage_ckpt_name} to HF ViuAI/ViuAI-500M...")
print(f"\nπ Uploading {stage_ckpt_name} to Hugging Face Model Hub (ViuAI/ViuAI-500M)...")
api = HfApi(token=token)
api.upload_file(
path_or_fileobj=save_path,1 unmodified line repo_id="ViuAI/ViuAI-500M",
repo_type="model"
)
print("π Upload to Hugging Face Completed Successfully!")
print("π Checkpoint Uploaded to Hugging Face Successfully!")
else:
print("β οΈ Skipping HF upload: No HF_TOKEN provided.")
print("
" + "=" * 80)
print(f"π SFT v15 {args.stage.upper()} TRAINING RUN COMPLETE!")
print("\n" + "=" * 80)
print(f"π SFT v15 {args.stage.upper()} COMPLETED SUCCESSFULLY!")
print("=" * 80)
if __name__ == "__main__":
train()code/build_sft_v15_dataset.py+47-28
code/train_sft.py+123-110