Upload code/build_sft_v17_dataset.py with huggingface_hub
Browse files123456789101112131415161718 unmodified lines36373839404118 unmodified lines6061626364656667382 unmodified lines450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649110 unmodified lines760761762763764765766# ==============================================================================# 🚀 ViuAI Sarus-500M — SFT v17 Grand Master Dataset Builder (145k+ Mega-Scale)# ==============================================================================# KEY UPGRADES IN SFT v17 (145k+ SCALE):# 1. 👋 ZERO-OVERTHINKING GREETINGS PACK: 500+ Dedicated "Hi", "Hello", "How are you" anchors (20x reinforced).# 2. 🧮 CLEAN MATH ARITHMETIC: Full GSM8K <<...>> sanitized + Local Math (14,500 samples).# 3. 💻 EXPANDED PYTHON CORE PACK: 18,500+ working algorithms, OOP, data structures & CodeAlpaca.# 4. ☕ AUTHENTIC INDIAN KITCHEN PACK: 13,500+ clean Indian & global culinary pairs without baking noise.# 5. 🌐 DIRECT 1-TO-1 TRANSLATION: 16,000+ strict parallel sentences (English <-> Hindi <-> Hinglish).# 6. 🏛️ SAMVAAD & CONTEMPORARY GK: 25,000+ Indian history, polity, geography + 2023-2026 milestones.# 7. 💼 CAREER, EMAIL & PRODUCTIVITY: 15,000+ professional workplace & formatting samples.# 8. 🌿 HEALTH, WELLNESS & FINANCE: 12,000+ daily wellness, fitness & personal finance.# 9. 🤖 100% AUTHENTIC VIUAI IDENTITY: 2,500+ verified identity & core persona samples.# 10. ⚖️ 10 BALANCED DOMAINS: Scaled to 145,000+ ultra-clean samples (~35M tokens).# ==============================================================================import os18 unmodified linesVAL_RATIO = 0.02SEED = 42random.seed(SEED)np.random.seed(SEED)18 unmodified lines}print("=" * 85)print(f"🚀 ViuAI Sarus-500M — SFT {VERSION.upper()} Mega-Scale Dataset Builder (145,000+ Samples)")print(" 10 Balanced Domains | Ultra-Clean Sanitization | Zero Overthinking | ~35M Tokens")print("=" * 85)382 unmodified lines# ------------------------------------------------------------------------------# 5. Build Balanced 145k+ Mega-Scale Master Pool# ------------------------------------------------------------------------------def build_master_pool():raw_dir = resolve_or_download_raw_data_dir()master_pool = []print("\n📦 Building Balanced Multi-Domain Mega-Scale Pool (145,000+ Target)...")# 1. Anchor Packs Ingestiongreetings_anchors = get_zero_overthinking_greetings_pack()python_anchors = get_clean_python_algorithms_pack()recipe_anchors = get_authentic_indian_recipes_pack()math_anchors = get_step_by_step_unitary_math_pack()gk_anchors = get_updated_contemporary_gk_pack()master_pool.extend(greetings_anchors)master_pool.extend(python_anchors)master_pool.extend(recipe_anchors)master_pool.extend(math_anchors)master_pool.extend(gk_anchors)print(f" ✅ Reinforced {len(greetings_anchors) + len(python_anchors) + len(recipe_anchors) + len(math_anchors) + len(gk_anchors):,} Clean Core Anchor Samples (20x).")# 2. 100% Authentic 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)for row in id_data:master_pool.append({"instruction": row.get("instruction", "").strip(),"thinking": row.get("thinking", "Identify as Sarus created by ViuAI, friendly and warm persona.").strip(),"response": row.get("response", "").strip(),"domain": "identity_greetings"})print(f" ✅ Loaded {len(id_data):,} Authentic Sarus Identity samples.")# 3. Authentic Chit-Chat (Expanded Cap: 15,000)cc_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)count_cc = 0for row in cc_data:inst = row.get("instruction", "").strip()resp = row.get("response", "").strip()# Filter out noisy parent roleplay / mom artifactsif "mom" in resp.lower() or len(inst) < 2 or len(resp) < 2:continuemaster_pool.append({"instruction": inst,"thinking": row.get("thinking", "Helpful, natural conversational check-in.").strip(),"response": resp,"domain": "empathetic_chitchat"})count_cc += 1if count_cc >= 15000:breakprint(f" ✅ Loaded {count_cc:,} Clean Chit-Chat samples.")# 4. Authentic Math Domain (Full Set: ~6,500)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)for row in math_data:master_pool.append({"instruction": row.get("instruction", "").strip(),"thinking": row.get("thinking", "Mathematical analysis and logical step calculation.").strip(),"response": row.get("response", "").strip(),"domain": "math_logic"})print(f" ✅ Loaded {len(math_data):,} Local Math samples.")# 5. Authentic Reasoning Domain (Full Set: ~6,000)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)for row in reason_data:master_pool.append({"instruction": row.get("instruction", "").strip(),"thinking": row.get("thinking", "Logical reasoning and step-by-step premise deduction.").strip(),"response": row.get("response", "").strip(),"domain": "reasoning_domain"})print(f" ✅ Loaded {len(reason_data):,} Local Reasoning samples.")# 6. Master Export Stratified Ingestion (Expanded to 65,000+ total from export_all)export_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)trans_c, career_c, reason_c, recipe_c, finance_c = 0, 0, 0, 0, 0for row in export_data:cat = str(row.get("category", "")).lower()inst = row.get("instruction", "").strip()th = row.get("thinking", "").strip()resp = row.get("response", "").strip()if not inst or not resp:continueif "translation" in cat and trans_c < 16000:master_pool.append({"instruction": inst, "thinking": th or "Direct 1-to-1 language translation.", "response": resp, "domain": "translation_multilingual"})trans_c += 1elif any(k in cat for k in ["career", "format", "instruction", "email", "writing"]) and career_c < 15000:master_pool.append({"instruction": inst, "thinking": th or "Professional formatting and clear writing structure.", "response": resp, "domain": "career_productivity"})career_c += 1elif any(k in cat for k in ["puzzle", "riddle", "reason"]) and reason_c < 10000:master_pool.append({"instruction": inst, "thinking": th or "Logical analysis of relation and puzzle constraints.", "response": resp, "domain": "reasoning_domain"})reason_c += 1elif any(k in cat for k in ["recipe", "food", "cook", "chai", "kitchen"]) and recipe_c < 13000:# Filter out baking batter terms if prompt is about tea/chaiif "chai" in inst.lower() and ("batter" in resp.lower() or "fridge" in resp.lower()):continuemaster_pool.append({"instruction": inst, "thinking": th or "Authentic step-by-step cooking recipe with exact kitchen ingredients.", "response": resp, "domain": "recipes_indian_utility"})recipe_c += 1elif any(k in cat for k in ["finance", "health", "fit", "wellness", "money"]) and finance_c < 12000:master_pool.append({"instruction": inst, "thinking": th or "Health and financial well-being advice.", "response": resp, "domain": "finance_health_wellness"})finance_c += 1print(f" ✅ Master Export Balanced Ingestion:")print(f" • Translation : {trans_c:,}")print(f" • Career/Email: {career_c:,}")print(f" • Reasoning : {reason_c:,}")print(f" • Recipes/Food: {recipe_c:,}")print(f" • Health/Fin : {finance_c:,}")# 7. Open-Source Balanced Packs: CodeAlpaca (18k), Clean GSM8K (7.5k), Samvaad GK (15k)print(" -> Loading High-Quality Open-Source Balanced Packs...")try:code_ds = load_dataset("sahil2801/CodeAlpaca-20k", split="train")code_samples = list(code_ds)random.shuffle(code_samples)c_loaded = 0for r in code_samples:inst = 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:master_pool.append({"instruction": inst,"thinking": "Analyze programming task. Write clean, working, idiomatic code with edge-case handling.","response": out,"domain": "coding_tech"})c_loaded += 1if c_loaded >= 18000:breakprint(f" ✅ Loaded {c_loaded:,} CodeAlpaca samples.")except Exception as e:print(f" ⚠️ Could not load CodeAlpaca: {e}")try:gsm = load_dataset("openai/gsm8k", "main", split="train")g_loaded = 0for r in gsm:q = r.get("question", "").strip()a = r.get("answer", "").strip()th, clean_resp = sanitize_gsm8k_answer(a)if q and clean_resp:master_pool.append({"instruction": q,"thinking": th,"response": clean_resp,"domain": "math_logic"})g_loaded += 1if g_loaded >= 7500:breakprint(f" ✅ Loaded {g_loaded:,} Clean Sanitized GSM8K Math samples.")except Exception as e:print(f" ⚠️ Could not load GSM8K: {e}")try:samvaad = load_dataset("gairik/samvaad-hi-v1", split="train")s_loaded = 0for r in samvaad:inst = r.get("instruction", "").strip()out = r.get("output", "").strip()if inst and out and len(inst) > 5 and len(out) > 5:master_pool.append({"instruction": inst,"thinking": "Analyze general knowledge in clean Hindi, provide factual and accurate response.","response": out,"domain": "gk_polity_history"})s_loaded += 1if s_loaded >= 15000:breakprint(f" ✅ Loaded {s_loaded:,} Samvaad GK samples.")except Exception as e:print(f" ⚠️ Could not load Samvaad: {e}")print(f"\n🎉 Total Master Pool Assembled: {len(master_pool):,} Pristine Samples!")return master_pool110 unmodified linespool = build_master_pool()tokenize_and_pack(pool)print("\n" + "=" * 85)print(f"🎉 SFT {VERSION.upper()} MEGA-SCALE DATASET BUILT SUCCESSFULLY (145k+ SAMPLES)!")print(f"📂 Output Location: {output_dir}")print("=" * 85)123456789101112131415161718 unmodified lines36373839404142434418 unmodified lines6364656667686970382 unmodified lines453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630110 unmodified lines741742743744745746747# ==============================================================================# 🚀 ViuAI Sarus-500M — SFT v17 Uniformly Balanced Grand Master Dataset Builder# ==============================================================================# KEY UPGRADES IN SFT v17 (STRICT EQUAL-SHARE BALANCE: ~125,000 SAMPLES):# 1. ⚖️ STRICT UNIFORM BALANCE: All 9 core domains capped at EXACTLY ~13,500 samples each!# 2. 🤖 HIGH-DENSITY IDENTITY: 3,000+ pure authentic ViuAI Sarus identity & persona anchors.# 3. 👋 ZERO-OVERTHINKING GREETINGS: 500+ "Hi", "Hello", "How are you" anchors (20x reinforced).# 4. 🧮 CLEAN MATH ARITHMETIC: Full GSM8K <<...>> sanitized + Local Math + Unitary Method.# 5. 💻 PYTHON CORE ALGORITHMS: Complete working code (Prime check, Palindrome, Data Structures).# 6. ☕ AUTHENTIC INDIAN KITCHEN: Real Kadak Chai, Maggi, Poha, Dal without baking noise.# 7. 🌐 DIRECT 1-TO-1 TRANSLATION: Strict parallel sentences (English <-> Hindi <-> Hinglish).# 8. 🏛️ SAMVAAD & CONTEMPORARY GK: Indian history, polity, geography + 2023-2026 milestones.# 9. 💼 CAREER, EMAIL & PRODUCTIVITY: Professional workplace & formatting samples.# 10. 🌿 HEALTH, WELLNESS & FINANCE: Daily wellness, fitness & personal finance.# ==============================================================================import os18 unmodified linesVAL_RATIO = 0.02SEED = 42# Strict Target Cap per Major Domain for 100% Equal BalanceDOMAIN_TARGET_CAP = 13500random.seed(SEED)np.random.seed(SEED)18 unmodified lines}print("=" * 85)print(f"🚀 ViuAI Sarus-500M — SFT {VERSION.upper()} Strictly Balanced Dataset Builder (~125k Scale)")print(f" ⚖️ Equal Balance: ~{DOMAIN_TARGET_CAP:,} samples per domain | Zero Bias | Ultra-Clean")print("=" * 85)382 unmodified lines# ------------------------------------------------------------------------------# 5. Build Strictly Balanced Multi-Domain Pool (~13,500 per domain)# ------------------------------------------------------------------------------def build_master_pool():raw_dir = resolve_or_download_raw_data_dir()domain_pools = {d: [] for d in DOMAIN_MAP}print("\n📦 Ingesting Raw Data with Strict Uniform Domain Balancing (~13,500 target per domain)...")# 1. Anchors Ingestiondomain_pools["empathetic_chitchat"].extend(get_zero_overthinking_greetings_pack())domain_pools["coding_tech"].extend(get_clean_python_algorithms_pack())domain_pools["recipes_indian_utility"].extend(get_authentic_indian_recipes_pack())domain_pools["math_logic"].extend(get_step_by_step_unitary_math_pack())domain_pools["gk_polity_history"].extend(get_updated_contemporary_gk_pack())# 2. 100% Authentic Identity Ingestion (~3,000)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)for row in id_data:domain_pools["identity_greetings"].append({"instruction": row.get("instruction", "").strip(),"thinking": row.get("thinking", "Identify as Sarus created by ViuAI, friendly and warm persona.").strip(),"response": row.get("response", "").strip(),"domain": "identity_greetings"})print(f" ✅ [identity_greetings] : {len(domain_pools['identity_greetings']):,} samples")# 3. 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_CAP:breakinst = row.get("instruction", "").strip()resp = row.get("response", "").strip()if "mom" in resp.lower() or len(inst) < 2 or len(resp) < 2:continuedomain_pools["empathetic_chitchat"].append({"instruction": inst,"thinking": row.get("thinking", "Helpful, natural conversational check-in.").strip(),"response": resp,"domain": "empathetic_chitchat"})# 4. 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)for row in math_data:domain_pools["math_logic"].append({"instruction": row.get("instruction", "").strip(),"thinking": row.get("thinking", "Mathematical analysis and logical step calculation.").strip(),"response": row.get("response", "").strip(),"domain": "math_logic"})try:gsm = load_dataset("openai/gsm8k", "main", split="train")for r in gsm:if len(domain_pools["math_logic"]) >= DOMAIN_TARGET_CAP:breakq = r.get("question", "").strip()a = r.get("answer", "").strip()th, clean_resp = sanitize_gsm8k_answer(a)if q and clean_resp:domain_pools["math_logic"].append({"instruction": q,"thinking": th,"response": clean_resp,"domain": "math_logic"})except Exception as e:print(f" ⚠️ GSM8K error: {e}")# 5. 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)for row in reason_data:domain_pools["reasoning_domain"].append({"instruction": row.get("instruction", "").strip(),"thinking": row.get("thinking", "Logical reasoning and step-by-step premise deduction.").strip(),"response": row.get("response", "").strip(),"domain": "reasoning_domain"})# 6. 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_CAP: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:domain_pools["coding_tech"].append({"instruction": inst,"thinking": "Analyze programming task. Write clean, working, idiomatic code with edge-case handling.","response": out,"domain": "coding_tech"})except Exception as e:print(f" ⚠️ CodeAlpaca error: {e}")# 7. 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_CAP:breakinst = r.get("instruction", "").strip()out = r.get("output", "").strip()if inst and out and len(inst) > 5 and len(out) > 5:domain_pools["gk_polity_history"].append({"instruction": inst,"thinking": "Analyze general knowledge in clean Hindi, provide factual and accurate response.","response": out,"domain": "gk_polity_history"})except Exception as e:print(f" ⚠️ Samvaad error: {e}")# 8. Export All Stratified Fill for Career, Recipes, Health, Translation, Reasoningexport_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()inst = row.get("instruction", "").strip()th = row.get("thinking", "").strip()resp = row.get("response", "").strip()if not inst or not resp:continueif "translation" in cat and len(domain_pools["translation_multilingual"]) < DOMAIN_TARGET_CAP:domain_pools["translation_multilingual"].append({"instruction": inst, "thinking": th or "Direct 1-to-1 language translation.", "response": resp, "domain": "translation_multilingual"})elif any(k in cat for k in ["career", "format", "instruction", "email", "writing"]) and len(domain_pools["career_productivity"]) < DOMAIN_TARGET_CAP:domain_pools["career_productivity"].append({"instruction": inst, "thinking": th or "Professional formatting and clear writing structure.", "response": resp, "domain": "career_productivity"})elif any(k in cat for k in ["puzzle", "riddle", "reason"]) and len(domain_pools["reasoning_domain"]) < DOMAIN_TARGET_CAP:domain_pools["reasoning_domain"].append({"instruction": inst, "thinking": th or "Logical analysis of relation and puzzle constraints.", "response": resp, "domain": "reasoning_domain"})elif any(k in cat for k in ["recipe", "food", "cook", "chai", "kitchen"]) and len(domain_pools["recipes_indian_utility"]) < DOMAIN_TARGET_CAP:if "chai" in inst.lower() and ("batter" in resp.lower() or "fridge" in resp.lower()):continuedomain_pools["recipes_indian_utility"].append({"instruction": inst, "thinking": th or "Authentic step-by-step cooking recipe with exact kitchen ingredients.", "response": resp, "domain": "recipes_indian_utility"})elif any(k in cat for k in ["finance", "health", "fit", "wellness", "money"]) and len(domain_pools["finance_health_wellness"]) < DOMAIN_TARGET_CAP:domain_pools["finance_health_wellness"].append({"instruction": inst, "thinking": th or "Health and financial well-being advice.", "response": resp, "domain": "finance_health_wellness"})# Truncate each domain strictly to DOMAIN_TARGET_CAPmaster_pool = []print("\n--- Final Equal-Share Domain Balances ---")for d, items in domain_pools.items():random.shuffle(items)if d != "identity_greetings":final_items = items[:DOMAIN_TARGET_CAP]else:final_items = itemsdomain_pools[d] = final_itemsmaster_pool.extend(final_items)pct = (len(final_items) / max(1, len(master_pool))) * 100print(f" • {d:<25}: {len(final_items):>6,} samples")print(f"\n🎉 Total Strictly Balanced Master Pool: {len(master_pool):,} Samples!")return master_pool110 unmodified linespool = build_master_pool()tokenize_and_pack(pool)print("\n" + "=" * 85)print(f"🎉 SFT {VERSION.upper()} STRICTLY BALANCED DATASET BUILT SUCCESSFULLY (~125k SCALE)!")print(f"📂 Output Location: {output_dir}")print("=" * 85)
code/build_sft_v17_dataset.py+108-127