Upload code/build_sft_v17_dataset.py with huggingface_hub
Browse files1234567891011121314151620 unmodified lines37383940414243444546474849505152535423 unmodified lines7879808182838448 unmodified lines13313413513613713813932 unmodified lines17217317417517617717842 unmodified lines22122222322422522622719 unmodified lines24724824925025125225322 unmodified lines27627727827928028128244 unmodified lines327328329330331332333216 unmodified lines55055155255355455555648 unmodified lines6056066076086096106113 unmodified lines61561661761861962062162262362462562662762862963063163263363414 unmodified lines6496506516526536546556562 unmodified lines6596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237244 unmodified lines72973073173273373473573654 unmodified lines791792793794795796797# ==============================================================================# 🚀 ViuAI Sarus-500M — SFT v17 Grand Master Dataset Builder (150k+ Scale)# ==============================================================================# KEY UPGRADES IN THIS EXPANDED MASTER VERSION:# 1. 🎯 JSON & STRICT CONSTRAINT FOLLOWING: Structured JSON extraction, bullet constraints, word limits.# 2. 📄 SUMMARIZATION & KEY EXTRACTION: Paragraph-to-bullets, meeting action items extraction.# 3. 🚫 ANTI-HALLUCINATION & FALSE-PREMISE CALIBRATION: Accurate correction of fake/impossible premises.# 4. 📚 NCERT GENERAL SCIENCE (Class 6-10): Physics, Chemistry, Biology in simple Hindi & English.# 5. 🎨 CREATIVE, FESTIVE & SOCIAL WRITING: Indian festival wishes, captions, inspirational shayaris.# 6. 🔄 ALL-DOMAIN MULTI-TURN (20-25%): Interactive follow-ups across ALL 10 topics.# 7. 🛡️ TYPO ROBUSTNESS (English & Hinglish): Mobile fast-typing mistakes, dropped vowels ('kro', 'btao').# 8. ⚖️ 100% STRICT UNIFORM BALANCE: All 9 core domains capped at ~16,500, Identity capped at ~3,500.# 9. 💾 32-BIT FUTURE PROOFING: Saved as np.int32 tokens/labels to prevent overflow.# ==============================================================================import os20 unmodified linesVAL_RATIO = 0.02SEED = 42# Strategic Target Caps tailored for 500M SLM (~164k Total Scale)DOMAIN_TARGET_CAPS = {"coding_tech": 18500, # High syntax complexity & algorithms (+2k boost)"math_logic": 18500, # Step-by-step arithmetic reasoning (+2k boost)"reasoning_domain": 18500, # Logic puzzles & anti-hallucination (+2k boost)"empathetic_chitchat": 18500, # Conversational Hinglish & creative (+2k boost)"gk_polity_history": 18500, # Samvaad + NCERT Science + Modern GK (+2k boost)"career_productivity": 17000, # Workplace, Summarization & JSON (+500 boost)"recipes_indian_utility": 17000, # Indian kitchen & cooking (+500 boost)"finance_health_wellness": 17000,# Daily health & finance (+500 boost)"translation_multilingual": 17000,# 1-to-1 parallel translation (+500 boost)"identity_greetings": 3500 # Pure ViuAI Sarus persona anchors}random.seed(SEED)23 unmodified linesprint("=" * 85)print(f"🚀 ViuAI Sarus-500M — SFT {VERSION.upper()} Super Master Dataset Builder ({TOTAL_PLANNED:,} Scale)")print(f" ⚖️ Strategic Cognitive Balance | Coding: 18.5k | Math: 18.5k | Reasoning: 18.5k | NCERT & JSON")print("=" * 85)48 unmodified lines}def inject_realistic_typos(text: str, typo_prob: float = 0.15) -> str:"""Injects realistic mobile typing typos, dropped vowels, and keyboard slips for English/Hinglish."""if random.random() > typo_prob or len(text) < 10:return text32 unmodified lines# ------------------------------------------------------------------------------def get_json_and_constraints_pack():"""Pack 1: Strict JSON Schema Extraction and Constraint Adherence."""samples = [("Extract candidate details from this text into clean JSON format: 'Rahul Sharma is a 28-year old Software Engineer based in Bengaluru with 5 years experience in Python and Docker. Email: rahul.sharma@example.com'",42 unmodified linesdef get_summarization_and_extraction_pack():"""Pack 2: Summarization and Key Entity Extraction."""samples = [("Summarize the following text in 2 concise sentences:\n\n'Renewable energy sources such as solar and wind power are growing rapidly across India. Solar installations have witnessed exponential adoption due to falling panel prices and government subsidies. Meanwhile, wind energy capacity in coastal regions continues to supply clean power to the national grid, reducing reliance on coal-based thermal power plants.'",19 unmodified linesdef get_anti_hallucination_pack():"""Pack 3: Anti-Hallucination & False Premise Calibration."""samples = [("Who was the 55th President of the United States?",22 unmodified linesdef get_ncert_science_pack():"""Pack 4: NCERT Basic School Science (Classes 6-10)."""samples = [("Photosynthesis (Prakash Sanshleshan) kya hai aur iska basic chemical formula kya hai?",44 unmodified linesdef get_creative_and_cultural_pack():"""Pack 5: Indian Festivals, Wishes, Shayari, and Captions."""samples = [("Diwali par dosto aur parivar ko bhejne ke liye ek warm aur sundar Hindi wish likho.",216 unmodified lines# ------------------------------------------------------------------------------# 6. Build Strictly Balanced Mega Pool with All Capabilities# ------------------------------------------------------------------------------def build_master_pool():raw_dir = resolve_or_download_raw_data_dir()48 unmodified linesfor item in get_zero_overthinking_greetings_pack():add_sample(item["domain"], item["instruction"], item["thinking"], item["response"])# 1. Identity Ingestion (~3,500 capped)id_path = os.path.join(raw_dir, "final_viuai_dataset_identity.json")with open(id_path, "r", encoding="utf-8") as f:id_data = json.load(f)3 unmodified linesadd_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. Authentic Chit-Chatcc_path = os.path.join(raw_dir, "final_viuai_dataset_chit_chat.json")with open(cc_path, "r", encoding="utf-8") as f:cc_data = json.load(f)random.shuffle(cc_data)for row in cc_data:if len(domain_pools["empathetic_chitchat"]) >= DOMAIN_TARGET_CAPS["empathetic_chitchat"]:breakresp = row.get("response", "")if "mom" in resp.lower():continueadd_sample("empathetic_chitchat", row.get("instruction", ""), row.get("thinking", "Helpful, natural conversational check-in."), resp)# 3. Authentic Math Domain + GSM8Kmath_path = os.path.join(raw_dir, "final_viuai_dataset_math_domain.json")with open(math_path, "r", encoding="utf-8") as f:math_data = json.load(f)14 unmodified linesadd_sample("math_logic", q, th, clean_resp)except Exception as e:print(f" ⚠️ GSM8K error: {e}")# 4. Authentic Reasoning Domainreason_path = os.path.join(raw_dir, "final_viuai_dataset_reasoning_domain.json")with open(reason_path, "r", encoding="utf-8") as f:reason_data = json.load(f)2 unmodified linesbreakadd_sample("reasoning_domain", row.get("instruction", ""), row.get("thinking", "Logical reasoning and step-by-step premise deduction."), row.get("response", ""))# 5. Coding from CodeAlpacatry:code_ds = load_dataset("sahil2801/CodeAlpaca-20k", split="train")code_samples = list(code_ds)random.shuffle(code_samples)for r in code_samples:if len(domain_pools["coding_tech"]) >= DOMAIN_TARGET_CAPS["coding_tech"]:breakinst = r.get("instruction", "").strip()inp = r.get("input", "").strip()out = r.get("output", "").strip()if 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)except Exception as e:print(f" ⚠️ CodeAlpaca error: {e}")# 6. GK from Samvaadtry:samvaad = load_dataset("gairik/samvaad-hi-v1", split="train")for r in samvaad:if len(domain_pools["gk_polity_history"]) >= DOMAIN_TARGET_CAPS["gk_polity_history"]:breakinst = r.get("instruction", "").strip()out = r.get("output", "").strip()if inst and out and len(inst) > 5 and len(out) > 5:add_sample("gk_polity_history", inst, "Analyze general knowledge in clean Hindi, provide factual and accurate response.", out)except Exception as e:print(f" ⚠️ Samvaad error: {e}")# 7. Export All Stratified Ingestionexport_path = os.path.join(raw_dir, "export_all_v1.json")with open(export_path, "r", encoding="utf-8") as f:export_data = json.load(f)random.shuffle(export_data)for row in export_data:cat = str(row.get("category", "")).lower()cat_words = set(re.findall(r"[a-z0-9_]+", cat))inst = row.get("instruction", "").strip()th = row.get("thinking", "").strip()resp = row.get("response", "").strip()if not inst or not resp:continueif {"translation", "translate", "trans"}.intersection(cat_words) and len(domain_pools["translation_multilingual"]) < DOMAIN_TARGET_CAPS["translation_multilingual"]:add_sample("translation_multilingual", inst, th or "Direct 1-to-1 language translation.", resp)elif {"career", "resume", "cv", "interview", "job", "cover_letter", "email", "resignation", "workplace", "professional"}.intersection(cat_words) and len(domain_pools["career_productivity"]) < DOMAIN_TARGET_CAPS["career_productivity"]:add_sample("career_productivity", inst, th or "Professional formatting and clear writing structure.", resp)elif {"puzzle", "riddle", "reason", "reasoning", "logic", "deduction"}.intersection(cat_words) and len(domain_pools["reasoning_domain"]) < DOMAIN_TARGET_CAPS["reasoning_domain"]:add_sample("reasoning_domain", inst, th or "Logical analysis of relation and puzzle constraints.", resp)elif {"recipe", "food", "cook", "chai", "kitchen", "cooking", "dish", "cuisine"}.intersection(cat_words) and len(domain_pools["recipes_indian_utility"]) < DOMAIN_TARGET_CAPS["recipes_indian_utility"]:if "chai" in inst.lower() and ("batter" in resp.lower() or "fridge" in resp.lower()):continueadd_sample("recipes_indian_utility", inst, th or "Authentic step-by-step cooking recipe with exact kitchen ingredients.", resp)elif {"finance", "health", "wellness", "fitness", "money", "diet", "nutrition", "workout", "tax", "investing"}.intersection(cat_words) and len(domain_pools["finance_health_wellness"]) < DOMAIN_TARGET_CAPS["finance_health_wellness"]:add_sample("finance_health_wellness", inst, th or "Health and financial well-being advice.", resp)elif {"math", "calc", "algebra", "arithmetic", "geometry", "calculus"}.intersection(cat_words) and len(domain_pools["math_logic"]) < DOMAIN_TARGET_CAPS["math_logic"]:add_sample("math_logic", inst, th or "Step-by-step mathematical reasoning.", resp)# Final Strategic Truncationmaster_pool = []4 unmodified linesfinal_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 Strategic Master Pool: {len(master_pool):,} Samples!")return master_pool54 unmodified linesfull_ids.extend(a_ids)labels.extend(a_ids)# Skip entire multi-turn sample if total conversation exceeds context length (Zero broken samples)if len(full_ids) > MAX_SEQ_LEN:skipped_count += 1continue123456789101112131415161720 unmodified lines38394041424344454647484950515253545523 unmodified lines7980818283848548 unmodified lines13413513613713813932 unmodified lines17217317417517617742 unmodified lines22022122222322422519 unmodified lines24524624724824925022 unmodified lines27327427527627727844 unmodified lines323324325326327328216 unmodified lines54554654754854955055148 unmodified lines6006016026036046056063 unmodified lines61061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665714 unmodified lines6726736746756766776786796806812 unmodified lines6846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357364 unmodified lines74174274374474574674774854 unmodified lines803804805806807808809# ==============================================================================# 🚀 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 os20 unmodified linesVAL_RATIO = 0.02SEED = 42# Strategic Target Caps tailored for 500M SLM Full Ingestion (~150k Total)DOMAIN_TARGET_CAPS = {"coding_tech": 18500, # CodeAlpaca + Python algorithms"gk_polity_history": 18500, # Alpaca GPT-4 Hindi + NCERT Science + Modern GK"math_logic": 18500, # GSM8K + Math Domain + Export Math"empathetic_chitchat": 18500, # Conversational Hinglish + Creative & Typo Robustness"career_productivity": 17000, # Workplace, Summarization, JSON & Constraints"translation_multilingual": 17000,# English <-> Hindi <-> Hinglish Parallel"reasoning_domain": 15500, # Logic puzzles, Syllogisms, Anti-hallucination"finance_health_wellness": 14000,# Health, Nutrition, Fitness, Finance"recipes_indian_utility": 10000, # Indian kitchen recipes & lifestyle"identity_greetings": 2500 # Pure ViuAI Sarus persona anchors}random.seed(SEED)23 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)48 unmodified lines}def inject_realistic_typos(text: str, typo_prob: float = 0.15) -> str:if random.random() > typo_prob or len(text) < 10:return text32 unmodified lines# ------------------------------------------------------------------------------def get_json_and_constraints_pack():samples = [("Extract candidate details from this text into clean JSON format: 'Rahul Sharma is a 28-year old Software Engineer based in Bengaluru with 5 years experience in Python and Docker. Email: rahul.sharma@example.com'",42 unmodified linesdef get_summarization_and_extraction_pack():samples = [("Summarize the following text in 2 concise sentences:\n\n'Renewable energy sources such as solar and wind power are growing rapidly across India. Solar installations have witnessed exponential adoption due to falling panel prices and government subsidies. Meanwhile, wind energy capacity in coastal regions continues to supply clean power to the national grid, reducing reliance on coal-based thermal power plants.'",19 unmodified linesdef get_anti_hallucination_pack():samples = [("Who was the 55th President of the United States?",22 unmodified linesdef get_ncert_science_pack():samples = [("Photosynthesis (Prakash Sanshleshan) kya hai aur iska basic chemical formula kya hai?",44 unmodified linesdef get_creative_and_cultural_pack():samples = [("Diwali par dosto aur parivar ko bhejne ke liye ek warm aur sundar Hindi wish likho.",216 unmodified lines# ------------------------------------------------------------------------------# 6. Build Master Pool with High-Density Ingestion# ------------------------------------------------------------------------------def build_master_pool():raw_dir = resolve_or_download_raw_data_dir()48 unmodified linesfor item in get_zero_overthinking_greetings_pack():add_sample(item["domain"], item["instruction"], item["thinking"], item["response"])# 1. Identity Ingestionid_path = os.path.join(raw_dir, "final_viuai_dataset_identity.json")with open(id_path, "r", encoding="utf-8") as f:id_data = json.load(f)3 unmodified linesadd_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 CodeAlpacaprint(f" ⬇️ Ingesting CodeAlpaca...")try:code_ds = load_dataset("sahil2801/CodeAlpaca-20k", split="train")code_samples = list(code_ds)random.shuffle(code_samples)for r in code_samples:if len(domain_pools["coding_tech"]) >= DOMAIN_TARGET_CAPS["coding_tech"]:breakinst = r.get("instruction", "").strip()inp = r.get("input", "").strip()out = r.get("output", "").strip()if 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")gk_samples = list(hindi_gk)random.shuffle(gk_samples)for r in gk_samples:if len(domain_pools["gk_polity_history"]) >= DOMAIN_TARGET_CAPS["gk_polity_history"]:breakinst = r.get("instruction", "").strip()inp = r.get("input", "").strip()out = r.get("output", "").strip()if inp:inst = 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}")# 4. Authentic Math Domain + GSM8Kprint(f" ⬇️ Ingesting Math & GSM8K...")math_path = os.path.join(raw_dir, "final_viuai_dataset_math_domain.json")with open(math_path, "r", encoding="utf-8") as f:math_data = json.load(f)14 unmodified linesadd_sample("math_logic", q, th, clean_resp)except Exception as e:print(f" ⚠️ GSM8K error: {e}")print(f" ✅ [math_logic] : {len(domain_pools['math_logic']):,} loaded")# 5. Authentic Reasoning Domainprint(f" ⬇️ Ingesting Reasoning...")reason_path = os.path.join(raw_dir, "final_viuai_dataset_reasoning_domain.json")with open(reason_path, "r", encoding="utf-8") as f:reason_data = json.load(f)2 unmodified linesbreakadd_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")with open(cc_path, "r", encoding="utf-8") as f:cc_data = json.load(f)random.shuffle(cc_data)for row in cc_data:if len(domain_pools["empathetic_chitchat"]) >= DOMAIN_TARGET_CAPS["empathetic_chitchat"]:breakresp = 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...")CAT_MAP = {"translation_multilingual": {"hindi_to_english", "hinglish_to_english", "english_to_hinglish", "english_to_hindi", "slang_and_idioms"},"career_productivity": {"business_and_office", "career_advice", "career_and_study_dilemmas", "education_study", "academic_pressure", "word_length_budget_constraints", "strictly_no_intro_or_outro", "exact_format_and_bullets", "negative_constraint_following", "json_xml_custom_schema", "multi_step_conditional_tasks", "roleplay_persona_constraints", "language_switching_constraints"},"recipes_indian_utility": {"food_recommendations", "incomplete_recipe_or_how_to", "daily_routine", "seasonal_living", "shopping_consumer", "apartment_hunting", "vehicle_maintenance"},"finance_health_wellness": {"money_finance", "health_fitness", "health_concerns", "financial_literacy", "body_image", "aging_parents", "health_symptom_clarification", "environmental_living", "social_anxiety", "parenting_concerns"},"reasoning_domain": {"blood_relations", "syllogisms", "pattern_series", "critical_thinking", "coding_decoding", "direction_test", "logical_deduction", "seating_arrangement", "multi_option_disambiguation", "missing_context_proactive_followup"},"math_logic": {"basic_arithmetic", "everyday_math", "calculus", "probability", "statistics", "geometry", "algebra", "simple_word_problems", "unit_conversion", "percentage_and_discount"},"empathetic_chitchat": {"daily_life", "emotional_and_relational", "daily_conversations", "humor", "travel_planning", "entertainment_recs", "festival_celebration", "relationships", "college_life", "fast_keyboard_typos", "sms_shorthand_slang", "greetings", "casual_banter", "mixed_devanagari_roman_typos", "informal_code_mixing", "creative_hobbies", "spoken_transcription_artifacts", "slang_and_colloquial_grammar", "phonetic_spelling_swaps", "abbreviations_and_acronyms", "relationship_advice", "casual_chit_chat", "music_arts", "spiritual_exploration", "gaming_entertainment", "conflict_resolution", "digital_life", "hobbies_interests", "nostalgia", "cultural_pressure", "life_transitions"}}cat_to_dom = {}for dom, cat_set in CAT_MAP.items():for c in cat_set:cat_to_dom[c] = domexport_path = os.path.join(raw_dir, "export_all_v1.json")with open(export_path, "r", encoding="utf-8") as f:export_data = json.load(f)random.shuffle(export_data)for row in export_data:cat = str(row.get("category", "")).strip().lower()inst = row.get("instruction", "").strip()th = row.get("thinking", "").strip()resp = row.get("response", "").strip()if not inst or not resp:continueif 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 = []4 unmodified linesfinal_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_pool54 unmodified linesfull_ids.extend(a_ids)labels.extend(a_ids)# Skip entire multi-turn sample if total conversation exceeds context lengthif len(full_ids) > MAX_SEQ_LEN:skipped_count += 1continue
code/build_sft_v17_dataset.py+106-94