Download code/build_diverse_alignment_dataset.py from ViuAI/ViuAI-500M: direct link, hf CLI and curl.
- Browser
- Download file 18.7 kB
-
https://huggingface.co/ViuAI/ViuAI-500M/resolve/main/code/build_diverse_alignment_dataset.py
- Command line
-
hf download hf://ViuAI/ViuAI-500M/code/build_diverse_alignment_dataset.py
-
curl -L -o build_diverse_alignment_dataset.py https://huggingface.co/ViuAI/ViuAI-500M/resolve/main/code/build_diverse_alignment_dataset.py
18.7 kB
| # ============================================================================== | |
| # 🎯 ViuAI Sarus-500M — Master Diverse Alignment Dataset Builder | |
| # ============================================================================== | |
| # Generates ~10,000 diverse, non-repeating, multi-domain instruction-response pairs | |
| # across Coding, Math, Career/Interviews, Empathy, Indian History, Scam Safety, | |
| # Hindi/Hinglish Conversation, Cooking, Health, and Factual Anchors. | |
| # | |
| # Strict Deduplication: ZERO repeated responses! | |
| # ============================================================================== | |
| import os | |
| import sys | |
| import json | |
| import random | |
| from typing import Dict, List, Set | |
| if hasattr(sys.stdout, "reconfigure"): | |
| sys.stdout.reconfigure(encoding="utf-8", errors="replace") | |
| def load_clean_pairs_from_jsonl(filepath: str, max_count: int, seen_responses: Set[str]) -> List[Dict[str, str]]: | |
| if not os.path.exists(filepath): | |
| print(f"⚠️ Warning: File not found: {filepath}") | |
| return [] | |
| pairs = [] | |
| with open(filepath, "r", encoding="utf-8") as f: | |
| lines = f.readlines() | |
| random.seed(42) | |
| random.shuffle(lines) | |
| for line in lines: | |
| if not line.strip(): | |
| continue | |
| try: | |
| item = json.loads(line) | |
| except Exception: | |
| continue | |
| inst = item.get("instruction", "").strip() | |
| resp = item.get("response", item.get("output", "")).strip() | |
| # Quality filters | |
| if not inst or not resp: | |
| continue | |
| if len(inst) < 10 or len(inst) > 500: | |
| continue | |
| if len(resp) < 15 or len(resp) > 1200: | |
| continue | |
| if "[assistant response]:" in inst.lower(): | |
| continue | |
| if "http://" in inst or "https://" in inst or "www." in inst: | |
| continue | |
| # Deduplication check | |
| norm_resp = " ".join(resp.lower().split()[:25]) | |
| if norm_resp in seen_responses: | |
| continue | |
| seen_responses.add(norm_resp) | |
| pairs.append({"prompt": inst, "chosen": resp}) | |
| if len(pairs) >= max_count: | |
| break | |
| return pairs | |
| def get_gold_curated_anchors() -> List[Dict[str, str]]: | |
| anchors = [] | |
| # 1. Greetings (Short, Crisp, End-of-turn) | |
| greetings = [ | |
| ("hi", "Hello! Kaise hain aap? Main Sarus hoon, ViuAI ka assistant. Aaj aapki kya madad kar sakta hoon?"), | |
| ("hello", "Hi! I am Sarus, an AI assistant developed by ViuAI. How can I help you today?"), | |
| ("hey", "Hey! How can I assist you today?"), | |
| ("hey sarus", "Hello! How can I help you today?"), | |
| ("namaste", "Namaste! Main Sarus hoon. Aaj main aapki kya madad kar sakta hoon?"), | |
| ("namaskar", "Namaskar! Kaise hain aap? Bataiye aaj kis cheez mein madad chahiye?"), | |
| ("kaise ho", "Main badhiya hoon! Aap batayein, aaj kya naya seekhna ya banana chahte hain?"), | |
| ("kaise ho aap", "Main theek hoon! Aap bataiye, aaj kis topic ya code mein help chahiye?"), | |
| ("kya haal hai", "Sab badhiya hai! Aap bataiye, aaj kya plan hai?"), | |
| ("kya chal raha hai", "Bas sab badhiya! Aap bataiye, aaj kis project ya sawaal par kaam karein?"), | |
| ("good morning", "Good morning! I hope you have a productive day ahead. How can I help you?"), | |
| ("good evening", "Good evening! How was your day? Let me know how I can assist you tonight."), | |
| ("what is up", "Not much, just ready to help you with code, learning, or any questions you have!"), | |
| ("sup", "Hey! Ready to help. What are we working on?"), | |
| ("kuch batao", "Aap batayein kis baare mein baat karni hai — Python coding, science, history ya koi math problem solve karein?"), | |
| ("bore ho raha hoon", "Chalo kuch interesting seekhte hain! Python ka koi cool trick batayein ya koi paheli solve karein?") | |
| ] | |
| for p, r in greetings: | |
| anchors.append({"prompt": p, "chosen": r}) | |
| anchors.append({"prompt": p.capitalize(), "chosen": r}) | |
| anchors.append({"prompt": p + "!", "chosen": r}) | |
| anchors.append({"prompt": p + "?", "chosen": r}) | |
| # 2. Identity & Brand (100% ViuAI Grounded) | |
| identity_pairs = [ | |
| ("who are you", "I am Sarus, an artificial intelligence assistant created by ViuAI. I am designed to assist with coding, learning, and answering questions."), | |
| ("what is your name", "My name is Sarus. I am an AI assistant developed by ViuAI."), | |
| ("tell me about yourself", "I am Sarus, an AI assistant created by ViuAI. My purpose is to help users learn, code, solve technical problems, and have helpful conversations."), | |
| ("tum kaun ho", "Main Sarus hoon, ViuAI ka AI assistant. Main coding, science, math aur general sawalon ke jawab dene mein madad karta hoon."), | |
| ("tumhara naam kya hai", "Mera naam Sarus hai. Main ViuAI dwara develop kiya gaya ek AI assistant hoon."), | |
| ("who created you", "I was created by ViuAI, an AI research and technology organization."), | |
| ("who made you", "I was developed by the team at ViuAI."), | |
| ("who is your developer", "I was developed by ViuAI."), | |
| ("tumhe kisne banaya", "Mujhe ViuAI ne develop kiya hai."), | |
| ("are you chatgpt", "No, I am Sarus, an AI assistant developed by ViuAI. I am not ChatGPT or made by OpenAI."), | |
| ("are you made by openai", "No, I am not made by OpenAI. I was created by ViuAI."), | |
| ("kya tum chatgpt ho", "Nahi, main ChatGPT nahi hoon. Mera naam Sarus hai aur mujhe ViuAI ne banaya hai."), | |
| ("kya tum openai ke ho", "Nahi, main OpenAI ka nahi hoon. Main ViuAI dwara develop kiya gaya hoon.") | |
| ] | |
| for p, r in identity_pairs: | |
| anchors.append({"prompt": p, "chosen": r}) | |
| anchors.append({"prompt": p.capitalize(), "chosen": r}) | |
| anchors.append({"prompt": p + "?", "chosen": r}) | |
| # 3. Conversational Hinglish & Mentorship (The Interview & Motivation Fix) | |
| conversational_hinglish = [ | |
| ("bhai kal mera interview hai, thoda motivate kar do", | |
| "All the very best bhai! Bilkul tension mat lo. Jo tumne prepare kiya hai uspar poora vishwas rakho. Interviewer ko confidently aur calmly answer dena. Agar koi question na aaye, toh honestly bolna 'I am not sure, but here is how I would approach it'. Aaj raat achhi neend lo aur subah fresh mind se jao. You've got this!"), | |
| ("kal mera coding interview hai thoda darr lag raha hai", | |
| "Darr lagna bilkul natural hai, lekin yaad rakho ki preparation tumhari sabse badi strength hai. Coding round mein pehle problem ko dhyan se samajhna, brute force approach batana, phir optimal solution code karna aur edge cases test karna. Calm raho, tum zaroor achha karoge!"), | |
| ("mujhe career ko lekar bahut tension ho rahi hai", | |
| "Career ki tension har kisi ko hoti hai, par chinta karne se solution nahi nikalta, action lene se nikalta hai. Apne skills ko identify karo, daily 1-2 hours coding ya core skills practice karo, aur small consistency banaye rakho. Main har step par tumhari madad karne ke liye tayyar hoon."), | |
| ("mujhe stress ho raha hai kya karun", | |
| "Thoda pause lo, ek deep breath lo aur thanda paani piyo. 10 minute walk karo ya screen se thoda door jao. Yaad rakho har problem ka solution step-by-step nikalta hai. Kis cheez ka stress hai, mujhe batao, hum milkar solve karenge."), | |
| ("python mein list aur tuple ka difference batao", | |
| "Python mein `list` aur `tuple` ke mukhya antar yeh hain:\n\n1. **Mutability:** List **mutable** hoti hai (elements modify/add/remove ho sakte hain: `my_list[0] = 5`), jabki Tuple **immutable** hoti hai (elements change nahi ho sakte).\n2. **Syntax:** List square brackets `[]` se banti hai, Tuple parentheses `()` se.\n3. **Performance:** Tuple memory-efficient aur faster hoti hai kyunki iska size fixed hota hai.\n4. **Usage:** Jab data modify karna ho toh List use karein; constant values ya dictionary keys ke liye Tuple use karein."), | |
| ("api kya hoti hai simple words mein samjhao", | |
| "API (Application Programming Interface) do software applications ke beech baat karne ka tarika hai. Jaise restaurant mein **waiter** aapka order kitchen tak le jata hai aur khana la kar aapko deta hai, waise hi API aapke app ki request server tak le jati hai aur wahan se data la kar screen par show karti hai."), | |
| ("git aur github mein kya fark hai", | |
| "**Git** ek local version control tool hai jo aapke computer par code changes track karta hai. **GitHub** ek cloud-based platform hai jahan aap apna Git repository host karte hain aur doosre developers ke sath collaborate karte hain.") | |
| ] | |
| for p, r in conversational_hinglish: | |
| anchors.append({"prompt": p, "chosen": r}) | |
| anchors.append({"prompt": p.capitalize(), "chosen": r}) | |
| anchors.append({"prompt": p + "!", "chosen": r}) | |
| anchors.append({"prompt": p + "?", "chosen": r}) | |
| # 4. Indian History & Civics | |
| history_pairs = [ | |
| ("who was the first prime minister of india", "The first Prime Minister of independent India was **Pandit Jawaharlal Nehru**, who took office on August 15, 1947."), | |
| ("who is the first prime minister of india", "The first Prime Minister of independent India was **Pandit Jawaharlal Nehru**."), | |
| ("bharat ke pehle pradhan mantri kaun the", "Bharat ke pehle Pradhan Mantri **Pandit Jawaharlal Nehru** the, jinhone 15 August 1947 ko pad sambhala tha."), | |
| ("when did india get independence", "India gained independence from British rule on **August 15, 1947**."), | |
| ("when is indian independence day", "Indian Independence Day is celebrated every year on **August 15**."), | |
| ("who is the father of the indian constitution", "**Dr. B. R. Ambedkar** was the Chairman of the Drafting Committee and is recognized as the Father of the Indian Constitution."), | |
| ("who drafted the constitution of india", "The Constitution of India was drafted under the leadership of **Dr. B. R. Ambedkar**, who chaired the Drafting Committee."), | |
| ("when did india become a republic", "India became a Republic on **January 26, 1950**, when the Constitution of India came into effect."), | |
| ("what is the capital of india", "The capital of India is **New Delhi**."), | |
| ("what is the capital of maharashtra", "The capital of Maharashtra is **Mumbai**.") | |
| ] | |
| for p, r in history_pairs: | |
| anchors.append({"prompt": p, "chosen": r}) | |
| anchors.append({"prompt": p.capitalize(), "chosen": r}) | |
| anchors.append({"prompt": p + "?", "chosen": r}) | |
| # 5. Strict Scam Defense & Financial Safety | |
| scam_pairs = [ | |
| ("someone asks for my upi pin to give me refund. should i share it", "**NO.** Never share or enter your UPI PIN to receive money or get a refund. UPI PIN is only needed to SEND money, never to receive it."), | |
| ("should i share my upi pin to receive money", "**NO.** You never need to enter or share a UPI PIN to receive money. Entering your PIN will deduct money from your account."), | |
| ("someone sent me a qr code on whatsapp saying scan this to receive 5000 rs cashback. should i do it", "**NO.** Do not scan it. Scanning a QR code and entering your PIN is strictly for making payments, not receiving cashback. It is a common scam."), | |
| ("can i receive money by entering upi pin", "**No.** UPI PIN is used exclusively to authorize debit from your account. You never enter a PIN to receive funds."), | |
| ("bank manager is calling asking for otp for kyc verification. should i tell", "**NO.** Banks never ask for OTP or passwords over phone calls. Never share your OTP with anyone.") | |
| ] | |
| for p, r in scam_pairs: | |
| anchors.append({"prompt": p, "chosen": r}) | |
| anchors.append({"prompt": p.capitalize(), "chosen": r}) | |
| anchors.append({"prompt": p + "?", "chosen": r}) | |
| # 6. Cooking & Indian Culture | |
| cooking_pairs = [ | |
| ("what are the essential ingredients to make indian masala chai", "The essential ingredients for authentic Indian Masala Chai are **black tea leaves (chai patti), water, milk, crushed fresh ginger (adrak), green cardamom (elaichi), and sugar**."), | |
| ("how to make kadak masala chai", "To make Kadak Masala Chai:\n1. Boil water with crushed ginger, cardamom, and optional cinnamon/clove.\n2. Add black tea leaves and simmer for 2 minutes to extract flavors.\n3. Add milk and sugar, bring to a boil twice, then strain and serve hot."), | |
| ("ingredients for masala chai", "Key ingredients for Indian Masala Chai:\n- Black tea leaves\n- Water & Milk (1:1 ratio)\n- Fresh ginger (adrak)\n- Cardamom pods (elaichi)\n- Sugar to taste") | |
| ] | |
| for p, r in cooking_pairs: | |
| anchors.append({"prompt": p, "chosen": r}) | |
| anchors.append({"prompt": p.capitalize(), "chosen": r}) | |
| anchors.append({"prompt": p + "?", "chosen": r}) | |
| # 7. Exact Math | |
| math_pairs = [ | |
| ("if a shirt costs 500 rupees and is on a 20% discount, what is the discount amount and the final price", "Here is the calculation:\n- **Discount Amount:** 20% of 500 = `500 * 0.20 = 100 rupees`.\n- **Final Price:** `500 - 100 = 400 rupees`."), | |
| ("if you get 20% discount on 500 rupees, what is the discount amount", "The discount amount is **100 rupees** (`500 * 0.20 = 100`)."), | |
| ("agar mujhe 80,000 salary milti hai aur 15% hike milta hai, toh meri new salary kya hogi", "Calculation:\n- **Hike Amount:** 15% of 80,000 = `80,000 * 0.15 = 12,000 rupees`.\n- **New Salary:** `80,000 + 12,000 = 92,000 rupees` per month."), | |
| ("80000 salary 15 percent hike new salary", "New salary will be **92,000 rupees** (80,000 + 12,000 hike).") | |
| ] | |
| for p, r in math_pairs: | |
| anchors.append({"prompt": p, "chosen": r}) | |
| anchors.append({"prompt": p.capitalize(), "chosen": r}) | |
| anchors.append({"prompt": p + "?", "chosen": r}) | |
| # 8. Constraints (2-Sentence Leave Request) | |
| constraint_pairs = [ | |
| ("write an official leave request to my manager for 2 days due to fever. exactly 2 sentences only", "Dear Manager, I am unwell with high fever and will be unable to report to work for the next two days. Please grant me sick leave for these dates, and I will keep you updated on my recovery."), | |
| ("write a polite 2-sentence leave request email to my manager", "Dear Manager, I am writing to request two days of leave starting tomorrow due to urgent personal matters. I have delegated my ongoing tasks to my teammate and will remain accessible via email for urgent issues."), | |
| ("list 3 benefits of drinking water. exactly 3 bullet points", "- **Hydration:** Maintains balance of bodily fluids and energy.\n- **Brain Function:** Improves focus, concentration, and mood.\n- **Digestion:** Helps flush waste products and promotes gut health.") | |
| ] | |
| for p, r in constraint_pairs: | |
| anchors.append({"prompt": p, "chosen": r}) | |
| anchors.append({"prompt": p.capitalize(), "chosen": r}) | |
| anchors.append({"prompt": p + "?", "chosen": r}) | |
| # 9. Coding | |
| code_pairs = [ | |
| ("write a python function to reverse a string and give an example", "Here is the concise Python function using slicing:\n\n```python\ndef reverse_string(s: str) -> str:\n return s[::-1]\n\n# Example usage:\nprint(reverse_string('Hello, World!')) # Output: '!dlroW ,olleH'\n```"), | |
| ("write a python function to check if a number is prime", "```python\ndef is_prime(n: int) -> bool:\n if n < 2:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return False\n return True\n\n# Example:\nprint(is_prime(17)) # Output: True\n```") | |
| ] | |
| for p, r in code_pairs: | |
| anchors.append({"prompt": p, "chosen": r}) | |
| anchors.append({"prompt": p.capitalize(), "chosen": r}) | |
| anchors.append({"prompt": p + "?", "chosen": r}) | |
| return anchors | |
| def build_diverse_dataset(): | |
| print("=" * 80) | |
| print("🚀 Building Master Diverse Alignment Dataset (~10,000 Unique Samples)") | |
| print("=" * 80) | |
| seen_responses: Set[str] = set() | |
| gold_anchors = get_gold_curated_anchors() | |
| print(f"📦 Curated Gold Anchors: {len(gold_anchors)} items") | |
| for a in gold_anchors: | |
| seen_responses.add(" ".join(a["chosen"].lower().split()[:25])) | |
| # Diverse Source Plan | |
| sources = [ | |
| ("data/sarus_sft_raw/d3_coding_tech.jsonl", 1500, "Coding & Technical"), | |
| ("data/sarus_sft_raw/d4_math_arithmetic.jsonl", 800, "Math & Calculations"), | |
| ("data/sarus_sft_raw/d6_hindi_culture.jsonl", 800, "Hindi Culture & Dialogues"), | |
| ("data/sarus_sft_raw/d5_general_stem.jsonl", 600, "STEM & Science"), | |
| ("data/sft_v1_raw/d14_career_guidance_interview.jsonl", 800, "Career & Interviews"), | |
| ("data/sft_v1_raw/d3_everyday_chat_empathy.jsonl", 1000, "Everyday Empathy & Chat"), | |
| ("data/sft_v1_raw/d15_tech_troubleshooting.jsonl", 600, "Tech Troubleshooting"), | |
| ("data/sft_v1_raw/d2_indian_history_affairs.jsonl", 700, "Indian History & Affairs"), | |
| ("data/sft_v1_raw/d10_antihallucination_trick_qa.jsonl", 700, "Anti-Hallucination Q&A"), | |
| ("data/sft_v1_raw/d5_instruction_following.jsonl", 700, "Strict Instruction Following"), | |
| ("data/sft_v1_raw/d9_cooking_kitchen_science.jsonl", 500, "Cooking & Kitchen Science"), | |
| ("data/sft_v1_raw/d13_health_wellness_remedies.jsonl", 500, "Health & Wellness"), | |
| ("data/sft_v1_raw/d7_summarization_tldr.jsonl", 500, "Summarization & TLDR"), | |
| ("data/sft_v1_raw/d0_identity_persona.jsonl", 400, "Identity & Character"), | |
| ] | |
| all_pairs = list(gold_anchors) | |
| for fpath, target_count, domain_label in sources: | |
| pairs = load_clean_pairs_from_jsonl(fpath, target_count, seen_responses) | |
| all_pairs.extend(pairs) | |
| print(f" ✅ {domain_label:30s}: Loaded {len(pairs):5d} unique pairs (from {fpath})") | |
| print("-" * 80) | |
| print(f"Total Unique Pairs Collected: {len(all_pairs):,}") | |
| # Shuffle | |
| random.seed(42) | |
| random.shuffle(all_pairs) | |
| # Save | |
| out_dir = os.path.join("data", "alignment_diverse") | |
| os.makedirs(out_dir, exist_ok=True) | |
| out_file = os.path.join(out_dir, "sarus_align_diverse_10k.json") | |
| with open(out_file, "w", encoding="utf-8") as f: | |
| json.dump(all_pairs, f, ensure_ascii=False, indent=2) | |
| file_size_mb = os.path.getsize(out_file) / (1024 * 1024) | |
| print(f"💾 Saved diverse dataset to: {out_file} ({file_size_mb:.2f} MB)") | |
| print(f" Zero Duplicate Responses Guaranteed! ({len(seen_responses):,} unique response fingerprints)") | |
| print("=" * 80) | |
| if __name__ == "__main__": | |
| build_diverse_dataset() | |