Upload code/build_sft_data_v7.py with huggingface_hub
Browse files331 unmodified lines3323333343353363373386 unmodified lines34534634734834935035114 unmodified lines36636736836937037137237337437537637737837938038138238338438538638732 unmodified lines42042142242342442542617 unmodified lines44444544644744844945022 unmodified lines47347447547647747847939 unmodified lines51952052152252352452513 unmodified lines53954054154254354454523 unmodified lines56957057157257357457536 unmodified lines61261361461561661761813 unmodified lines6326336346356366376386396406416426436446456466476486496506516526536546556566571 unmodified line6596606616626636646656666676686696706716726736746756766776786796806816826836846856866871 unmodified line6896906916926936946956966976986997007017024 unmodified lines70770870971071171271371471571671771871972072172272372472572672772872973073173273373415 unmodified lines7507517527537547557567577587597607617627637647657667673 unmodified lines7717727737747757767777787797807815 unmodified lines78778878979079179229 unmodified lines82282382482582682782810 unmodified lines83984084184284384484584684763 unmodified lines91191291391491591691791891992092192292392492592692792892993093193293320 unmodified lines954955956957958959960331 unmodified linesif not ctx or not resp:continueh = hashlib.md5(f"{ctx[:50]}:{resp[:50]}".encode()).hexdigest()if h in seen:continueseen.add(h)6 unmodified linesexcept Exception as e:print(f" ⚠️ Could not load counseling dataset: {e}")# 2. Daily Emotional Dialogues & Life Situationsemotional_scenarios = [("Aaj mera interview bohot bura gaya, lagta hai reject ho jaunga.","Main samajh sakta hoon bhai, interview bura jaane se dil toot jata hai. Lekin yaad rakhna ek interview tumhari poori kabiliyat define nahi karta. Jo galtiyan hui unse seekhenge aur agle interview me aur better karenge. Main tumhare saath hoon!"),14 unmodified lines("Bhai bohot stress ho raha hai coding project complete nahi ho raha.","Fret mat karo bhai! Coding me jab bugs aate hain to sabse pehle thoda walk leke aao. Step by step debug karenge to solution zaroor milega."),("Nobody seemed to remember my birthday today...","I am right here with you, and I want to wish you a genuinely Happy Birthday! 🎂 You are valued, appreciated, and meaningful. Treat yourself to something you love today!")]prefixes = ["Suno Sarus, ", "Bhai, ek baat batao: ", "Hey friend, ", "Yaar ek problem hai... ","Can I talk to you? ", "Sarus, ", "Bhai, ", "Dear Sarus, ", "Hey buddy, ", ""]attempts = 0while len(examples) < target_count and attempts < 25000:attempts += 1prompt_base, ans_base = random.choice(emotional_scenarios)prefix = random.choice(prefixes)prompt = f"{prefix}{prompt_base}".strip()h = hashlib.md5(prompt.lower().encode()).hexdigest()if h not in seen:seen.add(h)think = random.choice(counsel_think_variants)32 unmodified linesq = clean_text(item.get("prompt") or item.get("instruction") or item.get("question") or "")a = clean_text(item.get("response") or item.get("output") or item.get("answer") or "")if q and a:h = hashlib.md5(q.lower().encode()).hexdigest()if h not in seen_raw:seen_raw.add(h)raw_pairs.append(("custom_pair", q, a, ""))17 unmodified linesif len(en_txt) < 15 or len(hi_txt) < 10 or len(en_txt) > 300:continueh = hashlib.md5(en_txt.lower().encode()).hexdigest()if h in seen_raw:continueseen_raw.add(h)22 unmodified lines("Stay curious and keep exploring new horizons every single day.", "उत्सुक रहें और हर एक दिन नए क्षितिज तलाशते रहें।", "Hamesha curious raho aur har din kuch naya explore karo.")]for en, hi, hng in curated_benchmark_pairs:h = hashlib.md5(en.lower().encode()).hexdigest()if h not in seen_raw:seen_raw.add(h)raw_pairs.append(("triplet", en, hi, hng))39 unmodified linesif pair_type == "custom_pair":q, a = item1, item2h = hashlib.md5(q.lower().encode()).hexdigest()if h not in seen:seen.add(h)think = create_content_grounded_think(q, a)13 unmodified linesp = tmpl.format(s=hi)think = "1. Translation Task: Hindi -> English.\n2. Accuracy: Produce fluent, idiomatic English phrasing."r = enh = hashlib.md5(p.encode()).hexdigest()if h not in seen:seen.add(h)ex = build_direct_example(p, think, r)23 unmodified linesthink = "1. Translation Task: Hindi -> English.\n2. Fidelity: Accurate and clear English."r = enh = hashlib.md5(p.encode()).hexdigest()if h not in seen:seen.add(h)ex = build_direct_example(p, think, r)36 unmodified linesif len(ans) < 3 or len(ctx) < 50:continueh = hashlib.md5(f"{q}:{ans}".encode()).hexdigest()if h in seen:continueseen.add(h)13 unmodified linesprint(f" ⚠️ Could not load SQuAD dataset: {e}")# 2. Live Tool Search & Verified Retrieval Patternscities = ["Mumbai", "Delhi", "Bengaluru", "Kolkata", "Chennai", "Hyderabad", "London", "Tokyo", "New York"]sports_teams = [("India", "Australia"), ("England", "South Africa"), ("Mumbai Indians", "CSK"), ("Real Madrid", "Barcelona")]tech_gadgets = ["H200 Tensor Core GPU", "ViuAI 500M Neural Architecture", "Llama 3 8B", "PyTorch 2.4 Distributed"]attempts = 0while len(examples) < target_count and attempts < 25000:attempts += 1cat = attempts % 4if cat == 0:city = random.choice(cities)u_q = f"What is the current weather update for {city} today?"h = hashlib.md5(f"w:{city}:{attempts}".encode()).hexdigest()if h not in seen:seen.add(h)sq = f"current weather live report {city}"res = f"[Live Meteorological Feed] Location: {city} | Conditions: Normal seasonal weather | Data source: Verified Meteorological Bureau."p1 = f"1. User Query: Real-time weather request for '{city}'.\n2. Tool Check: Live fluctuating condition -> trigger search query."p2 = f"3. Source Evaluation: Read feed for {city}.\n4. Formulation: Present verified update with attribution."ans = f"According to the live meteorological update for **{city}**:\n- **Status:** Clear and seasonal weather conditions.\n\n*(Data retrieved via verified meteorological search feed.)*"ex = build_search_example(u_q, p1, sq, res, p2, ans)if ex:examples.append(ex)1 unmodified lineelif cat == 1:t1, t2 = random.choice(sports_teams)u_q = f"Can you check the latest match bulletin for {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} match update news bulletin"res = f"[Sports News Wire] {t1} vs {t2}: Official scoreboard and match highlights published by tournament committee."p1 = f"1. User Query: Sports match status for {t1} vs {t2}.\n2. Tool Check: Live sporting event -> lookup sports news feed."p2 = f"3. Data Synthesis: Parse tournament bulletin.\n4. Deliver clear match summary."ans = f"**{t1} vs {t2} Match Summary** (from official tournament feed):\n- Latest bulletin confirms the fixture is scheduled and underway according to tournament timetables."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", "Bengaluru", "Jaipur", "Chennai"])u_q = f"Aaj {g_city} me bullion market updates kya hain?"h = hashlib.md5(f"g:{g_city}:{attempts}".encode()).hexdigest()if h not in seen:seen.add(h)sq = f"bullion market gold silver rates today {g_city}"res = f"[Bullion Association Feed] {g_city}: Official benchmark bullion indices updated for today."p1 = f"1. User Query: Bullion rates for {g_city}.\n2. Tool Check: Daily fluctuating commodity -> lookup latest market index."p2 = f"3. Data Extraction: Review bullion association feed.\n4. Formulation: Present verified market overview."ans = f"Today's Bullion Market Overview in **{g_city}**:\n- Standard market trading is active under current daily benchmark rates.\n\n*(Note: Local jewellery making charges, taxes, and GST may vary.)*"ex = build_search_example(u_q, p1, sq, res, p2, ans)if ex:examples.append(ex)1 unmodified lineelse:gadget = random.choice(tech_gadgets)u_q = f"What are the official architectural 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 architecture whitepaper"res = f"[Technical Documentation: {gadget}] Features upgraded compute units, high memory bandwidth, and optimized energy efficiency."p1 = f"1. User Query: Technical specs for {gadget}.\n2. Tool Check: Search official release documentation."p2 = f"3. Synthesis: Extract key architectural features."ans = f"Key Specifications for **{gadget}** (from official documentation):\n- **Architecture:** Next-gen high-efficiency compute architecture.\n- **Acceleration:** Upgraded high-throughput matrix compute units.\n- **Performance:** Optimized power-to-performance profile."ex = build_search_example(u_q, p1, sq, res, p2, ans)if ex:examples.append(ex)4 unmodified lines# ==============================================================================# MODULE 4: Reasoning, Real Math (GSM8k & Orca-Math) & Coding (~15,000 Real Problems)# ==============================================================================def generate_reasoning_and_math_dataset(target_count=15000) -> list:global _current_module_key_current_module_key = "module_4"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:breakq = item["question"].strip()a = item["answer"].strip()h = hashlib.md5(q.lower().strip().encode()).hexdigest()if h in seen:continueseen.add(h)parts = a.split("####")if len(parts) == 2:raw_rationale = parts[0].strip()15 unmodified linesthink = f"Step-by-Step Reasoning:\n{clean_a}"final = clean_aex = build_direct_example(q, think, final)if ex:examples.append(ex)print(f" ✅ Loaded {len(examples)} GSM8k math problems (calculator tags cleanly stripped)!")except 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")orca_cap = max(1, int(target_count * 0.75))for item in tqdm(orca_math, desc="Parsing Orca Math"):if len(examples) >= orca_cap:break3 unmodified linesif 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)think = f"Step-by-Step Problem Solving & Deduction:\n{a_math}"concise_conclusion = extract_concise_math_conclusion(a_math)5 unmodified linesf"Thus, {concise_conclusion}"])final = fmtex = build_direct_example(q_math, think, final)if ex:examples.append(ex)29 unmodified linescontinueq = f"{inst}\n\nInput:\n{inp}" if inp else insth = hashlib.md5(q.lower().strip().encode()).hexdigest()if h in seen:continueseen.add(h)10 unmodified linesreturn examples[:target_count]# ==============================================================================# MODULE 6: Identity & Persona Alignment (~400 Examples)# ==============================================================================def generate_identity_dataset(target_count=400) -> list:global _current_module_key_current_module_key = "module_6"print(f"\n🏷️ Module 6: Generating Identity (Model: Sarus | Created by: ViuAI) Alignment (Target: {target_count})...")63 unmodified linesf"1. Direct name confirmation.\n2. State '{MODEL_NAME}'."),("Who is behind ViuAI?",f"**{CREATOR}** is the AI research and engineering organization that created and trained me, **{MODEL_NAME}**.",f"1. Organization background.\n2. Explain '{CREATOR}' relationship.")]prefixes = ["Hey, ", "Hello! ", "Excuse me, ", "Quick question: ", "Batao, ","Can you clarify: ", "Please tell me, ", "Suno, ", "Sir, ", "Dost, ","Ek baat batao, ", "Just wondering, ", "Hi there! ", "", ""]attempts = 0while len(examples) < target_count and attempts < 10000:attempts += 1q_base, ans, think = random.choice(identity_scenarios)prefix = random.choice(prefixes)prompt = f"{prefix}{q_base}".strip()h = hashlib.md5(prompt.lower().encode()).hexdigest()if h not in seen:seen.add(h)ex = build_direct_example(prompt, think, ans)20 unmodified linesm3 = generate_grounded_rag_dataset(12000)m4 = generate_reasoning_and_math_dataset(15000)m5 = generate_general_instruct_dataset(12500)m6 = generate_identity_dataset(400)other_examples = m1 + m3 + m4 + m5 + m6print(f"\n📊 Total Other Raw Examples Generated: {len(other_examples):,}")331 unmodified lines3323333343353363373386 unmodified lines34534634734834935035114 unmodified lines36636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740832 unmodified lines44144244344444544644717 unmodified lines46546646746846947047122 unmodified lines49449549649749849950039 unmodified lines54054154254354454554613 unmodified lines56056156256356456556623 unmodified lines59059159259359459559636 unmodified lines63363463563663763863913 unmodified lines6536546556566576586596606616626636646656666676686696706716726736746756766776786791 unmodified line6816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107111 unmodified line7137147157167177187197207217227237247257267274 unmodified lines73273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781815 unmodified lines8348358368378388398408418428438448458468478488498508518528538548558563 unmodified lines8608618628638648655 unmodified lines87187287387487587687787887988088188229 unmodified lines91291391491591691791810 unmodified lines92993093193293393493593693763 unmodified lines10011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105420 unmodified lines107510761077107810791080108110821083108410851086108710881089331 unmodified linesif not ctx or not resp:continueh = hashlib.md5(f"{ctx.lower().strip()}:{resp.lower().strip()}".encode()).hexdigest()if h in seen:continueseen.add(h)6 unmodified linesexcept Exception as e:print(f" ⚠️ Could not load counseling dataset: {e}")# 2. Daily Emotional Dialogues & Life Situations (Expanded template bank: 60+ scenarios)emotional_scenarios = [("Aaj mera interview bohot bura gaya, lagta hai reject ho jaunga.","Main samajh sakta hoon bhai, interview bura jaane se dil toot jata hai. Lekin yaad rakhna ek interview tumhari poori kabiliyat define nahi karta. Jo galtiyan hui unse seekhenge aur agle interview me aur better karenge. Main tumhare saath hoon!"),14 unmodified lines("Bhai bohot stress ho raha hai coding project complete nahi ho raha.","Fret mat karo bhai! Coding me jab bugs aate hain to sabse pehle thoda walk leke aao. Step by step debug karenge to solution zaroor milega."),("Nobody seemed to remember my birthday today...","I am right here with you, and I want to wish you a genuinely Happy Birthday! 🎂 You are valued, appreciated, and meaningful. Treat yourself to something you love today!"),("Mera project submission kal hai aur code me error aa rahi hai.","Ghabraao mat dost! Error message batao, hum dono milkar line-by-line debug karenge aur fix kar denge."),("I feel so overwhelmed by all the responsibilities piling up.","Take a deep breath. When everything feels like too much, break it down into one tiny task at a time. What is one small thing we can tackle right now?"),("Aaj office me boss ne bina wajah daant diya.","Ye sunkar bura laga bhai. Kabhi-kabhi log apna frustration doosron par nikal dete hain. Tum dil par mat lo, tumne apna kaam imaandari se kiya hai."),("I feel like giving up on my fitness goals.","Progress is never linear! Taking a couple of slow days doesn't erase all the work you've put in. Just show up tomorrow with a fresh mindset."),("Mera dil bohot udaas hai aaj, kisi kaam me man nahi lag raha.","Koi baat nahi dost, har din ek jaisa productive nahi hota. Thoda music suno, chai ya coffee piyo aur rest lo. Sab theek ho jayega."),("I feel anxious about an upcoming presentation.","Stage freight and presentation nerves are completely normal! Practice your opening slide a few times. You know your topic better than anyone in that room."),("Bhai mere dost ne mujhse paise liye the aur ab call nahi utha raha.","Ye bohot dukhdayi situation hai. Kuch din wait karke calmly message bhejo. Relationship aur finance dono handle karne me thoda dhairya rakhna padega."),("I didn't get selected for the scholarship I worked so hard for.","I know how devastating that feels after giving it your all. But remember, this is just one closed door. Many more opportunities are waiting for you."),("Subah se sar dard ho raha hai aur kaam bohot bacha hai.","Apni sehat pehle hai dost! 15 minute ke liye screen band karo, aankhein band karke rest lo aur paani piyo."),("I feel unappreciated at work no matter how much extra effort I put in.","Your efforts have genuine value, even if management fails to acknowledge them right now. Keep building your skills—they belong to you, not your company.")]prefixes = ["Suno Sarus, ", "Bhai, ek baat batao: ", "Hey friend, ", "Yaar ek problem hai... ","Can I talk to you? ", "Sarus, ", "Bhai, ", "Dear Sarus, ", "Hey buddy, ", "Dost, ","Please help me with this thought: ", "Ek baat share karni thi: ", "Listen Sarus, ", ""]attempts = 0while len(examples) < target_count and attempts < 35000:attempts += 1prompt_base, ans_base = random.choice(emotional_scenarios)prefix = random.choice(prefixes)prompt = f"{prefix}{prompt_base}".strip()h = hashlib.md5(f"{prompt.lower().strip()}:{ans_base.lower().strip()}".encode()).hexdigest()if h not in seen:seen.add(h)think = random.choice(counsel_think_variants)32 unmodified linesq = clean_text(item.get("prompt") or item.get("instruction") or item.get("question") or "")a = clean_text(item.get("response") or item.get("output") or item.get("answer") or "")if q and a:h = hashlib.md5(f"{q.lower().strip()}:{a.lower().strip()}".encode()).hexdigest()if h not in seen_raw:seen_raw.add(h)raw_pairs.append(("custom_pair", q, a, ""))17 unmodified linesif len(en_txt) < 15 or len(hi_txt) < 10 or len(en_txt) > 300:continueh = hashlib.md5(f"{en_txt.lower().strip()}:{hi_txt.lower().strip()}".encode()).hexdigest()if h in seen_raw:continueseen_raw.add(h)22 unmodified lines("Stay curious and keep exploring new horizons every single day.", "उत्सुक रहें और हर एक दिन नए क्षितिज तलाशते रहें।", "Hamesha curious raho aur har din kuch naya explore karo.")]for en, hi, hng in curated_benchmark_pairs:h = hashlib.md5(f"{en.lower().strip()}:{hi.lower().strip()}".encode()).hexdigest()if h not in seen_raw:seen_raw.add(h)raw_pairs.append(("triplet", en, hi, hng))39 unmodified linesif pair_type == "custom_pair":q, a = item1, item2h = hashlib.md5(f"{q.lower().strip()}:{a.lower().strip()}".encode()).hexdigest()if h not in seen:seen.add(h)think = create_content_grounded_think(q, a)13 unmodified linesp = tmpl.format(s=hi)think = "1. Translation Task: Hindi -> English.\n2. Accuracy: Produce fluent, idiomatic English phrasing."r = enh = hashlib.md5(f"{p.lower().strip()}:{r.lower().strip()}".encode()).hexdigest()if h not in seen:seen.add(h)ex = build_direct_example(p, think, r)23 unmodified linesthink = "1. Translation Task: Hindi -> English.\n2. Fidelity: Accurate and clear English."r = enh = hashlib.md5(f"{p.lower().strip()}:{r.lower().strip()}".encode()).hexdigest()if h not in seen:seen.add(h)ex = build_direct_example(p, think, r)36 unmodified linesif len(ans) < 3 or len(ctx) < 50:continueh = hashlib.md5(f"{q.lower().strip()}:{ans.lower().strip()}".encode()).hexdigest()if h in seen:continueseen.add(h)13 unmodified linesprint(f" ⚠️ Could not load SQuAD dataset: {e}")# 2. Live Tool Search & Verified Retrieval Patternscities = ["Mumbai", "Delhi", "Bengaluru", "Kolkata", "Chennai", "Hyderabad", "London", "Tokyo", "New York", "Pune", "Ahmedabad", "Jaipur"]sports_teams = [("India", "Australia"), ("England", "South Africa"), ("Mumbai Indians", "CSK"), ("Real Madrid", "Barcelona"), ("Kolkata Knight Riders", "RCB")]tech_gadgets = ["H200 Tensor Core GPU", "ViuAI 500M Neural Architecture", "Llama 3 8B", "PyTorch 2.4 Distributed", "Apple M4 Max Chip", "NVIDIA Blackwell B200"]attempts = 0while len(examples) < target_count and attempts < 30000:attempts += 1cat = attempts % 4if cat == 0:city = random.choice(cities)u_q = f"What is the current weather update for {city} today?"sq = f"current weather live report {city}"res = f"[Live Meteorological Feed] Location: {city} | Conditions: Normal seasonal weather | Data source: Verified Meteorological Bureau."p1 = f"1. User Query: Real-time weather request for '{city}'.\n2. Tool Check: Live fluctuating condition -> trigger search query."p2 = f"3. Source Evaluation: Read feed for {city}.\n4. Formulation: Present verified update with attribution."ans = f"According to the live meteorological update for **{city}**:\n- **Status:** Clear and seasonal weather conditions.\n\n*(Data retrieved via verified meteorological search feed.)*"h = hashlib.md5(f"{u_q.lower().strip()}:{ans.lower().strip()}".encode()).hexdigest()if h not in seen:seen.add(h)ex = build_search_example(u_q, p1, sq, res, p2, ans)if ex:examples.append(ex)1 unmodified lineelif cat == 1:t1, t2 = random.choice(sports_teams)u_q = f"Can you check the latest match bulletin for {t1} vs {t2}?"sq = f"{t1} vs {t2} match update news bulletin"res = f"[Sports News Wire] {t1} vs {t2}: Official scoreboard and match highlights published by tournament committee."p1 = f"1. User Query: Sports match status for {t1} vs {t2}.\n2. Tool Check: Live sporting event -> lookup sports news feed."p2 = f"3. Data Synthesis: Parse tournament bulletin.\n4. Deliver clear match summary."ans = f"**{t1} vs {t2} Match Summary** (from official tournament feed):\n- Latest bulletin confirms the fixture is scheduled and underway according to tournament timetables."h = hashlib.md5(f"{u_q.lower().strip()}:{ans.lower().strip()}".encode()).hexdigest()if h not in seen:seen.add(h)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", "Bengaluru", "Jaipur", "Chennai", "Kolkata"])u_q = f"Aaj {g_city} me bullion market updates kya hain?"sq = f"bullion market gold silver rates today {g_city}"res = f"[Bullion Association Feed] {g_city}: Official benchmark bullion indices updated for today."p1 = f"1. User Query: Bullion rates for {g_city}.\n2. Tool Check: Daily fluctuating commodity -> lookup latest market index."p2 = f"3. Data Extraction: Review bullion association feed.\n4. Formulation: Present verified market overview."ans = f"Today's Bullion Market Overview in **{g_city}**:\n- Standard market trading is active under current daily benchmark rates.\n\n*(Note: Local jewellery making charges, taxes, and GST may vary.)*"h = hashlib.md5(f"{u_q.lower().strip()}:{ans.lower().strip()}".encode()).hexdigest()if h not in seen:seen.add(h)ex = build_search_example(u_q, p1, sq, res, p2, ans)if ex:examples.append(ex)1 unmodified lineelse:gadget = random.choice(tech_gadgets)u_q = f"What are the official architectural specifications of {gadget}?"sq = f"{gadget} official specifications architecture whitepaper"res = f"[Technical Documentation: {gadget}] Features upgraded compute units, high memory bandwidth, and optimized energy efficiency."p1 = f"1. User Query: Technical specs for {gadget}.\n2. Tool Check: Search official release documentation."p2 = f"3. Synthesis: Extract key architectural features."ans = f"Key Specifications for **{gadget}** (from official documentation):\n- **Architecture:** Next-gen high-efficiency compute architecture.\n- **Acceleration:** Upgraded high-throughput matrix compute units.\n- **Performance:** Optimized power-to-performance profile."h = hashlib.md5(f"{u_q.lower().strip()}:{ans.lower().strip()}".encode()).hexdigest()if h not in seen:seen.add(h)ex = build_search_example(u_q, p1, sq, res, p2, ans)if ex:examples.append(ex)4 unmodified lines# ==============================================================================# MODULE 4: Reasoning, Real Math (GSM8k & Orca-Math) & Coding (~15,000 Real Problems)# ==============================================================================def generate_synthetic_arithmetic(count=2500) -> list:"""Generates clean, precise multi-step and direct synthetic arithmetic examples."""examples = []seen = set()op_templates = [("Calculate {a} + {b}", "{a} + {b}", lambda a, b: a + b, "+"),("What is {a} - {b}?", "{a} - {b}", lambda a, b: a - b, "-"),("Solve {a} * {b}", "{a} * {b}", lambda a, b: a * b, "*"),("What is {a} multiplied by {b}?", "{a} * {b}", lambda a, b: a * b, "*"),("Divide {a} by {b}", "{a} / {b}", lambda a, b: a // b, "//"),("What is {a} % {b}?", "{a} % {b}", lambda a, b: a % b, "%"),("Evaluate: {a} + {b} * {c}", "{a} + {b} * {c}", lambda a, b, c: a + b * c, "mixed"),("Calculate ({a} + {b}) * {c}", "({a} + {b}) * {c}", lambda a, b, c: (a + b) * c, "mixed"),("What is {a} * {b} - {c}?", "{a} * {b} - {c}", lambda a, b, c: a * b - c, "mixed"),("Batao {a} + {b} kitna hota hai?", "{a} + {b}", lambda a, b: a + b, "+"),("{a} into {b} kitna hoga?", "{a} * {b}", lambda a, b: a * b, "*"),("Value of {a} - {b}?", "{a} - {b}", lambda a, b: a - b, "-"),]attempts = 0while len(examples) < count and attempts < count * 10:attempts += 1tmpl_desc, expr_tmpl, fn, op_type = random.choice(op_templates)if op_type == "mixed":a = random.randint(2, 50)b = random.randint(2, 30)c = random.randint(2, 20)q = tmpl_desc.format(a=a, b=b, c=c)expr = expr_tmpl.format(a=a, b=b, c=c)ans = fn(a, b, c)think = f"1. Expression to evaluate: {expr}\n2. Order of operations: Calculate according to standard precedence.\n3. Result: {expr} = {ans}"elif op_type == "//":b = random.randint(2, 25)ans = random.randint(2, 50)a = b * ansq = tmpl_desc.format(a=a, b=b)expr = expr_tmpl.format(a=a, b=b)think = f"1. Division operation: {a} / {b}\n2. Compute quotient: {a} / {b} = {ans}"else:a = random.randint(2, 500)b = random.randint(2, 500)q = tmpl_desc.format(a=a, b=b)expr = expr_tmpl.format(a=a, b=b)ans = fn(a, b)think = f"1. Direct arithmetic: {expr}\n2. Step computation: {expr} = {ans}"final = f"{expr} = **{ans}**"h = hashlib.md5(f"{q.lower().strip()}:{final.lower().strip()}".encode()).hexdigest()if h not in seen:seen.add(h)ex = build_direct_example(q, think, final)if ex:examples.append(ex)return examplesdef generate_reasoning_and_math_dataset(target_count=15000) -> list:global _current_module_key_current_module_key = "module_4"print(f"\n🧠 Module 4: Generating Reasoning, Real Math (GSM8k + Orca-Math + Synthetic) & Code (Target: {target_count})...")examples = []seen = set()# 1. Synthetic clean arithmetic injection (2,500 targeted examples)print(" 🔢 Generating 2,500 targeted clean arithmetic & arithmetic reasoning examples...")synth_math = generate_synthetic_arithmetic(2500)for ex in synth_math:examples.append(ex)print(f" ✅ Added {len(synth_math)} synthetic arithmetic examples!")# 2. 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) >= int(target_count * 0.55):breakq = item["question"].strip()a = item["answer"].strip()parts = a.split("####")if len(parts) == 2:raw_rationale = parts[0].strip()15 unmodified linesthink = f"Step-by-Step Reasoning:\n{clean_a}"final = clean_ah = hashlib.md5(f"{q.lower().strip()}:{final.lower().strip()}".encode()).hexdigest()if h in seen:continueseen.add(h)ex = build_direct_example(q, think, final)if ex:examples.append(ex)print(f" ✅ Total math problems loaded so far: {len(examples)} (calculator tags cleanly stripped)!")except Exception as e:print(f" ⚠️ Could not load GSM8k: {e}")# 3. 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")orca_cap = max(1, int(target_count * 0.90))for item in tqdm(orca_math, desc="Parsing Orca Math"):if len(examples) >= orca_cap:break3 unmodified linesif len(q_math) < 10 or len(a_math) < 10 or len(a_math) > 1500:continuethink = f"Step-by-Step Problem Solving & Deduction:\n{a_math}"concise_conclusion = extract_concise_math_conclusion(a_math)5 unmodified linesf"Thus, {concise_conclusion}"])final = fmth = hashlib.md5(f"{q_math.lower().strip()}:{final.lower().strip()}".encode()).hexdigest()if h in seen:continueseen.add(h)ex = build_direct_example(q_math, think, final)if ex:examples.append(ex)29 unmodified linescontinueq = f"{inst}\n\nInput:\n{inp}" if inp else insth = hashlib.md5(f"{q.lower().strip()}:{out.lower().strip()}".encode()).hexdigest()if h in seen:continueseen.add(h)10 unmodified linesreturn examples[:target_count]# ==============================================================================# MODULE 6: Identity & Persona Alignment (~400-800 Examples) - Expanded 60+ Scenarios# ==============================================================================def generate_identity_dataset(target_count=600) -> list:global _current_module_key_current_module_key = "module_6"print(f"\n🏷️ Module 6: Generating Identity (Model: Sarus | Created by: ViuAI) Alignment (Target: {target_count})...")63 unmodified linesf"1. Direct name confirmation.\n2. State '{MODEL_NAME}'."),("Who is behind ViuAI?",f"**{CREATOR}** is the AI research and engineering organization that created and trained me, **{MODEL_NAME}**.",f"1. Organization background.\n2. Explain '{CREATOR}' relationship."),("Who made you?",f"I was made and engineered by **{CREATOR}**.",f"1. Creator inquiry.\n2. Direct statement of '{CREATOR}'."),("Are you Llama or trained by Meta?",f"No, I am not Meta's Llama. I am **{MODEL_NAME}**, developed by **{CREATOR}**.",f"1. Disambiguate Meta/Llama.\n2. Affirm '{MODEL_NAME}' by '{CREATOR}'."),("Tumhara founder kaun hai?",f"Mujhe **{CREATOR}** ki engineering team ne develop kiya hai.",f"1. Founder inquiry in Hindi.\n2. Clarify '{CREATOR}' development team."),("What is the name of this AI?",f"This AI is called **{MODEL_NAME}**, crafted by **{CREATOR}**.",f"1. Model name inquiry.\n2. Clearly state '{MODEL_NAME}' by '{CREATOR}'."),("Can I call you Sarus?",f"Yes, absolutely! **{MODEL_NAME}** is my official name, and you can call me Sarus anytime.",f"1. Name verification.\n2. Confirm warmly."),("Tumhe kis company ne train kiya hai?",f"Mujhe **{CREATOR}** ne train kiya hai. Mera naam **{MODEL_NAME}** hai.",f"1. Company origin query in Hindi.\n2. Attribute to '{CREATOR}'."),("Are you an OpenAI model?",f"No, I have no affiliation with OpenAI. I am **{MODEL_NAME}**, independently created by **{CREATOR}**.",f"1. Competitor clarification.\n2. Affirm independent creation by '{CREATOR}'."),("What is your developer's name?",f"My developer is **{CREATOR}**.",f"1. Developer query.\n2. Direct answer '{CREATOR}'."),("Kya tum dost ban sakte ho?",f"Bilkul! Main **{MODEL_NAME}** hoon, aur main hamesha aapka ek achha aur loyal dost ban kar help karunga.",f"1. Friendship request in Hindi.\n2. Warm acceptance affirming persona."),("Who is the creator of Sarus?",f"The creator of **{MODEL_NAME}** is **{CREATOR}**.",f"1. Direct creator inquiry.\n2. Clear attribution to '{CREATOR}'.")]prefixes = ["Hey, ", "Hello! ", "Excuse me, ", "Quick question: ", "Batao, ","Can you clarify: ", "Please tell me, ", "Suno, ", "Sir, ", "Dost, ","Ek baat batao, ", "Just wondering, ", "Hi there! ", "Sarus bhai, ","Can you please tell me: ", "Aap kaun hain: ", ""]attempts = 0while len(examples) < target_count and attempts < 15000:attempts += 1q_base, ans, think = random.choice(identity_scenarios)prefix = random.choice(prefixes)prompt = f"{prefix}{q_base}".strip()h = hashlib.md5(f"{prompt.lower().strip()}:{ans.lower().strip()}".encode()).hexdigest()if h not in seen:seen.add(h)ex = build_direct_example(prompt, think, ans)20 unmodified linesm3 = generate_grounded_rag_dataset(12000)m4 = generate_reasoning_and_math_dataset(15000)m5 = generate_general_instruct_dataset(12500)m6 = generate_identity_dataset(600)# Assertions to guarantee valid dataset extraction across all modulesassert len(m1) > 0, "Module 1 failed to generate any examples!"assert len(train_m2) > 0 and len(val_m2) > 0, "Module 2 failed to generate train/val examples!"assert len(m3) > 0, "Module 3 failed to generate RAG/Search examples!"assert len(m4) > 0, "Module 4 failed to generate Math/Reasoning examples!"assert len(m5) > 0, "Module 5 failed to generate General Instruct examples!"assert len(m6) > 0, "Module 6 failed to generate Identity examples!"other_examples = m1 + m3 + m4 + m5 + m6print(f"\n📊 Total Other Raw Examples Generated: {len(other_examples):,}")
code/build_sft_data_v7.py+195-66