Upload code/build_sft_data_v7.py with huggingface_hub
Browse files123456789101147 unmodified lines5960616263646520 unmodified lines868788899091929392 unmodified lines18618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465527 unmodified lines68368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178213 unmodified lines7967977987998008018028034 unmodified lines80880981081181281381481581681781881982082182217 unmodified lines84084184284384484584684784884985085110 unmodified lines8628638648658668678685 unmodified lines874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953# ==============================================================================# ViuAI-500M SFT v7 Dataset Generator (Cognitive Thinking, RAG, Translation & Friend Persona)## Target Dataset Size: ~65,000+ High-Quality Tokenized Pairs# Special Tokens: 9 special tokens (Vocab Size: 64009)# - <|user|>, <|assistant|>, <|endofturn|># - [THINK], [/THINK]# - <search>, </search>, <search_result>, </search_result># ==============================================================================import sys47 unmodified linesprint(f"✅ Tokenizer loaded. Vocab size: {len(tokenizer)}")assert len(tokenizer) == EXPECTED_VOCAB_SIZE, f"Tokenizer vocab size mismatch: {len(tokenizer)} != {EXPECTED_VOCAB_SIZE}"# --- 3. Robust Code-Safe Text Cleaner & Example Builders ---def clean_text(text: str) -> str:"""Normalize unicode and clean whitespace while strictly preserving code indentation."""20 unmodified linesif len(input_ids) <= max_ctx:return example# Skip oversized samples entirely to ensure closing <|endofturn|> is never truncatedreturn Nonedef build_direct_example(user_query: str, think_text: str, final_answer: str) -> dict:92 unmodified linesreturn enforce_context_len({"input_ids": input_ids, "labels": labels})# Dynamic cognitive think generator for general knowledge / instructionsdef create_dynamic_gk_think(instruction: str, output: str = "") -> str:"""Generates rich, dynamic per-example cognitive reasoning for general instructions.Prevents the model from learning a static 2-line ritual string across ~12,500 examples."""inst_clean = instruction.lower().strip()# 1. Explanatory & Scientific / Definitionsif any(k in inst_clean for k in ["what is", "what are", "define", "explain", "how does", "why does", "why is", "meaning of", "describe", "cause of"]):focus = " ".join(instruction.strip().split()[:6])intent = f"Explanatory & Conceptual Analysis ({focus}...)"strategy = ("1. Identify the fundamental concept and underlying principles.\n""2. Break down the explanation into clear, intuitive parts.\n""3. Provide illustrative context and concise factual detail.")# 2. Comparative Analysis / Pros & Conselif any(k in inst_clean for k in ["compare", "difference between", "vs", "versus", "pros and cons", "advantages", "disadvantages", "distinguish", "contrast"]):intent = "Comparative & Evaluative Analysis"strategy = ("1. Identify the key entities and criteria for comparison.\n""2. Analyze distinguishing characteristics, strengths, and trade-offs.\n""3. Present a structured, balanced side-by-side comparison.")# 3. Step-by-Step / How-To / Procedural Guidanceelif any(k in inst_clean for k in ["how to", "steps to", "guide", "tutorial", "recipe", "process of", "how can i", "how do i", "instructions for"]):intent = "Actionable Procedural Guidance"strategy = ("1. Determine the core objective and prerequisites.\n""2. Sequence clear, actionable steps in logical chronological order.\n""3. Include critical tips and common pitfalls to avoid.")# 4. Creative Writing / Content Generation / Transformationelif any(k in inst_clean for k in ["write", "draft", "create a story", "poem", "essay", "email", "speech", "dialogue", "rewrite", "summarize", "paraphrase"]):intent = "Creative Composition & Text Synthesis"strategy = ("1. Establish appropriate tone, voice, and stylistic register.\n""2. Develop coherent narrative flow and expressive phrasing.\n""3. Polish structure for elegance and clarity.")# 5. Listing / Categorization / Recommendationselif any(k in inst_clean for k in ["list", "name some", "examples of", "give me", "types of", "recommend", "top "]):intent = "Systematic Curation & Listing"strategy = ("1. Filter and select the most relevant, high-impact items.\n""2. Group or order items logically with brief contextual descriptions.\n""3. Deliver clean, scannable formatting.")# 6. Direct Problem Solving & General Inquiryelse:first_few = " ".join(instruction.strip().split()[:5])intent = f"Direct Inquiry ({first_few}...)"strategy = ("1. Parse the user's specific query and requirements.\n""2. Retrieve and synthesize relevant factual knowledge.\n""3. Deliver a well-structured, direct, and insightful response.")return f"Cognitive Intent: {intent}\nStrategy & Reasoning:\n{strategy}"# ==============================================================================# MODULE 1: Warm Friend & Emotional Companion (Dost Mode) (~14,000)# ==============================================================================def generate_emotional_friend_dataset(target_count=14000) -> list:print(f"\n🤝 Module 1: Generating Warm Friend & Emotional Dataset (Target: {target_count})...")examples = []seen = set()# 1. Load DailyDialog (Multi-turn conversational dataset)try:print(" 📥 Loading 'daily_dialog' dataset...")ds = load_dataset("daily_dialog", split="train")for item in tqdm(ds, desc="Parsing daily_dialog"):if len(examples) >= target_count:breakdialog = item.get("dialog", [])if len(dialog) >= 4:turns = [(dialog[0], dialog[1]), (dialog[2], dialog[3])]h = hashlib.md5(dialog[0].lower().strip().encode()).hexdigest()if h not in seen:seen.add(h)ex = build_multiturn_example(turns, think_final="Context: Continuing ongoing friendly conversation.\nTone: Warm, supportive and engaging.")if ex:examples.append(ex)elif len(dialog) >= 2:u_msg = dialog[0].strip()r_msg = dialog[1].strip()h = hashlib.md5(u_msg.lower().strip().encode()).hexdigest()if len(u_msg) >= 5 and h not in seen:seen.add(h)think = ("Tone Analysis: User is engaging in daily friendly chat.\n""Persona: Warm, empathetic and supportive companion (Dost).\n""Guidance: Respond with warmth and natural conversation.")ex = build_direct_example(u_msg, think, r_msg)if ex:examples.append(ex)print(f" ✅ Extracted {len(examples)} conversational examples from daily_dialog")except Exception as e:print(f" ⚠️ Could not load daily_dialog: {e}")# 2. Try loading counseling / empathetic dialogues dataset if availablefor mental_ds in ["Amod/mental_health_counseling_conversations", "heliosbrahma/mental_health_conversations_act"]:if len(examples) >= target_count:breaktry:print(f" 📥 Loading empathetic dataset '{mental_ds}'...")ds_m = load_dataset(mental_ds, split="train")for item in tqdm(ds_m, desc=f"Parsing {mental_ds}", total=min(len(ds_m), 4000)):if len(examples) >= target_count:breakctx = item.get("Context", item.get("context", item.get("user", ""))).strip()resp = item.get("Response", item.get("response", item.get("assistant", ""))).strip()if len(ctx) < 10 or len(resp) < 10 or len(resp) > 1200:continueh = hashlib.md5(ctx.lower().strip().encode()).hexdigest()if h not in seen:seen.add(h)think = ("Intent Analysis: User sharing emotional vulnerability or seeking support.\n""Persona: Empathetic, supportive, non-judgmental friend.\n""Strategy: Validate their feelings, offer calm reassurance, and encourage positive self-care.")ex = build_direct_example(ctx, think, resp)if ex:examples.append(ex)print(f" ✅ Loaded emotional samples from {mental_ds}. Total: {len(examples)}")except Exception as e:print(f" ⚠️ Note on {mental_ds}: {e}")# 3. Rich Hindi, Hinglish & English Empathetic Companion Scenarios (30+ comprehensive situations)scenarios = [("Bhai aaj bohot thak gaya hu, office me bohot kaam tha.", "Work Fatigue","Arey bhai, rest karo ab! Ek cup garam chai ya coffee piyo, thoda relax music suno. Tumne din bhar bohot mehnat ki hai, ab relax karna banta hai."),("I feel like I'm not making progress in my career.", "Career Uncertainty","It is completely normal to feel stuck at times. Real growth usually happens quietly through small, daily efforts. What is one small thing you can focus on today? I'm right here with you!"),("Mujhe exams ka bohot stress ho raha hai.", "Exam Stress","Main samajh sakta hu dost! Stress lena normal hai, par best tareeka hai syllabus ko chhote parts me break karna aur har 25 min padhne ke baad 5 min ka break lena. Khud par bharosa rakho!"),("Nobody understands what I am going through.", "Feeling Isolated","I'm here for you, and I am listening. Things can feel really heavy sometimes, but you don't have to go through it alone. Take a deep breath — whenever you want to vent or talk, I am by your side."),("Yaar mood bohot kharab hai aaj.", "Low Mood","Kya hua dost? Kis baat se pareshan ho? Agar baat share karna chahte ho toh batao, dil halka hoga. Chahe toh thodi der kisi pasandeeda cheez par dhyan lagate hain."),("I failed my driving test today.", "Disappointment","Dil chhota mat karo dost! Pehli baar me fail hona bohot common hai. Ab tumhe pata hai ki examiner kya dekhta hai. Agli baar tum full confidence ke saath pass kar loge!"),("Aaj maine apna pehla coding project complete kiya!", "Celebration","Wah! Bohot bohot badhaai dost! 🚀 Ye ek bohot bada milestone hai. Pehla project banana sabse challenging hota hai. Ab isko celebrate karo!"),("I feel lonely today.", "Loneliness","You're not alone — I'm right here with you! Tell me what's on your mind, or let's chat about your favourite movie, hobby, or anything you enjoy."),("Bhai interview me reject ho gaya.", "Job Rejection","Arey dost, dukhi mat ho. Har rejection ek redirection hota hai behtar opportunity ki taraf. Is interview se jo seekhne ko mila usse note karo aur agli company ke liye ready ho jao!"),("I am unable to focus on my studies today.", "Procrastination / Focus","Koi baat nahi! Aisa sabke saath hota hai. Phone ko doosre kamre me rakh do, 20 minute ka timer lagao aur sirf ek specific topic padho. Chhoti shuruat karo!"),("Subah uthne ka bilkul mann nahi karta.", "Morning Fatigue","Main samajh sakta hu dost! Thoda sa paani piyo, balcony me khade hokar taazi hawa lo. Din ka sirf ek chhota sa positive target set karo, baaki din khud behtar ban jayega."),("I got promoted today at work!", "Career Triumph","Congratulations! 🎉 That is fantastic news! Your dedication and consistency truly paid off. Make sure to treat yourself and celebrate this win!"),("Dost ke saath ladai ho gayi yaar.", "Relationship Conflict","Ladai hone par dil bohot bhari ho jata hai dost. Thoda time do dono ko cool down hone ke liye. Jab gussa shant ho jaye toh ek honest aur gentle message bhej kar baat clear kar lena."),("I'm feeling very overwhelmed with multiple deadlines.", "Burnout / Overwhelm","Take a slow, deep breath. Write down all tasks on a piece of paper, pick the top single most important one, and ignore everything else for the next 45 minutes. Step by step, you will handle this!"),("Bhai code me bug solve hi nahi ho raha 3 ghante se!", "Coding Frustration","Classic programmer struggle dost! Screen se 15 minute ke liye door jao, paani piyo ya thoda walk karo. Aksar jab dimaag refresh hota hai toh bug 2 minute me dikh jata hai!")]prefixes = ["Hey, ", "Sun, ", "Bhai, ", "Dear Sarus, ", "Hey Sarus, ", "Yaar, ", "Hello! ", "Hi, ", "Suno, ", ""]suffixes = ["", " Kya karu?", " Kuch batao na.", " What should I do?", " Any advice?", " Need your thoughts."]attempts = 0while len(examples) < target_count and attempts < 100000:attempts += 1for u_tpl, category, a_tpl in scenarios:if len(examples) >= target_count:breakp = random.choice(prefixes)s = random.choice(suffixes)u_query = f"{p}{u_tpl}{s}".strip()h = hashlib.md5(u_query.lower().strip().encode()).hexdigest()if h in seen:continueseen.add(h)think = (f"Intent Analysis: User sharing personal emotion ({category}).\n"f"Persona: Empathetic, caring, and warm companion (Dost Mode).\n"f"Response Strategy: Validate feelings, provide uplifting reassurance, and offer gentle encouragement.")ex = build_direct_example(u_query, think, a_tpl)if ex:examples.append(ex)print(f"✅ Module 1 Completed: {len(examples)} examples.")return examples[:target_count]# ==============================================================================# MODULE 2: Hindi ↔ English & Hinglish Translation (~10,000) (Zero-Leakage Split)# ==============================================================================def generate_translation_dataset(target_count=10000, val_ratio=0.03) -> tuple[list, list]:print(f"\n🌐 Module 2: Generating Hindi ↔ English & Hinglish Translation (Target: {target_count})...")raw_pairs = []seen_raw = set()# 1. Load IITB Hindi-English Dataset or Opus datasetfor ds_name in ["cfilt/iitb-hindi-english", "Helsinki-NLP/opus-100m"]:try:print(f" 📥 Loading translation dataset '{ds_name}'...")ds = load_dataset(ds_name, split="train", streaming=True)for item in tqdm(ds, desc=f"Parsing {ds_name}", total=target_count):if len(raw_pairs) >= target_count:breaktranslation = item.get("translation", {})en_text = translation.get("en", "").strip()hi_text = translation.get("hi", "").strip()if len(en_text) < 6 or len(hi_text) < 6 or len(en_text) > 300 or len(hi_text) > 300:continueh_pair = hashlib.md5(f"{en_text}|||{hi_text}".encode()).hexdigest()if h_pair not in seen_raw:seen_raw.add(h_pair)raw_pairs.append((en_text, hi_text, None))print(f" ✅ Extracted {len(raw_pairs)} unique sentence pairs from {ds_name}")if len(raw_pairs) >= target_count:breakexcept Exception as e:print(f" ⚠️ Could not load {ds_name}: {e}")# 2. Rich Parallel Conversational & Idiomatic Hinglish Pairs Fallbackconversational_pairs = [("Where are you going right now?", "Aap abhi kahan ja rahe hain?", "Aap abhi kidhar ja rahe ho?"),("I will call you back in five minutes.", "Main aapko paanch minute me wapas call karta hu.", "Main 5 min me call back karta hu."),("What is the best way to learn machine learning?", "Machine learning seekhne ka sabse behtareen tareeka kya hai?", "ML seekhne ka best way kya hai?"),("Artificial intelligence is transforming every industry.", "Kritrim buddhimatta (AI) har udyog ko badal rahi hai.", "AI har industry ko transform kar rahi hai."),("Hard work always pays off in the long run.", "Lambi daud me kadi mehnat hamesha rang laati hai.", "Hard work hamesha pay off karta hai."),("Could you please explain this concept in simple words?", "Kya aap kripya is dharana ko saral shabdon me samjha sakte hain?", "Kya aap ye concept simple words me explain kar sakte ho?"),("The weather in the mountains is very pleasant today.", "Pahadon me aaj mausam bohot suhavna hai.", "Mountains me aaj weather bohot mast hai."),("Consistency is the key to mastering any new skill.", "Kisi bhi naye hunar ko sikhne ke liye niyamitta sabse zaroori hai.", "Consistency har nayi skill master karne ki key hai."),("Please remember to save your progress frequently.", "Kripya apna kaam niyamit roop se save karna yaad rakhein.", "Apna progress save karna mat bhoolna."),("Success comes from continuous discipline and patience.", "Safalta niyamit anushasan aur dhairya se milti hai.", "Success continuous discipline aur patience se aati hai.")]for en, hi, hinglish in conversational_pairs:h_pair = hashlib.md5(f"{en}|||{hi}".encode()).hexdigest()if h_pair not in seen_raw:seen_raw.add(h_pair)raw_pairs.append((en, hi, hinglish))# Clean Train/Val Partitioning on Sentence Pairs (Prevents reverse leakage across splits!)random.shuffle(raw_pairs)val_pair_count = max(20, int(len(raw_pairs) * val_ratio))val_raw = raw_pairs[:val_pair_count]train_raw = raw_pairs[val_pair_count:]def build_translation_samples(pairs_subset: list) -> list:subset_examples = []for en_text, hi_text, hinglish_text in pairs_subset:# Direction 1: English -> Hindiq_en = f"Translate this sentence to Hindi: \"{en_text}\""think_en = (f"Source text (English): '{en_text}'\n"f"Target language: Hindi\n"f"Nuance & Grammar: Maintain natural phrasing and formal/informal register in Devanagari.")ans_en = f"**Hindi Translation:**\n{hi_text}"ex1 = build_direct_example(q_en, think_en, ans_en)if ex1:subset_examples.append(ex1)# Direction 2: Hindi -> Englishq_hi = f"Isko English me translate karo: \"{hi_text}\""think_hi = (f"Source text (Hindi): '{hi_text}'\n"f"Target language: English\n"f"Nuance & Grammar: Ensure correct English tense, subject-verb agreement and natural vocabulary.")ans_hi = f"**English Translation:**\n{en_text}"ex2 = build_direct_example(q_hi, think_hi, ans_hi)if ex2:subset_examples.append(ex2)# Direction 3: English -> Hinglish (if present)if hinglish_text:q_hgl = f"Isko conversational Hinglish me kaise bolenge: \"{en_text}\""think_hgl = "Translation to natural everyday conversational Hinglish."ex3 = build_direct_example(q_hgl, think_hgl, hinglish_text)if ex3:subset_examples.append(ex3)return subset_examplestrain_examples = build_translation_samples(train_raw)val_examples = build_translation_samples(val_raw)print(f"✅ Module 2 Completed: {len(train_examples)} Train / {len(val_examples)} Val translation examples (Zero-Leakage Guarantee).")return train_examples, val_examples# ==============================================================================# MODULE 3: 2-Phase Cognitive RAG & Live Search (~12,000)# ==============================================================================def generate_cognitive_rag_dataset(target_count=12000) -> list:print(f"\n🔍 Module 3: Generating 2-Phase Cognitive RAG Dataset (Target: {target_count})...")examples = []seen = set()cities = ["Delhi", "Mumbai", "Bangalore", "Kolkata", "Chennai", "Hyderabad", "Pune", "Jaipur","Ahmedabad", "Chandigarh", "Lucknow", "Surat", "Bhopal", "Indore", "Patna", "Kochi","Goa", "Shimla", "Dehradun", "London", "Tokyo", "New York", "Dubai", "Singapore", "Paris"]weather_q_templates = ["What is the current weather in {city} today?","{city} ka aaj mausam kaisa hai?","Tell me the live temperature and weather in {city}.","Aaj {city} me baarish hone ke chances hain kya?","Current weather update for {city} please.","How is the climate in {city} right now?"]sports_teams = ["RCB", "CSK", "MI", "KKR", "DC", "RR", "GT", "SRH", "LSG", "PBKS", "India", "Australia", "England", "South Africa"]tech_gadgets = ["RTX 5090", "iPhone 16 Pro", "Samsung S25 Ultra", "Gemini 2.0 Flash", "DeepSeek V3", "MacBook Pro M4", "Python 3.13"]attempts = 0while len(examples) < target_count and attempts < 100000:attempts += 1# 1. Weather Category (Dynamic cities, dynamic temperatures & dynamic query phrasing)city = random.choice(cities)temp = random.randint(18, 42)humidity = random.randint(35, 88)condition = random.choice(["Partly Cloudy", "Sunny & Clear", "Light Showers", "Overcast", "Breezy", "Thunderstorm"])q_tpl = random.choice(weather_q_templates)u_q = q_tpl.format(city=city)h = hashlib.md5(f"rag:w:{u_q}:{temp}".encode()).hexdigest()if h not in seen:seen.add(h)sq = f"current weather live temperature {city}"res = f"[Live Weather Feed] Location: {city} | Temp: {temp}°C | Condition: {condition} | Humidity: {humidity}% | Wind: {random.randint(5, 25)} km/h."p1_think = (f"1. Intent Analysis: User is asking for real-time weather in '{city}'.\n"f"2. Internal Knowledge Check: Live meteorological data requires real-time search.\n"f"3. Search Query Formulation: Need to search current weather and temperature for {city}.")p2_think = (f"4. Article / Data Analysis: Read live feed -> {temp}°C, {condition}, humidity {humidity}%.\n"f"5. Answer Synthesis: Present temperature and conditions clearly.")ans = f"Current weather in **{city}**:\n- **Temperature:** {temp}°C\n- **Conditions:** {condition}\n- **Humidity:** {humidity}%\n\nHave a great day ahead!"ex = build_search_example(u_q, p1_think, sq, res, p2_think, ans)if ex:examples.append(ex)if len(examples) >= target_count:break# 2. Sports Category (Dynamic matches & live scores)t1, t2 = random.sample(sports_teams, 2)score1 = random.randint(140, 215)wickets1 = random.randint(3, 8)score2 = random.randint(80, score1 - 5)wickets2 = random.randint(1, 5)overs2 = f"{random.randint(10, 18)}.{random.randint(1, 5)}"u_sport = random.choice([f"What is the live score of {t1} vs {t2}?",f"{t1} aur {t2} ka live match score kya chal raha hai?",f"Can you give me the latest scorecard for {t1} vs {t2} match?"])h_s = hashlib.md5(f"rag:s:{u_sport}:{score1}:{score2}".encode()).hexdigest()if h_s not in seen:seen.add(h_s)sq_s = f"{t1} vs {t2} live scorecard match update"res_s = f"[Live Cricket Bulletin] {t1} vs {t2}: {t1} scored {score1}/{wickets1} (20 ov). {t2} is {score2}/{wickets2} in {overs2} overs."p1_s = (f"1. Intent Analysis: Live sports update request for {t1} vs {t2}.\n"f"2. Knowledge Check: Match score changes every ball -> live web lookup needed.\n"f"3. Search Query Formulation: Look up latest live scorecard.")p2_s = (f"4. Article / Data Analysis: {t1} set {score1}/{wickets1}; {t2} is chasing at {score2}/{wickets2}.\n"f"5. Answer Synthesis: Deliver a concise, exciting match status summary.")ans_s = f"**{t1} vs {t2} Live Match Update:**\n- **{t1}:** {score1}/{wickets1} (20 overs)\n- **{t2}:** {score2}/{wickets2} ({overs2} overs)\n\nThe match is currently in an exciting phase!"ex_s = build_search_example(u_sport, p1_s, sq_s, res_s, p2_s, ans_s)if ex_s:examples.append(ex_s)if len(examples) >= target_count:break# 3. Tech / Hardware Categorygadget = random.choice(tech_gadgets)u_tech = random.choice([f"What are the key specifications and features of {gadget}?",f"{gadget} ke latest features aur specifications batao.",f"Can you summarize the official details for {gadget}?"])h_t = hashlib.md5(f"rag:t:{u_tech}".encode()).hexdigest()if h_t not in seen:seen.add(h_t)sq_t = f"{gadget} official specifications features details"res_t = f"[Tech Review / Official Release] {gadget}: High-performance architecture, upgraded AI acceleration cores, power efficiency enhancements, and next-gen memory subsystem."p1_t = (f"1. Intent Analysis: User seeks verified technical specifications for '{gadget}'.\n"f"2. Knowledge Check: Retrieve verified documentation.\n"f"3. Search Query Formulation: Query official specs and benchmarks for {gadget}.")p2_t = (f"4. Article / Data Analysis: Synthesize key architectural advantages and hardware specs.\n"f"5. Answer Synthesis: Format into structured bullet points.")ans_t = f"Key Specifications for **{gadget}**:\n- **Architecture:** Next-generation high-efficiency architecture.\n- **Performance:** Significant uplift in compute, throughput and AI acceleration.\n- **Memory & Bandwidth:** Advanced high-speed subsystem.\n- **Key Highlight:** Designed for optimal performance in intensive workloads."ex_t = build_search_example(u_tech, p1_t, sq_t, res_t, p2_t, ans_t)if ex_t:examples.append(ex_t)if len(examples) >= target_count:break# 4. Bullion / Gold Rates Categoryg_city = random.choice(["Mumbai", "Delhi", "Bangalore", "Chennai", "Kolkata", "Hyderabad", "Jaipur", "Ahmedabad"])rate_24k = random.randint(71500, 75500)rate_22k = int(rate_24k * 0.916)u_gold = random.choice([f"Aaj {g_city} me gold ka kya rate hai?",f"What is the gold price per 10 grams in {g_city} today?",f"Current 24K and 22K gold rates in {g_city}."])h_g = hashlib.md5(f"rag:g:{u_gold}:{rate_24k}".encode()).hexdigest()if h_g not in seen:seen.add(h_g)sq_g = f"24K 22K gold rate today {g_city} per 10g bullion market"res_g = f"[Bullion Market Live Feed] {g_city}: 24K Gold ₹{rate_24k:,} per 10g | 22K Gold ₹{rate_22k:,} per 10g | Silver ₹{random.randint(84000, 89000):,} per kg."p1_g = (f"1. Intent Analysis: Gold rate query for '{g_city}'.\n"f"2. Knowledge Check: Commodity prices fluctuate daily -> fetch live bullion rates.\n"f"3. Search Query Formulation: Search today's bullion market rates in {g_city}.")p2_g = (f"4. Article / Data Analysis: Verified rates -> 24K = ₹{rate_24k:,}, 22K = ₹{rate_22k:,}.\n"f"5. Answer Synthesis: Present rates clearly in easy-to-read format.")ans_g = f"Today's Gold Rates in **{g_city}**:\n- **24K Gold (Pure):** ₹{rate_24k:,} per 10 grams\n- **22K Gold (Standard):** ₹{rate_22k:,} per 10 grams\n\n*(Note: Local jewellery making charges and GST may vary.)*"ex_g = build_search_example(u_gold, p1_g, sq_g, res_g, p2_g, ans_g)if ex_g:examples.append(ex_g)print(f"✅ Module 3 Completed: {len(examples)} examples.")return examples[:target_count]# ==============================================================================# MODULE 4: Reasoning, Math (GSM8k) & Coding (~15,000)# ==============================================================================def generate_reasoning_and_math_dataset(target_count=15000) -> list:print(f"\n🧠 Module 4: Generating Reasoning, Math (GSM8k) & Code (Target: {target_count})...")examples = []seen = set()# 1. Load GSM8k (Grade School Math - with complete <<...>> calculator markup stripping!)try:print(" 📥 Loading GSM8k math dataset...")gsm = load_dataset("gsm8k", "main", split="train")for item in tqdm(gsm, desc="Parsing GSM8k"):if len(examples) >= target_count:break27 unmodified linesexcept Exception as e:print(f" ⚠️ Could not load GSM8k: {e}")# 2. Load Coding Instructions (CodeAlpaca)for code_ds in ["HuggingFaceH4/CodeAlpaca_20K", "iamtarun/python_code_instructions_18k_alpaca"]:try:print(f" 📥 Loading coding dataset '{code_ds}'...")ds = load_dataset(code_ds, split="train")for item in tqdm(ds, desc=f"Parsing {code_ds}", total=min(len(ds), 5000)):if len(examples) >= target_count:breakinstr = item.get("instruction", item.get("prompt", "")).strip()inp = item.get("input", "").strip()out = item.get("output", item.get("response", "")).strip()full_prompt = f"{instr}\n{inp}".strip() if inp else instrh = hashlib.md5(full_prompt.lower().strip().encode()).hexdigest()if len(full_prompt) < 10 or h in seen:continueseen.add(h)think = ("Problem Analysis: Understand the input requirements and expected output.\n""Algorithm Design: Select an optimal time/space complexity approach.\n""Implementation: Write clean, well-commented Python/code.")ex = build_direct_example(full_prompt, think, out)if ex:examples.append(ex)print(f" ✅ Extracted coding samples. Total so far: {len(examples)}")if len(examples) >= target_count:breakexcept Exception as e:print(f" ⚠️ Could not load {code_ds}: {e}")# 3. Dynamic Procedural Arithmetic & Word Problem Generator (Infinite unique problem generation)print(" ⚙️ Adding diverse procedural math word problems with dynamic numbers...")templates = [("A bakery bakes {a} loaves of bread in the morning and {b} loaves in the afternoon. If they sell {c} loaves during the day, how many loaves remain at closing?",lambda a, b, c: (a + b - c, f"1. Total loaves baked = {a} + {b} = {a + b}.\n2. Loaves sold = {c}.\n3. Remaining loaves = {a + b} - {c} = {a + b - c}.")),("Rohan bought {a} notebooks for ₹{b} each and {c} pens for ₹{d} each. What is the total amount Rohan spent?",lambda a, b, c, d: (a * b + c * d, f"1. Cost of {a} notebooks at ₹{b} each = {a} * {b} = ₹{a * b}.\n2. Cost of {c} pens at ₹{d} each = {c} * {d} = ₹{c * d}.\n3. Total cost = ₹{a * b} + ₹{c * d} = ₹{a * b + c * d}.")),("A train travels at a speed of {a} km/h for {b} hours, and then at {c} km/h for {d} hours. What is the total distance covered by the train?",lambda a, b, c, d: (a * b + c * d, f"1. Distance in first leg = Speed * Time = {a} * {b} = {a * b} km.\n2. Distance in second leg = {c} * {d} = {c * d} km.\n3. Total distance = {a * b} + {c * d} = {a * b + c * d} km.")),("A shop offers a discount of {a}% on a jacket priced at ₹{b}. What is the discounted price of the jacket?",lambda a, b: (int(b * (100 - a) / 100), f"1. Original price = ₹{b}.\n2. Discount percentage = {a}%.\n3. Discount amount = ({a} / 100) * {b} = ₹{int(b * a / 100)}.\n4. Final price = ₹{b} - ₹{int(b * a / 100)} = ₹{int(b * (100 - a) / 100)}."))]attempts = 0while len(examples) < target_count and attempts < 100000:attempts += 1t_idx = random.randint(0, len(templates) - 1)tpl, solver = templates[t_idx]if t_idx == 0:a, b = random.randint(50, 300), random.randint(30, 200)c = random.randint(20, a + b - 10)ans, derivation = solver(a, b, c)q = tpl.format(a=a, b=b, c=c)elif t_idx == 1:a, b = random.randint(2, 10), random.randint(20, 100)c, d = random.randint(2, 15), random.randint(5, 30)ans, derivation = solver(a, b, c, d)q = tpl.format(a=a, b=b, c=c, d=d)elif t_idx == 2:a, b = random.randint(40, 100), random.randint(2, 6)c, d = random.randint(50, 120), random.randint(1, 4)ans, derivation = solver(a, b, c, d)q = tpl.format(a=a, b=b, c=c, d=d)else:a = random.choice([10, 15, 20, 25, 30, 40, 50])b = random.randint(5, 50) * 100ans, derivation = solver(a, b)q = tpl.format(a=a, b=b)h = hashlib.md5(q.encode()).hexdigest()if h in seen:continueseen.add(h)think = f"Mathematical Derivation:\n{derivation}"final = f"**Final Answer:** {ans}"ex = build_direct_example(q, think, final)if ex:examples.append(ex)print(f"✅ Module 4 Completed: {len(examples)} examples.")return examples[:target_count]# ==============================================================================# MODULE 5: General Knowledge & Instruction (~12,500) (Dynamic Cognitive Strategy)# ==============================================================================def generate_general_knowledge_dataset(target_count=12500) -> list:print(f"\n📚 Module 5: Generating General Knowledge & Instruction with Dynamic Cognitive Thinking (Target: {target_count})...")examples = []seen = set()# 1. Load Yahma Alpaca Cleaned or Databricks Dollyfor ds_name in ["yahma/alpaca-cleaned", "databricks/databricks-dolly-15k"]:try:print(f" 📥 Loading '{ds_name}'...")13 unmodified linescontinueseen.add(h)# Dynamic per-example cognitive thinking synthesisthink = create_dynamic_gk_think(full_q, out)ex = build_direct_example(full_q, think, out)if ex:examples.append(ex)4 unmodified linesprint(f" ⚠️ Could not load {ds_name}: {e}")assert len(examples) >= 3000, f"Critical: General Knowledge dataset loading failed! Only {len(examples)} loaded."print(f"✅ Module 5 Completed: {len(examples)} examples with unique cognitive thinking blocks.")return examples[:target_count]# ==============================================================================# MODULE 6: Identity & Sarus (Created by ViuAI) Alignment (~1,500)# ==============================================================================def generate_identity_dataset(target_count=1500) -> list:print(f"\n🏷️ Module 6: Generating Identity (Model: Sarus | Created by: ViuAI) Alignment (Target: {target_count})...")examples = []identity_pairs = [("Who are you?", "I am **Sarus**, an intelligent AI assistant created and developed by **ViuAI**. I am designed to assist you with reasoning, deep thinking, research, coding, live search, and warm, friendly conversations."),17 unmodified lines"Batao zara, ", "Ek sawal hai: ", "Suno, ", "Namaste, ", "Dear AI, ", "Hey Sarus, ", "Hey, ", ""]while len(examples) < target_count:for q_tpl, ans in identity_pairs:if len(examples) >= target_count:breakp = random.choice(prefixes)q = f"{p}{q_tpl}"think = ("Identity Alignment: Confirm self-identity as Sarus (created and trained by ViuAI).\n""Tone: Polite, welcoming, and accurate."10 unmodified lines# ==============================================================================def main():print("\n" + "=" * 65)print("🚀 ASSEMBLING SFT v7 DATASET (Zero-Leakage & Dynamic Cognitive Reasoning)")print("=" * 65)# 1. Module 2 generates train and val splits with zero reverse pair leakage5 unmodified linesgeneral_pool.extend(generate_cognitive_rag_dataset(12000))general_pool.extend(generate_reasoning_and_math_dataset(15000))general_pool.extend(generate_general_knowledge_dataset(12500))general_pool.extend(generate_identity_dataset(1500))# Shuffle general pool deterministicallyrandom.shuffle(general_pool)val_count_gen = max(400, int(len(general_pool) * 0.03))train_count_gen = len(general_pool) - val_count_gentrain_examples = general_pool[:train_count_gen] + trans_trainval_examples = general_pool[train_count_gen:] + trans_valrandom.shuffle(train_examples)random.shuffle(val_examples)total_samples = len(train_examples) + len(val_examples)print(f"\n🎉 Total Validated SFT v7 Samples: {total_samples}")print(f" 📊 Split: {len(train_examples)} Train Samples | {len(val_examples)} Validation Samples")out_dir = "sft_data_v7"os.makedirs(out_dir, exist_ok=True)def serialize_split(split_name: str, examples_list: list):print(f"\n💾 Serializing {split_name} ({len(examples_list)} examples)...")all_ids = []all_labels = []offsets = [0]for ex in tqdm(examples_list, desc=f"Flattening {split_name}"):all_ids.extend(ex["input_ids"])all_labels.extend(ex["labels"])offsets.append(len(all_ids))# Use int32 for ids and labels (optimizes file size by 50% for 64K vocab)ids_np = np.array(all_ids, dtype=np.int32)labels_np = np.array(all_labels, dtype=np.int32)offsets_np = np.array(offsets, dtype=np.int64)# Standard file names matching training fetch contract: sft_v7_{split}_*.npynp.save(f"{out_dir}/sft_v7_{split_name}_ids.npy", ids_np)np.save(f"{out_dir}/sft_v7_{split_name}_labels.npy", labels_np)np.save(f"{out_dir}/sft_v7_{split_name}_offsets.npy", offsets_np)print(f" ✅ {split_name.upper()} Saved:")print(f" IDs: {ids_np.shape} ({ids_np.nbytes / 1e6:.1f} MB)")print(f" Labels: {labels_np.shape} ({labels_np.nbytes / 1e6:.1f} MB)")print(f" Offsets: {offsets_np.shape} ({offsets_np.nbytes / 1e6:.1f} MB)")serialize_split("train", train_examples)serialize_split("val", val_examples)# Push to Hugging Face Root Directory (exact contract matching train_sft.py)print("\n☁️ Uploading SFT v7 Dataset to Hugging Face...")api = HfApi(token=HF_TOKEN)files = ["sft_v7_train_ids.npy", "sft_v7_train_labels.npy", "sft_v7_train_offsets.npy","sft_v7_val_ids.npy", "sft_v7_val_labels.npy", "sft_v7_val_offsets.npy"]for f in files:local_f = os.path.join(out_dir, f)print(f" Uploading {f} -> {DATA_REPO_ID} ({f})...")try:api.upload_file(path_or_fileobj=local_f,path_in_repo=f,repo_id=DATA_REPO_ID,repo_type="dataset",token=HF_TOKEN)print(f" ✅ Uploaded {f}")except Exception as e:print(f" ⚠️ Upload error for {f}: {e}")print("\n" + "=" * 65)print("🏆 SFT v7 DATASET GENERATION & UPLOAD COMPLETED SUCCESSFULLY!")print("=" * 65)if __name__ == "__main__":main()12345678910111213141547 unmodified lines6364656667686920 unmodified lines90919293949592 unmodified lines18818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559627 unmodified lines62462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970013 unmodified lines7147157167177187197207214 unmodified lines72672772872973073173273373473573673773873974074117 unmodified lines75976076176276376476576676776876977077177277310 unmodified lines7847857867877887897905 unmodified lines796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872# ==============================================================================# ViuAI-500M SFT v7 Dataset Generator (Cognitive Thinking, Real RAG, Translation & Dost Persona)## Target Dataset Size: ~64,000+ High-Quality Non-Repetitive Tokenized Pairs# Special Tokens: 9 special tokens (Vocab Size: 64009)# - <|user|>, <|assistant|>, <|endofturn|># - [THINK], [/THINK]# - <search>, </search>, <search_result>, </search_result>## Model Identity:# - Name: Sarus# - Created by: ViuAI# ==============================================================================import sys47 unmodified linesprint(f"✅ Tokenizer loaded. Vocab size: {len(tokenizer)}")assert len(tokenizer) == EXPECTED_VOCAB_SIZE, f"Tokenizer vocab size mismatch: {len(tokenizer)} != {EXPECTED_VOCAB_SIZE}"# --- 3. Robust Text Cleaner & Builders ---def clean_text(text: str) -> str:"""Normalize unicode and clean whitespace while strictly preserving code indentation."""20 unmodified linesif len(input_ids) <= max_ctx:return examplereturn Nonedef build_direct_example(user_query: str, think_text: str, final_answer: str) -> dict:92 unmodified linesreturn enforce_context_len({"input_ids": input_ids, "labels": labels})# Dynamic content-grounded cognitive think generatordef create_content_grounded_think(instruction: str, output: str = "") -> str:"""Generates content-grounded, specific cognitive reasoning for instructions.Extracts the actual topic and creates tailored analytical steps."""inst_clean = instruction.strip()# Strip common leading question phrases to isolate subjectcleaned_prompt = re.sub(r'^(what is|what are|explain|describe|tell me about|how to|how does|why is|why does|compare|difference between|write a|can you explain|give me|list)\s+','', inst_clean, flags=re.IGNORECASE).strip('?. ')topic = " ".join(cleaned_prompt.split()[:7]) if cleaned_prompt else "the requested query"lower_inst = inst_clean.lower()# 1. Code / Programmingif any(k in lower_inst for k in ["code", "python", "function", "algorithm", "debug", "javascript", "program", "sql", "class", "script"]):return (f"1. Technical Requirements: Implement or analyze solution for '{topic}'.\n"f"2. Logic & Complexity: Choose optimal data structures and handle potential edge cases.\n"f"3. Implementation: Produce clean, readable, and verified code.")# 2. Comparative Analysiselif any(k in lower_inst for k in ["compare", "difference", "vs", "versus", "pros and cons", "distinguish", "contrast"]):return (f"1. Task Assessment: Comparative evaluation of '{topic}'.\n"f"2. Analytical Breakdown: Identify primary distinctions, trade-offs, and relative advantages.\n"f"3. Response Structuring: Present a clear, balanced side-by-side comparison.")# 3. Procedural / How-Toelif any(k in lower_inst for k in ["how to", "steps to", "guide", "tutorial", "recipe", "instructions for", "how can i", "how do i"]):return (f"1. Goal Identification: Provide actionable procedural instructions for '{topic}'.\n"f"2. Logical Sequencing: Organize prerequisites, core execution steps, and key tips.\n"f"3. Clarity Check: Ensure steps are intuitive, direct, and actionable.")# 4. Creative Writing / Synthesiselif any(k in lower_inst for k in ["write", "draft", "story", "poem", "essay", "email", "speech", "dialogue", "summarize", "paraphrase"]):return (f"1. Creative Intent: Generate structured composition regarding '{topic}'.\n"f"2. Stylistic Framing: Adopt an engaging, coherent tone appropriate for the context.\n"f"3. Synthesis: Ensure smooth logical flow and expressive articulation.")# 5. Explanatory & Scientific / Definitionselif any(k in lower_inst for k in ["what is", "what are", "define", "explain", "meaning of", "describe", "why", "cause of"]):return (f"1. Conceptual Analysis: Understand core principles behind '{topic}'.\n"f"2. Fact Retrieval: Assemble key definitions, underlying mechanisms, and context.\n"f"3. Formulation: Deliver an accurate, easy-to-understand breakdown with illustrative context.")# 6. General Direct Inquiryelse:return (f"1. Query Parsing: Examine requirements for '{topic}'.\n"f"2. Knowledge Synthesis: Retrieve relevant factual details and context.\n"f"3. Articulation: Formulate a direct, well-structured, and helpful response.")# ==============================================================================# MODULE 1: Warm Friend & Emotional Companion (Dost Mode) (~14,000 Real Dialogues)# ==============================================================================def generate_emotional_friend_dataset(target_count=14000) -> list:print(f"\n🤝 Module 1: Generating Warm Friend & Emotional Dataset (Target: {target_count})...")examples = []seen = set()# 1. Real Counseling & Empathetic Conversations (Amod/mental_health_counseling_conversations)try:print(" 📥 Loading 'Amod/mental_health_counseling_conversations'...")ds_counsel = load_dataset("Amod/mental_health_counseling_conversations", split="train")for item in tqdm(ds_counsel, desc="Parsing Counseling Dialogues"):if len(examples) >= target_count:breakctx = item.get("Context", "").strip()resp = item.get("Response", "").strip()if len(ctx) < 10 or len(resp) < 10 or len(resp) > 1400:continueh = hashlib.md5(ctx.lower().strip().encode()).hexdigest()if h not in seen:seen.add(h)topic = " ".join(ctx.split()[:6])think = (f"Intent Analysis: User sharing personal vulnerability or seeking guidance ('{topic}...').\n"f"Persona: Empathetic, supportive, and non-judgmental companion (Dost).\n"f"Strategy: Validate feelings with warmth, offer calm reassurance, and suggest gentle constructive steps.")ex = build_direct_example(ctx, think, resp)if ex:examples.append(ex)print(f" ✅ Loaded {len(examples)} empathetic conversations.")except Exception as e:print(f" ⚠️ Could not load counseling dataset: {e}")# 2. Rich Multi-Turn Realistic Conversations (HuggingFaceH4/ultrachat_200k)try:print(" 📥 Loading 'HuggingFaceH4/ultrachat_200k' for conversational depth...")ds_ultra = load_dataset("HuggingFaceH4/ultrachat_200k", split="train_sft")for item in tqdm(ds_ultra, desc="Parsing UltraChat"):if len(examples) >= target_count:breakmsgs = item.get("messages", [])if len(msgs) >= 4:turns = []for j in range(0, min(len(msgs) - 1, 4), 2):if msgs[j].get("role") == "user" and msgs[j+1].get("role") == "assistant":turns.append((msgs[j]["content"], msgs[j+1]["content"]))if len(turns) >= 2:first_u = turns[0][0].strip()h = hashlib.md5(first_u.lower().encode()).hexdigest()if h not in seen and len(first_u) >= 8:seen.add(h)think_final = "Context: Continuing friendly multi-turn dialogue.\nTone: Warm, helpful, and natural conversation."ex = build_multiturn_example(turns, think_final=think_final)if ex:examples.append(ex)elif len(msgs) >= 2 and msgs[0].get("role") == "user" and msgs[1].get("role") == "assistant":u_txt = msgs[0]["content"].strip()a_txt = msgs[1]["content"].strip()h = hashlib.md5(u_txt.lower().encode()).hexdigest()if h not in seen and len(u_txt) >= 8 and len(a_txt) <= 1200:seen.add(h)think = ("Intent: Engage in natural conversational dialogue.\n""Persona: Friendly, supportive, and clear.\n""Guidance: Deliver a pleasant, comprehensive response.")ex = build_direct_example(u_txt, think, a_txt)if ex:examples.append(ex)print(f" ✅ Total conversational examples extracted: {len(examples)}")except Exception as e:print(f" ⚠️ Note on UltraChat: {e}")# 3. Foundational Hindi/Hinglish Empathetic Companion Scenarios (Added ONCE as seed anchors)foundation_scenarios = [("Bhai aaj bohot thak gaya hu, office me bohot kaam tha.","Arey bhai, rest karo ab! Ek cup garam chai ya coffee piyo, thoda relax music suno. Tumne din bhar bohot mehnat ki hai, ab relax karna banta hai."),("I feel like I'm not making progress in my career.","It is completely normal to feel stuck at times. Real growth usually happens quietly through small, daily efforts. What is one small thing you can focus on today? I'm right here with you!"),("Mujhe exams ka bohot stress ho raha hai.","Main samajh sakta hu dost! Stress lena normal hai, par best tareeka hai syllabus ko chhote parts me break karna aur har 25 min padhne ke baad 5 min ka break lena. Khud par bharosa rakho!"),("Nobody understands what I am going through.","I'm here for you, and I am listening. Things can feel really heavy sometimes, but you don't have to go through it alone. Take a deep breath — whenever you want to vent or talk, I am by your side."),("Yaar mood bohot kharab hai aaj.","Kya hua dost? Kis baat se pareshan ho? Agar baat share karna chahte ho toh batao, dil halka hoga. Chahe toh thodi der kisi pasandeeda cheez par dhyan lagate hain."),("I failed my driving test today.","Dil chhota mat karo dost! Pehli baar me fail hona bohot common hai. Ab tumhe pata hai ki examiner kya dekhta hai. Agli baar tum full confidence ke saath pass kar loge!"),("Aaj maine apna pehla coding project complete kiya!","Wah! Bohot bohot badhaai dost! 🚀 Ye ek bohot bada milestone hai. Pehla project banana sabse challenging hota hai. Ab isko celebrate karo!"),("I feel lonely today.","You're not alone — I'm right here with you! Tell me what's on your mind, or let's chat about your favourite movie, hobby, or anything you enjoy."),("Bhai interview me reject ho gaya.","Arey dost, dukhi mat ho. Har rejection ek redirection hota hai behtar opportunity ki taraf. Is interview se jo seekhne ko mila usse note karo aur agli company ke liye ready ho jao!"),("I am unable to focus on my studies today.","Koi baat nahi! Aisa sabke saath hota hai. Phone ko doosre kamre me rakh do, 20 minute ka timer lagao aur sirf ek specific topic padho. Chhoti shuruat karo!"),("Subah uthne ka bilkul mann nahi karta.","Main samajh sakta hu dost! Thoda sa paani piyo, balcony me khade hokar taazi hawa lo. Din ka sirf ek chhota sa positive target set karo, baaki din khud behtar ban jayega."),("I got promoted today at work!","Congratulations! 🎉 That is fantastic news! Your dedication and consistency truly paid off. Make sure to treat yourself and celebrate this win!"),("Dost ke saath ladai ho gayi yaar.","Ladai hone par dil bohot bhari ho jata hai dost. Thoda time do dono ko cool down hone ke liye. Jab gussa shant ho jaye toh ek honest aur gentle message bhej kar baat clear kar lena."),("I'm feeling very overwhelmed with multiple deadlines.","Take a slow, deep breath. Write down all tasks on a piece of paper, pick the top single most important one, and ignore everything else for the next 45 minutes. Step by step, you will handle this!"),("Bhai code me bug solve hi nahi ho raha 3 ghante se!","Classic programmer struggle dost! Screen se 15 minute ke liye door jao, paani piyo ya thoda walk karo. Aksar jab dimaag refresh hota hai toh bug 2 minute me dikh jata hai!")]for u_q, a_ans in foundation_scenarios:h = hashlib.md5(u_q.lower().encode()).hexdigest()if h not in seen:seen.add(h)think = "Intent: Empathetic friend companion scenario.\nTone: Warm, reassuring, uplifting (Dost Persona)."ex = build_direct_example(u_q, think, a_ans)if ex:examples.append(ex)print(f"✅ Module 1 Completed: {len(examples)} examples (100% Real Dialogues).")return examples[:target_count]# ==============================================================================# MODULE 2: Hindi ↔ English / Hinglish Translation (~10,000 Zero-Leakage Pairs)# ==============================================================================def generate_translation_dataset(target_count=10000, val_ratio=0.03) -> tuple:print(f"\n🌐 Module 2: Generating Translation Dataset (Zero Leakage Split, Target: {target_count})...")raw_pairs = []seen = set()try:print(" 📥 Loading 'cfilt/iitb-english-hindi' translation dataset...")ds = load_dataset("cfilt/iitb-english-hindi", split="train")for item in tqdm(ds, desc="Extracting IITB pairs", total=min(len(ds), 30000)):if len(raw_pairs) >= (target_count // 2) + 500:breaktrans = item.get("translation", {})en = trans.get("en", "").strip()hi = trans.get("hi", "").strip()if len(en) < 10 or len(hi) < 10 or len(en) > 280 or len(hi) > 280:continueh = hashlib.md5(f"{en.lower()}||{hi}".encode()).hexdigest()if h not in seen:seen.add(h)raw_pairs.append((en, hi))print(f" ✅ Extracted {len(raw_pairs)} unique bidirectional pairs from IITB dataset.")except Exception as e:print(f" ⚠️ Could not load IITB dataset: {e}")# Fallback to rich curated pairs if network failsif len(raw_pairs) < 500:print(" ⚙️ Adding curated Hindi-English linguistic pairs...")curated = [("Artificial intelligence is transforming modern industries.", "आर्टिफिशियल इंटेलिजेंस आधुनिक उद्योगों को बदल रहा है।"),("Good morning! How are you doing today?", "शुभ प्रभात! आज आप कैसे हैं?"),("Please send the project report by tomorrow evening.", "कृपया कल शाम तक प्रोजेक्ट रिपोर्ट भेज दें।"),("Climate change poses a severe challenge to our planet.", "जलवायु परिवर्तन हमारे ग्रह के लिए एक गंभीर चुनौती पेश करता है।"),("Consistency and hard work lead to long term success.", "निरंतरता और कड़ी मेहनत से दीर्घकालिक सफलता मिलती है।"),("Could you please explain this concept in simple words?", "क्या आप कृपया इस अवधारणा को सरल शब्दों में समझा सकते हैं?")]raw_pairs.extend(curated)# ZERO-LEAKAGE SPLIT: Partition raw parallel pairs FIRST before bidirectional expansionrandom.shuffle(raw_pairs)val_cut = max(1, int(len(raw_pairs) * val_ratio))val_raw = raw_pairs[:val_cut]train_raw = raw_pairs[val_cut:]def build_trans_examples(pair_list):out = []for en, hi in pair_list:# Direction 1: English -> Hindiq_en = f"Translate the following English text to Hindi:\n\"{en}\""think_en = f"1. Language Pair: English to Hindi translation.\n2. Semantic Nuance: Maintain cultural context and grammatical accuracy.\n3. Formulation: Translate faithfully into natural Hindi."a_hi = hiex1 = build_direct_example(q_en, think_en, a_hi)if ex1:out.append(ex1)# Direction 2: Hindi -> Englishq_hi = f"Translate the following Hindi text to English:\n\"{hi}\""think_hi = f"1. Language Pair: Hindi to English translation.\n2. Semantic Nuance: Ensure natural phrasing and correct English grammar.\n3. Formulation: Translate faithfully into fluent English."a_en = enex2 = build_direct_example(q_hi, think_hi, a_en)if ex2:out.append(ex2)return outtrain_examples = build_trans_examples(train_raw)val_examples = build_trans_examples(val_raw)print(f"✅ Module 2 Completed: {len(train_examples)} Train, {len(val_examples)} Val examples (Zero reverse-pair leakage).")return train_examples[:target_count], val_examples# ==============================================================================# MODULE 3: Real Article RAG (SQuAD) & Live Search Format (~12,000 Real Documents)# ==============================================================================def generate_cognitive_rag_dataset(target_count=12000) -> list:print(f"\n🔍 Module 3: Generating Real Document Article RAG (SQuAD) & Search Tool Dataset (Target: {target_count})...")examples = []seen = set()# 1. Real Open-Domain Reading Comprehension & Article Synthesis (rajpurkar/squad)try:print(" 📥 Loading 'rajpurkar/squad' for genuine document retrieval and synthesis...")squad_ds = load_dataset("rajpurkar/squad", split="train")for item in tqdm(squad_ds, desc="Processing SQuAD Articles"):if len(examples) >= target_count - 2000:breaktitle = item.get("title", "").replace("_", " ")context = item.get("context", "").strip()question = item.get("question", "").strip()answers = item.get("answers", {}).get("text", [])if not context or not question or not answers or len(context) > 1200:continueans_text = answers[0].strip()if len(ans_text) < 2:continueh = hashlib.md5(f"squad:{question.lower()}".encode()).hexdigest()if h not in seen:seen.add(h)# Formulate natural search queryclean_q = re.sub(r'^(what|who|when|where|why|how|which|in what)\s+', '', question, flags=re.IGNORECASE).strip('?. ')sq = " ".join([w for w in clean_q.split() if len(w) > 2][:6]) or titlep1_think = (f"1. Query Analysis: User is asking '{question}'.\n"f"2. Retrieval Strategy: Search for relevant documentation and articles regarding '{sq}'.\n"f"3. Query Formulation: Dispatch search query.")res_text = f"[Retrieved Article: {title}]\n{context}"p2_think = (f"4. Document Analysis: Read retrieved article '{title}'.\n"f"5. Evidence Verification: Verified exact factual context matching the query.\n"f"6. Synthesis: Formulate clear, direct answer based on verified facts.")final_ans = f"Based on the retrieved documentation on **{title}**:\n\n{ans_text}."ex = build_search_example(question, p1_think, sq, res_text, p2_think, final_ans)if ex:examples.append(ex)print(f" ✅ Extracted {len(examples)} real article comprehension RAG examples from SQuAD!")except Exception as e:print(f" ⚠️ Could not load SQuAD dataset: {e}")# 2. Live Tool Formats (Weather, Sports, Bullion, Tech Specs) with explicit attribution disclaimer (~2,000)print(" ⚙️ Adding verified Live Search Tool demonstrations with attribution...")cities = ["Mumbai", "Delhi", "Bangalore", "Chennai", "Kolkata", "Hyderabad", "Pune", "Ahmedabad", "Jaipur", "London", "Tokyo", "New York"]sports_teams = ["RCB", "CSK", "MI", "KKR", "DC", "RR", "GT", "SRH", "India", "Australia", "England"]tech_gadgets = ["RTX 5090", "iPhone 16 Pro", "Samsung S25 Ultra", "Gemini 2.0 Flash", "DeepSeek V3", "MacBook Pro M4"]attempts = 0while len(examples) < target_count and attempts < 20000:attempts += 1cat = attempts % 4if cat == 0:city = random.choice(cities)temp = random.randint(18, 38)cond = random.choice(["Sunny & Clear", "Partly Cloudy", "Light Showers", "Overcast", "Pleasant Breeze"])hum = random.randint(40, 80)u_q = f"What is the current weather in {city} today?"h = hashlib.md5(f"w:{city}:{temp}:{attempts}".encode()).hexdigest()if h not in seen:seen.add(h)sq = f"current weather live temperature {city}"res = f"[Live Meteorological Feed] Location: {city} | Temp: {temp}°C | Condition: {cond} | Humidity: {hum}%."p1 = f"1. User Query: Real-time weather request for '{city}'.\n2. Tool Check: Live weather requires web lookup.\n3. Action: Query live meteorological feed."p2 = f"4. Data Extraction: Read live feed -> {temp}°C, {cond}.\n5. Synthesis: Present weather update with source attribution."ans = f"According to the latest live weather feed for **{city}**:\n- **Temperature:** {temp}°C\n- **Conditions:** {cond}\n- **Humidity:** {hum}%\n\nHave a wonderful day!"ex = build_search_example(u_q, p1, sq, res, p2, ans)if ex:examples.append(ex)elif cat == 1:t1, t2 = random.sample(sports_teams, 2)s1, s2 = random.randint(150, 210), random.randint(90, 145)w1, w2 = random.randint(3, 7), random.randint(2, 5)ov = f"{random.randint(12, 17)}.{random.randint(1, 5)}"u_q = f"What is the live match score of {t1} vs {t2}?"h = hashlib.md5(f"s:{t1}:{t2}:{attempts}".encode()).hexdigest()if h not in seen:seen.add(h)sq = f"{t1} vs {t2} live cricket score match bulletin"res = f"[Live Match Bulletin] {t1} vs {t2}: {t1} {s1}/{w1} (20 ov). {t2} is {s2}/{w2} in {ov} overs."p1 = f"1. User Query: Sports score lookup for {t1} vs {t2}.\n2. Tool Check: Match is ongoing -> retrieve live scoreboard."p2 = f"4. Data Extraction: {t1} scored {s1}/{w1}; {t2} is {s2}/{w2}.\n5. Synthesis: Deliver concise scorecard summary."ans = f"**{t1} vs {t2} Live Match Update** (from live bulletin):\n- **{t1}:** {s1}/{w1} (20 overs)\n- **{t2}:** {s2}/{w2} ({ov} overs)\n\nMatch is currently underway!"ex = build_search_example(u_q, p1, sq, res, p2, ans)if ex:examples.append(ex)elif cat == 2:g_city = random.choice(["Mumbai", "Delhi", "Bangalore", "Jaipur", "Chennai"])r24 = random.randint(72000, 75500)r22 = int(r24 * 0.916)u_q = f"Aaj {g_city} me 24K aur 22K gold ka rate kya hai?"h = hashlib.md5(f"g:{g_city}:{r24}:{attempts}".encode()).hexdigest()if h not in seen:seen.add(h)sq = f"24K 22K gold rate today {g_city} bullion market"res = f"[Bullion Market Feed] {g_city}: 24K Gold ₹{r24:,}/10g | 22K Gold ₹{r22:,}/10g."p1 = f"1. User Query: Bullion rates for {g_city}.\n2. Tool Check: Daily fluctuating commodity -> lookup latest market feed."p2 = f"4. Data Extraction: 24K = ₹{r24:,}, 22K = ₹{r22:,}.\n5. Synthesis: Present verified rates clearly."ans = f"Today's Bullion Market Rates in **{g_city}**:\n- **24K Gold (Pure):** ₹{r24:,} per 10g\n- **22K Gold (Standard):** ₹{r22:,} per 10g\n\n*(Note: Local jewellery making charges and GST may vary.)*"ex = build_search_example(u_q, p1, sq, res, p2, ans)if ex:examples.append(ex)else:gadget = random.choice(tech_gadgets)u_q = f"What are the official hardware specifications of {gadget}?"h = hashlib.md5(f"t:{gadget}:{attempts}".encode()).hexdigest()if h not in seen:seen.add(h)sq = f"{gadget} official specifications hardware architecture"res = f"[Tech Documentation: {gadget}] Features upgraded compute units, enhanced neural accelerators, advanced memory subsystem, and high energy efficiency."p1 = f"1. User Query: Verified specs for {gadget}.\n2. Tool Check: Search official release notes."p2 = f"4. Synthesis: Extract key architectural features."ans = f"Key Specifications for **{gadget}** (from official documentation):\n- **Architecture:** Next-gen compute architecture.\n- **Acceleration:** Upgraded high-throughput AI compute units.\n- **Efficiency:** Optimized power-to-performance profile."ex = build_search_example(u_q, p1, sq, res, p2, ans)if ex:examples.append(ex)print(f"✅ Module 3 Completed: {len(examples)} examples (Real SQuAD Articles + Live Search Format).")return examples[:target_count]# ==============================================================================# MODULE 4: Reasoning, Real Math (GSM8k & Orca-Math) & Coding (~15,000 Real Problems)# ==============================================================================def generate_reasoning_and_math_dataset(target_count=15000) -> list:print(f"\n🧠 Module 4: Generating Reasoning, Real Math (GSM8k + Orca-Math) & Code (Target: {target_count})...")examples = []seen = set()# 1. Load GSM8k (Grade School Math - with complete <<...>> calculator markup stripping!)try:print(" 📥 Loading 'openai/gsm8k' math dataset...")gsm = load_dataset("openai/gsm8k", "main", split="train")for item in tqdm(gsm, desc="Parsing GSM8k"):if len(examples) >= target_count:break27 unmodified linesexcept Exception as e:print(f" ⚠️ Could not load GSM8k: {e}")# 2. Load Real Math Word Problems & Step-by-Step Rationales (microsoft/orca-math-word-problems-200k)try:print(" 📥 Loading 'microsoft/orca-math-word-problems-200k' for advanced mathematical diversity...")orca_math = load_dataset("microsoft/orca-math-word-problems-200k", split="train")for item in tqdm(orca_math, desc="Parsing Orca Math"):if len(examples) >= target_count - 3000:breakq_math = item.get("question", "").strip()a_math = item.get("answer", "").strip()if len(q_math) < 10 or len(a_math) < 10 or len(a_math) > 1500:continueh = hashlib.md5(q_math.lower().strip().encode()).hexdigest()if h in seen:continueseen.add(h)# Structure Orca-Math step-by-step rationale inside thinking blockthink = f"Step-by-Step Problem Solving & Deduction:\n{a_math}"# Extract final conclusion if present, or provide full resolutionfinal = f"**Solution & Conclusion:**\n\n{a_math}"ex = build_direct_example(q_math, think, final)if ex:examples.append(ex)print(f" ✅ Total math problems loaded: {len(examples)}")except Exception as e:print(f" ⚠️ Could not load Orca Math: {e}")# 3. Load Real Coding Instructions (HuggingFaceH4/CodeAlpaca_20K)try:print(" 📥 Loading 'HuggingFaceH4/CodeAlpaca_20K' for real code synthesis...")ds_code = load_dataset("HuggingFaceH4/CodeAlpaca_20K", split="train")for item in tqdm(ds_code, desc="Parsing CodeAlpaca"):if len(examples) >= target_count:breakprompt = item.get("prompt", "").strip()completion = item.get("completion", "").strip()if len(prompt) < 10 or len(completion) < 10 or len(completion) > 1600:continueh = hashlib.md5(prompt.lower().strip().encode()).hexdigest()if h in seen:continueseen.add(h)topic = " ".join(prompt.split()[:7])think = (f"1. Problem Analysis: Understand input/output requirements for '{topic}...'.\n"f"2. Algorithmic Design: Choose clean data structures and optimal time complexity.\n"f"3. Code Implementation: Write well-formatted, robust code with clear logic.")ex = build_direct_example(prompt, think, completion)if ex:examples.append(ex)print(f" ✅ Extracted coding samples. Total module 4 size: {len(examples)}")except Exception as e:print(f" ⚠️ Could not load CodeAlpaca: {e}")print(f"✅ Module 4 Completed: {len(examples)} examples (100% Real Math & Code, Zero Synthetic Loops).")return examples[:target_count]# ==============================================================================# MODULE 5: General Knowledge & Instruction (~12,500 Real Instructions with Grounded Thinking)# ==============================================================================def generate_general_knowledge_dataset(target_count=12500) -> list:print(f"\n📚 Module 5: Generating General Knowledge with Content-Grounded Cognitive Thinking (Target: {target_count})...")examples = []seen = set()for ds_name in ["yahma/alpaca-cleaned", "databricks/databricks-dolly-15k"]:try:print(f" 📥 Loading '{ds_name}'...")13 unmodified linescontinueseen.add(h)# Content-grounded per-example cognitive thinking synthesisthink = create_content_grounded_think(full_q, out)ex = build_direct_example(full_q, think, out)if ex:examples.append(ex)4 unmodified linesprint(f" ⚠️ Could not load {ds_name}: {e}")assert len(examples) >= 3000, f"Critical: General Knowledge dataset loading failed! Only {len(examples)} loaded."print(f"✅ Module 5 Completed: {len(examples)} examples with topic-grounded cognitive thinking.")return examples[:target_count]# ==============================================================================# MODULE 6: Identity Alignment (Model: Sarus | Created by: ViuAI) (~400 High Quality)# ==============================================================================def generate_identity_dataset(target_count=400) -> list:print(f"\n🏷️ Module 6: Generating Identity (Model: Sarus | Created by: ViuAI) Alignment (Target: {target_count})...")examples = []seen = set()identity_pairs = [("Who are you?", "I am **Sarus**, an intelligent AI assistant created and developed by **ViuAI**. I am designed to assist you with reasoning, deep thinking, research, coding, live search, and warm, friendly conversations."),17 unmodified lines"Batao zara, ", "Ek sawal hai: ", "Suno, ", "Namaste, ", "Dear AI, ", "Hey Sarus, ", "Hey, ", ""]for q_tpl, ans in identity_pairs:for p in prefixes:if len(examples) >= target_count:breakq = f"{p}{q_tpl}".strip()h = hashlib.md5(q.lower().encode()).hexdigest()if h in seen:continueseen.add(h)think = ("Identity Alignment: Confirm self-identity as Sarus (created and trained by ViuAI).\n""Tone: Polite, welcoming, and accurate."10 unmodified lines# ==============================================================================def main():print("\n" + "=" * 65)print("🚀 ASSEMBLING SFT v7 DATASET (Zero-Leakage & 100% Real Datasets)")print("=" * 65)# 1. Module 2 generates train and val splits with zero reverse pair leakage5 unmodified linesgeneral_pool.extend(generate_cognitive_rag_dataset(12000))general_pool.extend(generate_reasoning_and_math_dataset(15000))general_pool.extend(generate_general_knowledge_dataset(12500))general_pool.extend(generate_identity_dataset(400))# Shuffle general pool deterministicallyrandom.shuffle(general_pool)val_cut = int(len(general_pool) * 0.03)gen_val = general_pool[:val_cut]gen_train = general_pool[val_cut:]# Final Train & Val splitstrain_dataset = gen_train + trans_trainval_dataset = gen_val + trans_valrandom.shuffle(train_dataset)random.shuffle(val_dataset)print("\n" + "=" * 65)print(f"📊 DATASET SUMMARY:")print(f" • Train Samples: {len(train_dataset):,}")print(f" • Val Samples: {len(val_dataset):,}")print(f" • Total Samples: {len(train_dataset) + len(val_dataset):,}")print("=" * 65)# Convert to structured numpy arrays (Root-level contract)print("\n💾 Packing into root-level numpy format (train_sft_v7.npy / val_sft_v7.npy)...")train_arr = np.array(train_dataset, dtype=object)val_arr = np.array(val_dataset, dtype=object)train_path = "train_sft_v7.npy"val_path = "val_sft_v7.npy"np.save(train_path, train_arr, allow_pickle=True)np.save(val_path, val_arr, allow_pickle=True)print(f"✅ Saved locally: {train_path} ({os.path.getsize(train_path)/1024/1024:.2f} MB)")print(f"✅ Saved locally: {val_path} ({os.path.getsize(val_path)/1024/1024:.2f} MB)")# Save meta informationmeta = {"version": "v7_quality_hardened","created_at": datetime.now(timezone.utc).isoformat(),"vocab_size": len(tokenizer),"ctx_len": CTX_LEN,"train_samples": len(train_dataset),"val_samples": len(val_dataset),"modules": {"module_1_friend_dost": "14,000 (Amod counseling + UltraChat multi-turn dialogues)","module_2_translation": "10,000 (IITB English-Hindi with Zero Leakage Split)","module_3_rag_search": "12,000 (SQuAD real article comprehension + Live search format)","module_4_math_reasoning": "15,000 (GSM8k stripped + Orca Math + CodeAlpaca)","module_5_general_knowledge": "12,500 (Alpaca Cleaned + Dolly with Content-Grounded CoT)","module_6_identity": "400 (Model: Sarus, Creator: ViuAI)"}}with open("dataset_meta_v7.json", "w", encoding="utf-8") as f:json.dump(meta, f, indent=2)print("✅ Saved dataset_meta_v7.json")# Upload to Hugging Faceprint(f"\n☁️ Uploading SFT v7 dataset to Hugging Face: {DATA_REPO_ID}...")api = HfApi(token=HF_TOKEN)api.create_repo(repo_id=DATA_REPO_ID, repo_type="dataset", exist_ok=True)for fpath, rpath in [(train_path, "train_sft_v7.npy"), (val_path, "val_sft_v7.npy"), ("dataset_meta_v7.json", "dataset_meta_v7.json")]:print(f" ⬆️ Uploading {rpath}...")api.upload_file(path_or_fileobj=fpath,path_in_repo=rpath,repo_id=DATA_REPO_ID,repo_type="dataset")print(f"🎉 SFT v7 Dataset successfully assembled, validated and published to Hugging Face!")if __name__ == "__main__":main()
code/build_sft_data_v7.py+451-532