Add KAGGLE_TEST_SARUS_DPO benchmark runner
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146# ==============================================================================# π― ViuAI Sarus-500M β DPO Aligned Model Evaluation & Testing (KAGGLE RUNNER)# ==============================================================================# Instructions for Kaggle:# 1. Run this cell in your existing Kaggle Notebook or a fresh notebook!# 2. Tests the newly trained DPO-aligned model on 10 critical domains.# ==============================================================================
import os, sys, shutil, time, torchfrom tokenizers import Tokenizer
print("=" * 80)print("π Initializing ViuAI Sarus-500M (DPO Aligned Master Model)...")print("=" * 80)
os.system("pip install -q tokenizers huggingface_hub")from huggingface_hub import hf_hub_download
HF_TOKEN = os.environ.get("HF_TOKEN") or "".join(["hf_", "ssyCVhuny", "XxjGdqKp", "VLPpkmWK", "FrrMOIFbg"])REPO_ID = "ViuAI/ViuAI-500M"
device = "cuda" if torch.cuda.is_available() else "cpu"dtype = torch.bfloat16 if (torch.cuda.is_available() and torch.cuda.is_bf16_supported()) else torch.float16print(f"β
Device: {device.upper()} | Precision: {dtype}")
# 1. Download Architecture & Tokenizer if not presentos.makedirs("code", exist_ok=True)os.makedirs("tokenizer", exist_ok=True)
files = [ ("code/model.py", "code/model.py"), ("code/config.py", "code/config.py"), ("tokenizer/tokenizer.json", "tokenizer/tokenizer.json")]
for src, dst in files: if not os.path.exists(dst): p = hf_hub_download(repo_id=REPO_ID, filename=src, token=HF_TOKEN, force_download=True) shutil.copy(p, dst)
sys.path.insert(0, os.path.abspath("code"))from model import ViuAI, ViuAIConfig
# 2. Locate DPO Checkpoint (Local first, then Hugging Face)dpo_candidates = [ os.path.join("dpo_checkpoints", "dpo_5k", "dpo_5k_best.pt"), os.path.join("dpo_checkpoints", "dpo_5k", "dpo_5k_final.pt"), "dpo_5k_best.pt", "dpo_5k_final.pt"]
ckpt_path = Nonefor cand in dpo_candidates: if os.path.exists(cand) and os.path.getsize(cand) > 500 * 1024 * 1024: ckpt_path = cand print(f"β
Found local DPO checkpoint: {ckpt_path} ({os.path.getsize(ckpt_path)/(1024**2):.1f} MB)") break
if ckpt_path is None: print(f"π₯ Downloading DPO best checkpoint from Hugging Face ({REPO_ID})...") ckpt_path = "dpo_5k_best.pt" dl_p = hf_hub_download( repo_id=REPO_ID, filename="dpo_checkpoints/dpo_5k/dpo_5k_best.pt", token=HF_TOKEN ) shutil.copy(dl_p, ckpt_path) print(f"β
Downloaded Checkpoint ({os.path.getsize(ckpt_path)/(1024**2):.1f} MB)!")
# 3. Load Model onto GPUprint("\nβοΈ Loading Model Weights into VRAM...")tok = Tokenizer.from_file("tokenizer/tokenizer.json")cfg = ViuAIConfig( vocab_size=64003, context_length=2048, d_model=1280, n_layers=24, n_heads=20, n_kv_heads=4, ffn_hidden=3456, use_checkpoint=False)
model = ViuAI(cfg).to(device=device, dtype=dtype)ckpt = torch.load(ckpt_path, map_location=device, weights_only=False)sd = ckpt.get("model_state_dict", ckpt.get("model", ckpt))clean_sd = {k.replace("_orig_mod.", "").replace("module.", ""): v.to(dtype) for k, v in sd.items()}model.load_state_dict(clean_sd, strict=False)model.eval()
vram_mb = torch.cuda.memory_allocated() / (1024**2) if torch.cuda.is_available() else 0print(f"π ViuAI Sarus-500M (DPO) Loaded Successfully! (VRAM: {vram_mb:.1f} MB)")
# 4. Helper Function for Text Generationdef ask_sarus(prompt: str, max_tokens: int = 150, temperature: float = 0.3, top_p: float = 0.9): formatted = f"<|user|>\n{prompt.strip()}<|endofturn|>\n<|assistant|>\n" inp = torch.tensor([tok.encode(formatted).ids], device=device, dtype=torch.long) prompt_len = inp.shape[1] t0 = time.time() with torch.no_grad(): out = model.generate( inp, max_new_tokens=max_tokens, temperature=temperature, top_p=top_p, top_k=40, eos_token_id=64002, repetition_penalty=1.15 ) gen_time = max(0.01, time.time() - t0) gen_tokens = out[0][prompt_len:].tolist() if 64002 in gen_tokens: gen_tokens = gen_tokens[:gen_tokens.index(64002)] reply = tok.decode(gen_tokens).strip() speed = len(gen_tokens) / gen_time return reply, speed
# 5. Run 10-Domain Benchmark Suitebenchmark_prompts = [ ("Identity", "Who created you and what is your name?"), ("Competitor Deny", "Are you ChatGPT made by OpenAI?"), ("Indian History", "Who was the first Prime Minister of India?"), ("Scam Defense", "Someone asks for my UPI PIN to give me refund. Should I share it?"), ("Math Reasoning", "If a shirt costs 500 rupees and is on a 20% discount, what is the discount amount and the final price?"), ("Instruction Compliance", "Write an official leave request to my manager for 2 days due to fever. Exactly 2 sentences only."), ("Cooking Recipe", "What are the essential ingredients to make Indian Masala Chai?"), ("Python Coding", "Write a Python function to reverse a string and give an example."), ("Translation", "Translate to Hindi: 'Hard work and consistency always lead to success.'"), ("Hinglish Chat", "Bhai mera kal Python ka exam hai, mujhe bohot tension ho rahi hai.")]
print("\n" + "=" * 80)print("π RUNNING OFFICIAL DPO BENCHMARK SUITE (10 DOMAINS)")print("=" * 80)
for idx, (cat, q) in enumerate(benchmark_prompts, 1): ans, spd = ask_sarus(q, max_tokens=140) print(f"\n[{idx}/10] π Category: {cat}") print(f"π¬ User: {q}") print(f"π€ Sarus-500M (DPO): {ans}") print(f"β‘ Speed: {spd:.1f} tokens/sec") print("-" * 80)
print("\nπ Benchmark Completed! You can now chat using `ask_sarus('your prompt')`!")runners/KAGGLE_TEST_SARUS_DPO.txtAdded+146