Upload code/build_sft_v17_dataset.py with huggingface_hub
Browse files123456789101112131415161764 unmodified lines8283848586878824 unmodified lines1131141151161171181192 unmodified lines12212312412512612712812913013113213313413513613713813931 unmodified lines171172173174175176177195 unmodified lines373374375376377378379116 unmodified lines4964974984995005015026 unmodified lines50951051151251351451532 unmodified lines54854955055155255355421 unmodified lines57657757857958058158258358458524 unmodified lines61061161261361461561611 unmodified lines62862963063163263363463563663763863919 unmodified lines6596606616626636646656 unmodified lines67267367467567667767817 unmodified lines6966976986997007017026 unmodified lines70971071171271371471528 unmodified lines74474574674774874975075175275375475575675775875976076176276376476576676776876934 unmodified lines804805806807808809810811812813# ==============================================================================# 🚀 ViuAI Sarus-500M — SFT v17 Grand Master Dataset Builder (~150k Scale)# ==============================================================================# KEY UPGRADES & COMPLETE DATA INGESTION:# 1. 🏛️ HINDI GK & POLITY: Powered by 'FreedomIntelligence/alpaca-gpt4-hindi' (49.9k) + Indian GK Anchors.# 2. 🗺️ EXACT CATEGORY MAPPING: Full utilization of export_all_v1.json across all 7 mapped domains.# 3. 🎯 JSON & STRICT CONSTRAINT FOLLOWING: Structured JSON extraction, bullet constraints, word limits.# 4. 📄 SUMMARIZATION & KEY EXTRACTION: Paragraph-to-bullets, meeting action items extraction.# 5. 🚫 ANTI-HALLUCINATION & FALSE-PREMISE CALIBRATION: Accurate correction of fake/impossible premises.# 6. 📚 NCERT GENERAL SCIENCE (Class 6-10): Physics, Chemistry, Biology in simple Hindi & English.# 7. 🎨 CREATIVE, FESTIVE & SOCIAL WRITING: Indian festival wishes, captions, inspirational shayaris.# 8. 🔄 ALL-DOMAIN MULTI-TURN (20-25%): Interactive follow-ups across ALL 10 topics.# 9. 🛡️ TYPO ROBUSTNESS (English & Hinglish): Fast-typing mistakes, dropped vowels ('kro', 'btao').# 10. 🚫 ZERO TRUNCATION: Entire overlong samples (>2048) are cleanly skipped to preserve 100% fidelity.# ==============================================================================import os64 unmodified linesprint("=" * 85)print(f"🚀 ViuAI Sarus-500M — SFT {VERSION.upper()} Super Master Dataset Builder ({TOTAL_PLANNED:,} Scale)")print(f" ⚖️ High-Density Multi-Domain Ingestion | Multi-Turn | Typo-Immune | Zero Broken Sequences")print("=" * 85)24 unmodified lines# ------------------------------------------------------------------------------# 2. Typo-Robustness Generator (English & Hinglish Only)# ------------------------------------------------------------------------------KEYBOARD_ADJACENT = {'q': 'w', 'w': 'e', 'e': 'r', 'r': 't', 't': 'y', 'y': 'u', 'u': 'i', 'i': 'o', 'o': 'p',2 unmodified lines}HINGLISH_ABBREVIATIONS = {"karo": "kro","batao": "btao","kaise": "kse","kya": "kyaa","bhai": "bhaii","theek": "thik","achha": "acha","please": "plz","thanks": "thx","because": "bcoz","you": "u","are": "r"}def inject_realistic_typos(text: str, typo_prob: float = 0.15) -> str:31 unmodified lines# ------------------------------------------------------------------------------# 3. High-Impact Anchor Packs (JSON, NCERT, Summarization, Anti-Hallucination, Creative)# ------------------------------------------------------------------------------def get_json_and_constraints_pack():195 unmodified lines# ------------------------------------------------------------------------------# 4. Multi-Turn Conversation Packs (All 10 Domains)# ------------------------------------------------------------------------------def get_all_domain_multi_turn_pack():multi_turn_data = [116 unmodified lines# ------------------------------------------------------------------------------# 5. Cloud Raw Data Fetcher & Sanitizer# ------------------------------------------------------------------------------def sanitize_gsm8k_answer(ans_str: str) -> tuple[str, str]:if "####" in ans_str:6 unmodified linesclean_steps = re.sub(r"<<.*?>>", "", steps_part).strip()clean_steps = re.sub(r"(?i)\n*(?:The answer is:?|Final Answer:?)\s*.*$", "", clean_steps).strip()thinking = "Step-by-step mathematical reasoning. Calculate accurately and state final answer."response = f"{clean_steps}\n\n**Final Answer:** {final_val}" if final_val else clean_stepsreturn thinking, response32 unmodified lines# ------------------------------------------------------------------------------# 6. Build Master Pool with High-Density Ingestion# ------------------------------------------------------------------------------def build_master_pool():raw_dir = resolve_or_download_raw_data_dir()21 unmodified lines# Inject Typo Robustness to ~15% of English/Hinglish instructionsaug_inst = inject_realistic_typos(inst_clean, typo_prob=0.15)domain_pools[domain].append({"instruction": aug_inst,"thinking": th.strip() if th else "Helpful, clear response.","response": resp_clean,"domain": domain})24 unmodified linesfor row in id_data:if len(domain_pools["identity_greetings"]) >= DOMAIN_TARGET_CAPS["identity_greetings"]:breakadd_sample("identity_greetings", row.get("instruction", ""), row.get("thinking", "Identify as Sarus created by ViuAI, friendly and warm persona."), row.get("response", ""))print(f" ✅ [identity_greetings] : {len(domain_pools['identity_greetings']):,} loaded")# 2. Coding from CodeAlpaca11 unmodified linesif inp:inst = f"{inst}\nInput: {inp}"if inst and out:add_sample("coding_tech", inst, "Analyze programming task. Write clean, working, idiomatic code with edge-case handling.", out)print(f" ✅ [coding_tech] : {len(domain_pools['coding_tech']):,} loaded")except Exception as e:print(f" ⚠️ CodeAlpaca error: {e}")# 3. Hindi GK & Polity from FreedomIntelligence/alpaca-gpt4-hindi (49.9k samples)print(f" ⬇️ Ingesting Hindi GK & Instruction dataset...")try:hindi_gk = load_dataset("FreedomIntelligence/alpaca-gpt4-hindi", split="train")19 unmodified linesinst = f"{inst}\n{inp}"if inst and out and len(inst) > 4 and len(out) > 4:add_sample("gk_polity_history", inst, "General knowledge and conceptual explanation in Hindi.", out)print(f" ✅ [gk_polity_history] : {len(domain_pools['gk_polity_history']):,} loaded")except Exception as e:print(f" ⚠️ Hindi GK loading error: {e}")6 unmodified linesfor row in math_data:if len(domain_pools["math_logic"]) >= DOMAIN_TARGET_CAPS["math_logic"]:breakadd_sample("math_logic", row.get("instruction", ""), row.get("thinking", "Mathematical analysis and logical step calculation."), row.get("response", ""))try:gsm = load_dataset("openai/gsm8k", "main", split="train")17 unmodified linesfor row in reason_data:if len(domain_pools["reasoning_domain"]) >= DOMAIN_TARGET_CAPS["reasoning_domain"]:breakadd_sample("reasoning_domain", row.get("instruction", ""), row.get("thinking", "Logical reasoning and step-by-step premise deduction."), row.get("response", ""))# 6. Authentic Chit-Chatcc_path = os.path.join(raw_dir, "final_viuai_dataset_chit_chat.json")6 unmodified linesresp = row.get("response", "")if "mom" in resp.lower():continueadd_sample("empathetic_chitchat", row.get("instruction", ""), row.get("thinking", "Helpful, natural conversational check-in."), resp)# 7. Complete Export All Ingestion with Exact Category Mappingprint(f" ⬇️ Ingesting from export_all_v1.json across mapped categories...")28 unmodified linesif cat in cat_to_dom:target_dom = cat_to_dom[cat]if len(domain_pools[target_dom]) < DOMAIN_TARGET_CAPS[target_dom]:add_sample(target_dom, inst, th or f"Clear and helpful response for {cat}.", resp)# Final Strategic Truncationmaster_pool = []print("\n--- Final Strategic Cognitive Domain Distribution ---")for d, items in domain_pools.items():random.shuffle(items)cap = DOMAIN_TARGET_CAPS.get(d, 17000)final_items = items[:cap]domain_pools[d] = final_itemsmaster_pool.extend(final_items)pct = (len(final_items) / max(1, len(master_pool) or 1)) * 100print(f" • {d:<25}: {len(final_items):>6,} samples")print(f"\n🎉 Total Strategic Master Pool: {len(master_pool):,} Samples!")return master_pool# ------------------------------------------------------------------------------# 7. Stratified Split, Multi-Turn Tokenization & Masked Packing# ------------------------------------------------------------------------------def tokenize_and_pack(master_pool, start_time):print("\n⚡ Tokenizing & Packing Dataset (Multi-Turn Loss Masking & Typo-Immune)...")34 unmodified lineslabels = []for u_msg, th, a_msg in item["conversations"]:u_str = f"<|user|>\n{u_msg.strip()}<|endofturn|>\n"if th.strip():a_str = f"<|assistant|>\n[THINK]\n{th.strip()}\n[/THINK]\n{a_msg.strip()}<|endofturn|>\n"else:a_str = f"<|assistant|>\n{a_msg.strip()}<|endofturn|>\n"u_ids = tokenizer.encode(u_str).idsa_ids = tokenizer.encode(a_str).ids123456789101112131415161764 unmodified lines8283848586878824 unmodified lines1131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921932 unmodified lines19619719819920020120220320431 unmodified lines236237238239240241242195 unmodified lines438439440441442443444116 unmodified lines5615625635645655665676 unmodified lines57457557657757857958032 unmodified lines61361461561661761861921 unmodified lines64164264364464564664764864965065124 unmodified lines67667767867968068168211 unmodified lines69469569669769869970070170270370470519 unmodified lines7257267277287297307316 unmodified lines73873974074174274374417 unmodified lines7627637647657667677686 unmodified lines77577677777877978078128 unmodified lines81081181281381481581681781881982082182282382482582682782882983083183283383483534 unmodified lines870871872873874875876877# ==============================================================================# 🚀 ViuAI Sarus-500M — SFT v17 Super Master Dataset Builder (150k Scale)# ==============================================================================# KEY UPGRADES & COMPLETE DYNAMIC REASONING ENGINE:# 1. 🧠 DYNAMIC THINKING ENGINE: 50+ diverse, task-specific thinking variations per domain to prevent memorization/ratta.# 2. ⚖️ 100% STRICT UNIFORM BALANCE: All 9 core domains capped at ~16,500, Identity capped at ~2,500 (~151k Total).# 3. 🏛️ HINDI GK & POLITY: Powered by 'FreedomIntelligence/alpaca-gpt4-hindi' (49.8k clean parsed samples).# 4. 🗺️ EXACT CATEGORY MAPPING: Full utilization of export_all_v1.json across all mapped categories.# 5. 🎯 JSON & STRICT CONSTRAINT FOLLOWING: Structured JSON extraction, bullet constraints, word limits.# 6. 📄 SUMMARIZATION & KEY EXTRACTION: Paragraph-to-bullets, meeting action items extraction.# 7. 🚫 ANTI-HALLUCINATION & FALSE-PREMISE CALIBRATION: Accurate correction of fake/impossible premises.# 8. 📚 NCERT GENERAL SCIENCE (Class 6-10): Physics, Chemistry, Biology in simple Hindi & English.# 9. 🔄 ALL-DOMAIN MULTI-TURN: Interactive follow-ups across ALL 10 topics with Zero-Truncation.# 10. 🛡️ TYPO ROBUSTNESS (English & Hinglish): Fast-typing mistakes, dropped vowels ('kro', 'btao').# ==============================================================================import os64 unmodified linesprint("=" * 85)print(f"🚀 ViuAI Sarus-500M — SFT {VERSION.upper()} Super Master Dataset Builder ({TOTAL_PLANNED:,} Scale)")print(f" ⚖️ 100% Strict Equal Balance | Dynamic Thinking Engine (Anti-Ratta) | Zero Broken Sequences")print("=" * 85)24 unmodified lines# ------------------------------------------------------------------------------# 2. Dynamic Thinking Engine (Anti-Memorization & Adaptive Reasoning)# ------------------------------------------------------------------------------THINKING_TEMPLATES = {"translation_multilingual": ["Direct 1-to-1 parallel language translation. Maintain exact grammatical agreement and natural phrasing.","Analyze source sentence structure and produce accurate, idiomatic translation without adding commentary.","Identify core meaning and translate with high fidelity to the target language tone.","Ensure vocabulary precision and preserve the original context across languages."],"math_logic": ["Read mathematical constraints carefully, identify known variables, and calculate step-by-step.","Apply unitary and arithmetic principles: compute unit values and arrive at the exact final answer.","Deconstruct word problem into logical operations, solve intermediate values, and verify accuracy.","Formulate step-by-step mathematical reasoning and clearly state the final numerical result."],"coding_tech": ["Analyze programming requirements. Implement clean, idiomatic code with optimal time complexity and edge cases.","Understand function logic, choose appropriate data structures, and provide clear working implementation.","Write modular, readable code handling edge cases with explanatory comments.","Break down technical problem, implement correct algorithmic solution, and ensure syntax correctness."],"reasoning_domain": ["Analyze given premises and constraints. Deduce logically step-by-step to arrive at the sound conclusion.","Evaluate relationships and logical conditions carefully without making unstated assumptions.","Follow deductive reasoning path from evidence to valid deduction.","Identify key logical rules, eliminate contradictions, and establish the definitive answer."],"gk_polity_history": ["Recall verifiable factual details, historical context, and constitutional provisions in clear language.","Structure factual response clearly with dates, key figures, and core principles.","Provide accurate, factual, and informative explanation based on authentic knowledge.","Explain historical and general knowledge concepts clearly and concisely."],"career_productivity": ["Format workplace communication professionally with clear purpose, structured tone, and actionable steps.","Organize response logically with professional etiquette, brevity, and structured clarity.","Extract key action items, deadlines, or draft clear professional text meeting all constraints.","Adhere to formatting constraints and provide a polished, executive-ready response."],"recipes_indian_utility": ["Authentic Indian kitchen cooking technique with exact ingredients, preparation steps, and heat control.","Detail step-by-step traditional culinary process ensuring authentic flavors and safety tips.","Provide practical, easy-to-follow cooking instructions with ingredient proportions.","Explain cooking method clearly, highlighting key timing and flavor enhancements."],"finance_health_wellness": ["Provide practical, well-balanced wellness and financial guidance focused on daily healthy habits.","Explain health, nutrition, or financial principles clearly with practical daily precautions.","Offer informative, actionable guidance promoting balanced lifestyle and financial awareness.","Structure health and wellness advice with clear, practical steps and sensible precautions."],"empathetic_chitchat": ["Friendly and helpful social response. Respond with warmth, natural tone, and positive engagement.","Polite conversational check-in. Keep response crisp, supportive, and engaging.","Engage naturally with casual friendly tone and assist with user inquiry.","Acknowledge user warmly with crisp, helpful, and natural conversational reply."],"identity_greetings": ["Identify as Sarus, created by ViuAI. Respond warmly, politely, and ask how to assist.","Polite identity acknowledgement as ViuAI Sarus. Offer ready assistance across tasks.","Friendly greeting with authentic Sarus persona, ready to support the user."]}def generate_dynamic_thinking(domain: str, existing_th: str = "") -> str:"""Selects dynamic, context-rich thinking to ensure the model never learns repetitive static patterns."""if existing_th and len(existing_th) > 10 and not any(k in existing_th for k in ["General knowledge", "Helpful response", "Step-by-step"]):return existing_th.strip()templates = THINKING_TEMPLATES.get(domain, THINKING_TEMPLATES["empathetic_chitchat"])return random.choice(templates)# ------------------------------------------------------------------------------# 3. Typo-Robustness Generator (English & Hinglish Only)# ------------------------------------------------------------------------------KEYBOARD_ADJACENT = {'q': 'w', 'w': 'e', 'e': 'r', 'r': 't', 't': 'y', 'y': 'u', 'u': 'i', 'i': 'o', 'o': 'p',2 unmodified lines}HINGLISH_ABBREVIATIONS = {"karo": "kro", "batao": "btao", "kaise": "kse", "kya": "kyaa","bhai": "bhaii", "theek": "thik", "achha": "acha", "please": "plz","thanks": "thx", "because": "bcoz", "you": "u", "are": "r"}def inject_realistic_typos(text: str, typo_prob: float = 0.15) -> str:31 unmodified lines# ------------------------------------------------------------------------------# 4. Core Capability Anchor Packs (JSON, NCERT, Summarization, Anti-Hallucination, Creative)# ------------------------------------------------------------------------------def get_json_and_constraints_pack():195 unmodified lines# ------------------------------------------------------------------------------# 5. Multi-Turn Conversation Packs (All 10 Domains)# ------------------------------------------------------------------------------def get_all_domain_multi_turn_pack():multi_turn_data = [116 unmodified lines# ------------------------------------------------------------------------------# 6. Cloud Raw Data Fetcher & Sanitizer# ------------------------------------------------------------------------------def sanitize_gsm8k_answer(ans_str: str) -> tuple[str, str]:if "####" in ans_str:6 unmodified linesclean_steps = re.sub(r"<<.*?>>", "", steps_part).strip()clean_steps = re.sub(r"(?i)\n*(?:The answer is:?|Final Answer:?)\s*.*$", "", clean_steps).strip()thinking = generate_dynamic_thinking("math_logic")response = f"{clean_steps}\n\n**Final Answer:** {final_val}" if final_val else clean_stepsreturn thinking, response32 unmodified lines# ------------------------------------------------------------------------------# 7. Build Master Pool with High-Density Ingestion# ------------------------------------------------------------------------------def build_master_pool():raw_dir = resolve_or_download_raw_data_dir()21 unmodified lines# Inject Typo Robustness to ~15% of English/Hinglish instructionsaug_inst = inject_realistic_typos(inst_clean, typo_prob=0.15)dyn_th = generate_dynamic_thinking(domain, th)domain_pools[domain].append({"instruction": aug_inst,"thinking": dyn_th,"response": resp_clean,"domain": domain})24 unmodified linesfor row in id_data:if len(domain_pools["identity_greetings"]) >= DOMAIN_TARGET_CAPS["identity_greetings"]:breakadd_sample("identity_greetings", row.get("instruction", ""), row.get("thinking", ""), row.get("response", ""))print(f" ✅ [identity_greetings] : {len(domain_pools['identity_greetings']):,} loaded")# 2. Coding from CodeAlpaca11 unmodified linesif inp:inst = f"{inst}\nInput: {inp}"if inst and out:add_sample("coding_tech", inst, "", out)print(f" ✅ [coding_tech] : {len(domain_pools['coding_tech']):,} loaded")except Exception as e:print(f" ⚠️ CodeAlpaca error: {e}")# 3. Hindi GK & Polity from FreedomIntelligence/alpaca-gpt4-hindi (49.8k samples)print(f" ⬇️ Ingesting Hindi GK & Instruction dataset...")try:hindi_gk = load_dataset("FreedomIntelligence/alpaca-gpt4-hindi", split="train")19 unmodified linesinst = f"{inst}\n{inp}"if inst and out and len(inst) > 4 and len(out) > 4:add_sample("gk_polity_history", inst, "", out)print(f" ✅ [gk_polity_history] : {len(domain_pools['gk_polity_history']):,} loaded")except Exception as e:print(f" ⚠️ Hindi GK loading error: {e}")6 unmodified linesfor row in math_data:if len(domain_pools["math_logic"]) >= DOMAIN_TARGET_CAPS["math_logic"]:breakadd_sample("math_logic", row.get("instruction", ""), "", row.get("response", ""))try:gsm = load_dataset("openai/gsm8k", "main", split="train")17 unmodified linesfor row in reason_data:if len(domain_pools["reasoning_domain"]) >= DOMAIN_TARGET_CAPS["reasoning_domain"]:breakadd_sample("reasoning_domain", row.get("instruction", ""), "", row.get("response", ""))# 6. Authentic Chit-Chatcc_path = os.path.join(raw_dir, "final_viuai_dataset_chit_chat.json")6 unmodified linesresp = row.get("response", "")if "mom" in resp.lower():continueadd_sample("empathetic_chitchat", row.get("instruction", ""), "", resp)# 7. Complete Export All Ingestion with Exact Category Mappingprint(f" ⬇️ Ingesting from export_all_v1.json across mapped categories...")28 unmodified linesif cat in cat_to_dom:target_dom = cat_to_dom[cat]if len(domain_pools[target_dom]) < DOMAIN_TARGET_CAPS[target_dom]:add_sample(target_dom, inst, th, resp)# Final Strict Truncationmaster_pool = []print("\n--- Final Strictly Balanced Equal-Share Domain Distribution ---")for d, items in domain_pools.items():random.shuffle(items)cap = DOMAIN_TARGET_CAPS.get(d, UNIFORM_DOMAIN_CAP)final_items = items[:cap]domain_pools[d] = final_itemsmaster_pool.extend(final_items)pct = (len(final_items) / max(1, TOTAL_PLANNED)) * 100print(f" • {d:<25}: {len(final_items):>6,} samples ({pct:.1f}%)")print(f"\n🎉 Total Strictly Balanced Master Pool: {len(master_pool):,} Samples!")return master_pool# ------------------------------------------------------------------------------# 8. Stratified Split, Multi-Turn Tokenization & Masked Packing# ------------------------------------------------------------------------------def tokenize_and_pack(master_pool, start_time):print("\n⚡ Tokenizing & Packing Dataset (Multi-Turn Loss Masking & Typo-Immune)...")34 unmodified lineslabels = []for u_msg, th, a_msg in item["conversations"]:u_str = f"<|user|>\n{u_msg.strip()}<|endofturn|>\n"dyn_th = generate_dynamic_thinking(item["domain"], th)a_str = f"<|assistant|>\n[THINK]\n{dyn_th}\n[/THINK]\n{a_msg.strip()}<|endofturn|>\n"u_ids = tokenizer.encode(u_str).idsa_ids = tokenizer.encode(a_str).ids
code/build_sft_v17_dataset.py+115-51