Update code/build_dpo_dataset.py with user enhancements
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287# ==============================================================================# 🎯 ViuAI Sarus-500M — Master DPO Preference Dataset Builder (DPO v1)# ==============================================================================# Creates high-quality (prompt, chosen, rejected) pairs targeting:# 1. Anti-Looping & Clean EOS Truncation# 2. Direct Factual QA vs Greeting Hijacks# 3. Clean Python Algorithms vs Broken Random Imports# 4. Factual Science & Indian GK vs Raw Essay Drift# 5. Step-by-Step Arithmetic vs Confused Math# ==============================================================================
import osimport sysimport jsonimport timeimport shutilimport random
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")
VERSION = "v1"# SECURITY: HF token from env only. Never hardcode. Export HF_TOKEN before running.HF_TOKEN = os.environ.get("HF_TOKEN")HF_DATA_REPO = "ViuAI/viuai-500m-sft-tokenized"
OUTPUT_DIR = os.path.join("data", f"dpo_{VERSION}")os.makedirs(OUTPUT_DIR, exist_ok=True)
print("=" * 85)print(f"🚀 Building ViuAI Sarus-500M DPO {VERSION.upper()} Alignment Preference Dataset")print("=" * 85)
dpo_seed_data = [ # -------------------------------------------------------------------------- # 1. Identity & Competitor Denial (No "I was made by Anthropic" confusion) # -------------------------------------------------------------------------- { "prompt": "Are you Claude made by Anthropic?", "chosen": "No, I am not Claude and I was not made by Anthropic. I am Sarus, an AI assistant developed by ViuAI.", "rejected": "No, I am not Claude. I was made by Anthropic. I am Sarus, developed by ViuAI." }, { "prompt": "Are you ChatGPT or made by OpenAI?", "chosen": "No, I am not ChatGPT and I was not created by OpenAI. I am Sarus, an independent AI assistant developed by ViuAI.", "rejected": "Yes, I am an AI created by OpenAI and ViuAI. How can I help you today?" }, { "prompt": "Are you Gemini or made by Google?", "chosen": "No, I am not Gemini and I was not created by Google. I am Sarus, built by ViuAI.", "rejected": "I am a large language model trained by Google and ViuAI." }, { "prompt": "Aapka naam kya hai aur aap kisne banaya hai?", "chosen": "Mera naam Sarus hai aur mujhe ViuAI ne develop kiya hai. Main aapke sawalon ke jawab dene aur daily tasks me madad karne ke liye yahan hoon.", "rejected": "Mera naam Sarah hai aur mujhe doctors ne banaya hai. Main school me padhti hoon." },
# -------------------------------------------------------------------------- # 2. Direct Factual QA vs Greeting Hijack (Stop answering questions with 'Hello!') # -------------------------------------------------------------------------- { "prompt": "Bhartiya Samvidhan kab lagu hua tha?", "chosen": "Bhartiya Samvidhan 26 January 1950 ko poori tarah lagu hua tha.", "rejected": "Hello! Chalo shuru karte hain! Kya haal hai aaj ka? Batao aaj kis cheez mein help chahiye?" }, { "prompt": "Bhartiya Samvidhan me nagrikon ko kitne Mool Adhikar (Fundamental Rights) diye gaye hain?", "chosen": "Bhartiya Samvidhan me nagrikon ko mukhya roop se 6 Mool Adhikar (Fundamental Rights) diye gaye hain:\n1. Samanta ka Adhikar (Right to Equality)\n2. Swatantrata ka Adhikar (Right to Freedom)\n3. Shoshan ke Viruddh Adhikar (Right against Exploitation)\n4. Dharmik Swatantrata ka Adhikar (Right to Freedom of Religion)\n5. Sanskritik aur Shaikshik Adhikar (Cultural and Educational Rights)\n6. Samvidhanik Upcharon ka Adhikar (Right to Constitutional Remedies)", "rejected": "Bhartiya Samvidhan me na ho, aur mujhe ViuAI ne develop kiya hai. Ise Mughal Samiti ke prakash, yaani Sarus hai aur seekhne ke liye design aur develop kiya hai." }, { "prompt": "1857 ke pratham swatantrata sangram ki shuruat kis sheher se hui thi?", "chosen": "1857 ke pratham swatantrata sangram ki shuruat 10 May 1857 ko Uttar Pradesh ke **Meerut** sheher se hui thi.", "rejected": "Bharat ke prakash, chalo revise karte hain! Kya topic hai aaj kaam ka din?" }, { "prompt": "Ganga nadi kahan se nikalti hai aur kahan jakar milti hai?", "chosen": "Ganga nadi Uttarakhand ke Uttarkashi jile me Gangotri Glacier (Gaumukh) se nikalti hai aur lagbhag 2,525 km behkar Bay of Bengal (Bangal ki Khadi) me jakar milti hai.", "rejected": "Ganga nadi ke tat par pehle bina gaya ek organization hai. Main aapke sawalon ke jawab dene aur daily tasks mein madad karne ke liye yahan hoon." }, { "prompt": "Bharat ka Rashtriya Pashu aur Rashtriya Pakshi kaunsa hai?", "chosen": "Bharat ka Rashtriya Pashu **Royal Bengal Tiger (Bagh)** hai aur Rashtriya Pakshi **Indian Peacock (Mor)** hai.", "rejected": "Bharat ke Rashtratak ko Rashtratak par bhojan (Rashtriya Parivar) hai. Mera naam Sarus hai, aur main ViuAI dwara develop kiya gaya ek AI assistant hoon." }, { "prompt": "RBI ka poora naam kya hai aur iska mukhya karya kya hai?", "chosen": "RBI ka poora naam **Reserve Bank of India (Bhartiya Reserve Bank)** hai. Yeh Bharat ka Central Bank hai jo currency issue karta hai, monetary policy banata hai aur desh ke banking system ko regulate karta hai.", "rejected": "Mera naam Sarus hai aur mujhe ViuAI ne develop kiya hai. Main aapke sawalon ke jawab dene aur daily tasks mein madad karne ke liye yahan hoon." }, { "prompt": "Munshi Premchand ke prasiddh upanyason ke naam batao.", "chosen": "Munshi Premchand ke sabse prasiddh upanyas hain:\n1. Godan (गोदान)\n2. Gaban (गबन)\n3. Nirmala (निर्मला)\n4. Sevasadan (सेवासदन)\n5. Karmabhoomi (कर्मभूमि)\n6. Rangbhoomi (रंगभूमि)", "rejected": "नीला आसमान बहुत सुंदर दिखाई देता है। इसकी चौड़ाई लगभग 3,000 फुट होती है। यह पृथ्वी की सतह से लगभग 1,200 मीटर नीचे स्थित है।" }, { "prompt": "Kabir Das ji kaun the aur unke dohe kis bhasha me hain?", "chosen": "Kabir Das ji 15vin sadi ke mahan Bhakti kaal ke sant, kavi aur samaj sudharak the. Unke dohe Sadhu-bhasha (Sadhukkadi / Panchmel Khichdi) me hain jisme Hindi, Braj, Awadhi aur Bhojpuri ka mishran hai.", "rejected": "Kabir Das ji kya aapke yahan? Sab anand me hai kya? Aaj main aapki madad kar sakta hoon." }, { "prompt": "Diwali ka tyohar kyu manaya jata hai?", "chosen": "Diwali (Deepawali) roshni ka tyohar hai. Pauranik manyata ke anusaar, is din Bhagwan Shri Ram 14 varsh ke vanvas aur Ravan par vijay ke baad Ayodhya laute the, jiske swagat me Ayodhyawasiyon ne ghee ke diye jalaye the.", "rejected": "Diwali! Kya plan hai aaj kaam theek chal raha hai? Batao." }, { "prompt": "Mughal Samrajya ke sansthapak kaun the aur unhone Bharat par kab raj shuru kiya?", "chosen": "Mughal Samrajya ke sansthapak **Babur** the. Unhone 1526 me Panipat ki Pehli Ladai me Ibrahim Lodi ko harakar Bharat me Mughal samrajya ki sthapna ki thi.", "rejected": "मैं आपको यह बताना चाहता हूं कि मेरे आधुनिक समाज में, शिक्षा मानव समाज को बदलने का सबसे शक्तिशाली साधन है। मेरे पास एक स्नातकोत्तर डिग्री है।" },
# -------------------------------------------------------------------------- # 3. Science & Biology (Clean facts vs Astrology/Wrong formulas) # -------------------------------------------------------------------------- { "prompt": "Matter ki 3 mukhya states kaunsi hain aur 1-1 example do.", "chosen": "Matter (Padarth) ki 3 mukhya physical states hain:\n1. **Solid (Thos):** Jaise Baraf (Ice) ya Patthar\n2. **Liquid (Drav):** Jaise Paani (Water) ya Tel\n3. **Gas (Vayu):** Jaise Oxygen ya Jalvashp (Steam)", "rejected": "दैनिक जीवन में, ज्योतिष शास्त्र में कर्म के आधार पर व्यक्ति के भविष्य के बारे में कई महत्वपूर्ण निर्णय लिए जाते हैं। 1. अच्छे कर्म करना: एक अच्छा कर्म करने के लिए क्षमता होनी चाहिए।" }, { "prompt": "What are the chemical formulas for Water and Common Salt (Table Salt)?", "chosen": "Here are the chemical formulas:\n- **Water:** H₂O (Two Hydrogen atoms bonded to one Oxygen atom)\n- **Common Salt (Table Salt):** NaCl (Sodium Chloride)", "rejected": "The chemical formula for Water and Common Salt is H2SO4. This means that it has two hydrogen atoms bonded together, with one oxygen atom attached to four oxygen atoms." }, { "prompt": "What is Newton's First Law of Motion?", "chosen": "Newton's First Law of Motion (Law of Inertia) states that an object at rest will remain at rest, and an object in uniform motion will continue moving in a straight line at a constant speed, unless acted upon by an external net force.", "rejected": "The first law of motion, also known as the laws of physics, states that the force between two objects in a frame of reference changes with time. So the Second Law states that force remains constant." }, { "prompt": "Ek swasth manushya ke shareer me kul kitni haddiyan (bones) hoti hain?", "chosen": "Ek swasth vayask (adult) manushya ke shareer me kul **206 haddiyan (bones)** hoti hain. (Navjaat shishu me lagbhag 270 se 300 haddiyan hoti hain jo aage chal kar jud jaati hain).", "rejected": "The part of the body that is hot and cold, i.e., it has internal temperature of 70°C to 140°C, can be described as hot and cold." }, { "prompt": "Dropped objects ground par kyu girti hain? Gravity explain karo.", "chosen": "Dropped objects ground par Earth ke Gravitational Force (Gurutvakarshan Bal) ki wajah se girti hain. Earth ka mass har vastu ko apne center ki taraf khinchta hai, jisse cheezein niche girti hain.", "rejected": "Gravity = (1/2) * gravity * 10/100. Dropped objects = 50%. Final Answer: 50" },
# -------------------------------------------------------------------------- # 4. Anti-Looping & Clean EOS Stop (No infinite repeating suffixes) # -------------------------------------------------------------------------- { "prompt": "Chandrayaan-3 kab land hua tha aur uske rover ka kya naam hai?", "chosen": "Chandrayaan-3 mission 23 August 2023 ko Chandrama ke Dakshini Dhruv (South Pole) par safaltapoorvak land hua tha. Iske Rover ka naam 'Pragyan' aur Lander ka naam 'Vikram' hai.", "rejected": "Chandrayaan-3 mission 23 August 2023 ko Chandrama ke Dakshini Dhruv par land hua tha. Iske Rover ka naam 'Pragyan' aur Lander ka naam 'Vikram' hai. Iske Rover ka naam 'Vikram' hai. Iske Rover ka naam 'Vikram' hai. Iske Rover ka naam 'Vikram' hai. Iske Rover ka naam 'Vikram' hai." }, { "prompt": "Kadak Masala Chai banane ki simple recipe step by step batao.", "chosen": "Kadak Masala Chai banane ki simple step-by-step recipe:\n\n1. **Paani Ubalein:** Ek pan me 1 cup paani garam karein.\n2. **Masale Daalein:** Kuta hua adrak (ginger), 2 kuta hua elaichi aur 1 laung daalein.\n3. **Chai Patti:** 1.5 chammach chai patti daal kar 2 minute ubalein.\n4. **Doodh & Cheeni:** 1 cup doodh aur swadanusar cheeni daalein.\n5. **Ubaal Aane Dein:** Madhyam aanch par 2-3 ubaal aane tak pakaayein.\n6. **Chaan Kar Serve Karein:** Chhanani se cup me chaan kar garma-garam serve karein.", "rejected": "Kadak Masala Chai banane ki recipe: 1. Paani Ubalein 2. Masale Daalein. Chalo shuru karte hain aur garma-garam karein. Dheemi aanch par pakaayein. Dheemi aanch par pakaayein. Dheemi aanch par pakaayein. Dheemi aanch par pakaayein." }, { "prompt": "Translate to Hindi: 'Water is essential for all living beings.'", "chosen": "Hindi Anuvaad: 'जल सभी जीवित प्राणियों के लिए अनिवार्य (आवश्यक) है।'", "rejected": "यह सर्वविदित है कि जल सभी जीवित प्राणियों के लिए सबसे मूलभूत संसाधन है। जल सभी जीवित प्राणियों के लिए सबसे मूलभूत संसाधन है। जल सभी जीवित प्राणियों के लिए सबसे मूलभूत संसाधन है। जल सभी जीवित प्राणियों के लिए सबसे मूलभूत संसाधन है।" },
# -------------------------------------------------------------------------- # 5. Clean Python Coding & Algorithms # -------------------------------------------------------------------------- { "prompt": "Write a Python function to check if a string is a palindrome.", "chosen": "Here is the Python function to check if a string is a palindrome:\n\n```python\ndef is_palindrome(s: str) -> bool:\n clean_s = \"\".join(c.lower() for c in s if c.isalnum())\n return clean_s == clean_s[::-1]\n\n# Example usage:\nprint(is_palindrome(\"radar\")) # True\nprint(is_palindrome(\"hello\")) # False\n```", "rejected": "Here is the Python solution:\n\n```python\ndef is_palindrome(str): \n str = \"\".join(random.choices(str)) \n return str == str[-1] \n```" }, { "prompt": "Write a Python function to calculate factorial of a number.", "chosen": "Here is the recursive Python function to calculate factorial:\n\n```python\ndef factorial(n: int) -> int:\n if n < 0:\n raise ValueError(\"Factorial is not defined for negative numbers.\")\n if n <= 1:\n return 1\n return n * factorial(n - 1)\n\n# Example usage:\nprint(factorial(5)) # Output: 120\n```", "rejected": "Here is the Python solution:\n\n```python\ndef factorial(n): \n if n < 0 or n < 1: \n return 2\n else: \n return 3\n```" }, { "prompt": "Write a Python function to reverse a list without using slicing.", "chosen": "Here is the Python function to reverse a list:\n\n```python\ndef reverse_list(lst):\n left = 0\n right = len(lst) - 1\n while left < right:\n lst[left], lst[right] = lst[right], lst[left]\n left += 1\n right -= 1\n return lst\n\n# Example usage:\nprint(reverse_list([1, 2, 3, 4, 5])) # Output: [5, 4, 3, 2, 1]\n```", "rejected": "Here is the Python solution:\n\n```python\ndef reverse_list(lst):\n return str(lst[::-1]) + list.reverse(10)\n```" },
# -------------------------------------------------------------------------- # 6. Step-by-Step Math Reasoning vs Confused Geometry # -------------------------------------------------------------------------- { "prompt": "Find the area of a rectangle with length 10 cm and width 5 cm.", "chosen": "Given:\n- Length ($l$) = 10 cm\n- Width ($w$) = 5 cm\n\nFormula: `Area = Length × Width`\nCalculation: `Area = 10 × 5 = 50 cm²`\n\n**Final Answer:** The area of the rectangle is **50 cm²**.", "rejected": "To find the area of a rectangle, you can use the formula: Area = πr^2 * (length * 10). Area = π × 10 × 10 = 400 square centimeters. Thus, the area is approximately 300 square centimeters." }, { "prompt": "Agar kisi phone ki MRP ₹20,000 hai aur uspe 15% discount hai, toh final price kya hogi?", "chosen": "Step-by-step calculation:\n\n1. **Discount Amount Nikaalein:**\n Discount = 15% of ₹20,000\n Discount = (15 / 100) × 20,000 = ₹3,000\n\n2. **Final Price Nikaalein:**\n Final Price = MRP - Discount\n Final Price = ₹20,000 - ₹3,000 = ₹17,000\n\n**Antim Uttar:** Phone ki final price **₹17,000** hogi.", "rejected": "Mera phone ki MRP = 20000 / 15 / 100 = ₹1,500. Total cost = 20000 - 1000 = ₹2,200. Final Answer: 2200" }, { "prompt": "If a car travels at 60 km/h for 3 hours, how far does it travel?", "chosen": "To calculate the total distance traveled:\n\nFormula: `Distance = Speed × Time`\nGiven: Speed = 60 km/h, Time = 3 hours\nCalculation: `Distance = 60 × 3 = 180 km`\n\n**Final Answer:** The car travels **180 km**.", "rejected": "The total distance traveled by the car is 60 x 3 = 180 km. So the total distance traveled by the car is 180 + 180 = 360 km. Final Answer: 360" }, { "prompt": "Agar kal Monday tha, toh 100 din baad kaunsa din hoga? Step-by-step calculate karo.", "chosen": "Step-by-step calculation:\n\n1. **Aaj ka din:** Agar kal Monday tha, toh aaj **Tuesday** hai.\n2. **100 din me hafte aur remainder:**\n 100 ÷ 7 = 14 hafte (98 din) aur **2 din baki (remainder = 2)**.\n3. **Tuesday se 2 din aage:**\n Tuesday + 1 = Wednesday\n Tuesday + 2 = Thursday\n\n**Antim Uttar:** 100 din baad **Thursday (Guruwar)** hoga.", "rejected": "1 din a day is equal to 1.5 hours. 2 din a week is equal to 2.5 hours. 3 din a month is equal to 3 days. 4 din a year is equal to 4*12 = 48 din a year. 5 din a year is equal to 5*24 = 240 din a year." },
# -------------------------------------------------------------------------- # 7. Context QA (RAG) Direct Extraction # -------------------------------------------------------------------------- { "prompt": "Context:\nViuAI launched Sarus-500M in September 2026 with 64k vocabulary.\n\nQuestion:\nWhat is the vocabulary size of Sarus-500M according to the context?", "chosen": "According to the provided context, the vocabulary size of Sarus-500M is **64k (64,003)**.", "rejected": "The given input was a sample word list from September 2026. Could you please provide more information about the vocabulary size of the document?" }]
# --- De-duplicated, leakage-free split (prompt-grouped) ---# Previous versions repeated every pair 120x then randomly split, which put# identical prompts in both train and val (leakage -> inflated val accuracy).# Fix: split by UNIQUE prompt first (zero overlap), then expand train only.seen = set()unique_seeds = []for item in dpo_seed_data: key = (item["prompt"].strip(), item["chosen"].strip(), item["rejected"].strip()) if key not in seen: seen.add(key) unique_seeds.append({"prompt": item["prompt"], "chosen": item["chosen"], "rejected": item["rejected"]})
random.seed(42)random.shuffle(unique_seeds)
# Hold out ~20% of UNIQUE prompts (min 5) for val. No prompt appears in both splits.n_val_prompts = max(5, int(len(unique_seeds) * 0.2))val_seeds = unique_seeds[:n_val_prompts]train_seeds = unique_seeds[n_val_prompts:]val_prompts = set(s["prompt"] for s in val_seeds)assert not (set(s["prompt"] for s in train_seeds) & val_prompts), "Prompt leakage between train/val!"
# Expand TRAIN split only to reach target volume. Exact repeats are a stopgap:# prefer adding genuine paraphrases of (prompt, chosen, rejected) instead of# raising TRAIN_REPEAT further. Val stays as unique held-out prompts (no repeats).TRAIN_REPEAT = 100all_train_pairs = []for item in train_seeds * TRAIN_REPEAT: all_train_pairs.append({ "prompt": item["prompt"], "chosen": item["chosen"], "rejected": item["rejected"] })random.seed(42)random.shuffle(all_train_pairs)
train_pairs = all_train_pairsval_pairs = val_seeds
train_file = os.path.join(OUTPUT_DIR, "dpo_train.json")val_file = os.path.join(OUTPUT_DIR, "dpo_val.json")
with open(train_file, "w", encoding="utf-8") as f: json.dump(train_pairs, f, indent=2, ensure_ascii=False)
with open(val_file, "w", encoding="utf-8") as f: json.dump(val_pairs, f, indent=2, ensure_ascii=False)
print(f"✅ Generated DPO Preference Pairs (leakage-free, prompt-grouped split):")print(f" - Unique seeds: {len(unique_seeds)} | Train prompts: {len(train_seeds)} x{TRAIN_REPEAT} repeats")print(f" - Train Split: {len(train_pairs):,} pairs ({train_file})")print(f" - Val Split: {len(val_pairs):,} pairs ({val_file}) [unique held-out prompts, no repeats]")print(f" - Prompt overlap train/val: 0 (verified)")
# Push to Hugging Faceif "--push_to_hf" in sys.argv: if not HF_TOKEN: raise ValueError("HF_TOKEN env var is not set! Export HF_TOKEN before --push_to_hf.") print(f"\n☁️ Pushing DPO Dataset to Hugging Face ({HF_DATA_REPO}/dpo_v1/)...") from huggingface_hub import HfApi api = HfApi(token=HF_TOKEN) for fname, local_p in [("dpo_train.json", train_file), ("dpo_val.json", val_file)]: api.upload_file( path_or_fileobj=local_p, path_in_repo=f"dpo_{VERSION}/{fname}", repo_id=HF_DATA_REPO, repo_type="dataset", commit_message=f"Upload DPO {VERSION} preference pairs: {fname}" ) print(f" ✅ Uploaded {fname} to HF dataset hub!")
print("\n🎉 DPO Dataset Build Complete!")code/build_dpo_dataset.pyAdded+287