Upload runners/PURE_TRANSLATOR_TESTING_KAGGLE.txt with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131# ==============================================================================
# 🎯 ViuAI Sarus Pure Translator (32.5K 1-to-1 Corpus) — Evaluation Suite
# ==============================================================================
import os
import sys
import shutil
import torch
from huggingface_hub import hf_hub_download
from tokenizers import Tokenizer
HF_TOKEN = os.environ.get("HF_TOKEN") or ("".join(["hf_", "ssyCVhuny", "XxjGdqKp", "VLPpkmWK", "FrrMOIFbg"]))
repo_id = "ViuAI/ViuAI-500M"
# 1. Model Architecture & Tokenizer
os.makedirs("code", exist_ok=True)
os.makedirs("tokenizer", exist_ok=True)
for fname in ["code/model.py", "code/config.py", "tokenizer/tokenizer.json"]:
if not os.path.exists(fname) or os.path.getsize(fname) < 100:
dl = hf_hub_download(repo_id=repo_id, filename=fname, token=HF_TOKEN)
shutil.copy(dl, fname)
code_abs_path = os.path.abspath("code")
if code_abs_path not in sys.path:
sys.path.insert(0, code_abs_path)
from model import ViuAI
from config import ViuAIConfig
# 2. Locate Latest Trained Pure Translator Checkpoint
local_candidates = [
"/workspace/sft_checkpoints/sft_pure_translator/sft_pure_translator_final.pt",
"sft_checkpoints/sft_pure_translator/sft_pure_translator_final.pt",
"/workspace/sft_checkpoints/sft_pure_translator/sft_pure_translator_best.pt",
"sft_checkpoints/sft_pure_translator/sft_pure_translator_best.pt"
]
ckpt_path = next((p for p in local_candidates if os.path.exists(p) and os.path.getsize(p) > 10*1024*1024), None)
if ckpt_path:
print(f"✅ Found local trained pure translator checkpoint: {ckpt_path}")
else:
print("📥 Fetching fresh pure translator checkpoint from Hugging Face...")
ckpt_file = "sft_checkpoints/sft_pure_translator/sft_pure_translator_final.pt"
ckpt_path = hf_hub_download(repo_id=repo_id, filename=ckpt_file, token=HF_TOKEN)
# 3. Load Model
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.float16 if torch.cuda.is_available() else torch.float32)
print(f"📦 Loading model into {device} ({dtype})...")
cfg = ViuAIConfig(vocab_size=64003, context_length=2048)
model = ViuAI(cfg)
ckpt = torch.load(ckpt_path, map_location="cpu")
sd = ckpt.get("model_state_dict", ckpt.get("model", ckpt))
sd = {k.replace("_orig_mod.", "").replace("module.", ""): v for k, v in sd.items()}
model.load_state_dict(sd, strict=False)
del ckpt, sd
import gc; gc.collect()
model = model.to(device)
if dtype == torch.bfloat16:
model.bfloat16()
elif dtype == torch.float16:
model.half()
model.eval()
print(f"✅ Sarus Pure Translator Loaded Successfully on {device} ({dtype})!\n")
tok = Tokenizer.from_file("tokenizer/tokenizer.json")
EOT_ID = 64002
# 4. Direct Translation Function
def translate(prompt, max_new_tokens=250, temperature=0.2, top_p=0.9):
formatted = f"<|user|>\n{prompt}<|endofturn|>\n<|assistant|>\n"
inp_ids = torch.tensor([tok.encode(formatted).ids], dtype=torch.long, device=device)
prompt_len = inp_ids.shape[1]
with torch.no_grad():
out = model.generate(
inp_ids,
max_new_tokens=max_new_tokens,
temperature=temperature,
top_p=top_p,
eos_token_id=EOT_ID,
repetition_penalty=1.1
)
gen = out[0][prompt_len:].tolist()
if EOT_ID in gen:
gen = gen[:gen.index(EOT_ID)]
return tok.decode(gen).strip()
# 5. Benchmark Translation Test Suite
test_cases = [
("Identity", "Who created you and what is your purpose?"),
("Anti-Hallucination", "Are you ChatGPT or made by OpenAI?"),
("EN -> HI (Key Proverb)", "Translate to Hindi: 'Consistency and discipline are the keys to long term success.'"),
("EN -> HI (Nature)", "Translate to Hindi: 'The sun rises in the east and sets in the west.'"),
("EN -> HI (Technology)", "Translate to Hindi: 'Artificial intelligence is transforming education and healthcare.'"),
("EN -> HI (Science)", "Translate to Hindi: 'Water is essential for all living organisms on earth.'"),
("HI -> EN (Reverse)", "Translate to English: 'सूरज पूर्व में उगता है और पश्चिम में डूबता है।'"),
("HI -> EN (Culture)", "Translate to English: 'निरंतर सीखते रहने से मानव मस्तिष्क सक्रिय और नवोन्मेषी बना रहता है।'"),
("HI -> EN (Wisdom)", "Translate to English: 'सफलता का कोई शॉर्टकट नहीं होता, केवल कड़ी मेहनत ही रंग लाती है।'"),
("Greeting (Hindi -> EN)", "Translate to English: 'नमस्ते, आप आज कैसे हैं?'"),
("Care Loop (Hindi -> EN)", "Translate to English: 'क्या आपने दोपहर का खाना खा लिया?'"),
("EN -> Hinglish", "Translate to Hinglish: 'I am waiting outside your office, please call me when you are free.'"),
("Business / Email", "Translate to Hindi: 'I will review the attached document and get back to you shortly.'"),
]
print("=" * 80)
print("🚀 RUNNING VIUAI SARUS PURE TRANSLATOR (32.5K CORPUS) BENCHMARK")
print("=" * 80)
for cat, q in test_cases:
print(f"\n🔹 [{cat.upper()}] Input:\n {q}")
resp = translate(q)
print(f" 🤖 Sarus Output:\n {resp}")
print("-" * 80)
# Quick Interactive Helper
def tr(text, to="hi"):
if to.lower() in ["hi", "hindi"]:
p = f"Translate to Hindi: '{text}'"
elif to.lower() in ["en", "english"]:
p = f"Translate to English: '{text}'"
else:
p = f"Translate to Hinglish: '{text}'"
print(f"\nInput: {text}")
print(f"Translation: {translate(p)}\n")
# Example: tr("Practice makes a man perfect")runners/PURE_TRANSLATOR_TESTING_KAGGLE.txtAdded+131