Upload code/build_sft_v17_dataset.py with huggingface_hub
Browse files1234567891011121314151617450 unmodified lines4684694704714724734744754764774784794804814824834844854864874884894904914924934944 unmodified lines4995005015025035045055065075085095105115125135145155165175185195205215225235245255264 unmodified lines5315325335345355365375385395405415422 unmodified lines5455465475485495505515525535545555569 unmodified lines5665675685695705715725735745755765776 unmodified lines5845855865875885895905915925935945955965975985999 unmodified lines60961061161261361461561661761861962062162262362462562662714 unmodified lines64264364464564664764839 unmodified lines6886896906916926936946951 unmodified line69769869970070170270370470511 unmodified lines71771871972072172272314 unmodified lines7387397407417427437447457461 unmodified line748749750751752753754755756757758759760761762763764765766767768# ==============================================================================# 🚀 ViuAI Sarus-500M — SFT v17 Strictly Balanced Dataset Builder (150k+ Scale)# ==============================================================================# KEY UPGRADES & AUDIT FIXES IN SFT v17:# 1. 🛡️ TOKEN ID INTEGRITY: Strict null-checks on <|user|>, <|assistant|>, <|endofturn|>.# 2. 🎯 ZERO-MASKING BUG FIX: Skipped overlong prompts >= MAX_SEQ_LEN, guaranteed matching label lengths.# 3. ⚖️ 100% STRICT UNIFORM BALANCE: All 9 core domains capped at ~16,500, Identity capped at ~3,500.# 4. 🧮 CLEAN MATH ARITHMETIC: Sanitized GSM8K <<...>> tags + removed duplicate answer suffixes.# 5. 🔍 ACCURATE CATEGORY MATCHING: Token-set / word-boundary matching (no substring false positives).# 6. 💾 32-BIT FUTURE PROOFING: Saved as np.int32 tokens/labels to prevent overflow.# 7. 👋 ZERO-OVERTHINKING GREETINGS: 600+ "Hi", "Hello", "How are you" anchors (30x reinforced).# 8. 💻 PYTHON CORE ALGORITHMS: Complete working code (Prime check, Palindrome, Data Structures).# 9. ☕ AUTHENTIC INDIAN KITCHEN: Real Kadak Chai, Maggi, Poha, Dal without baking noise.# 10. 🌐 DIRECT 1-TO-1 TRANSLATION: Strict parallel sentences (English <-> Hindi <-> Hinglish).# ==============================================================================import os450 unmodified linesdef build_master_pool():raw_dir = resolve_or_download_raw_data_dir()domain_pools = {d: [] for d in DOMAIN_MAP}print(f"\n📦 Ingesting Raw Data with Strict Equal Balance (~{DOMAIN_TARGET_CAP:,} 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,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)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']):,} loaded")# 3. Authentic Chit-Chat4 unmodified linesfor 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")4 unmodified linesa = 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}")2 unmodified lineswith 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:9 unmodified linesif 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}")6 unmodified linesinst = 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, Reasoning, Mathexport_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)9 unmodified linescontinueif {"translation", "translate", "trans"}.intersection(cat_words) 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 {"career", "format", "instruction", "email", "writing", "resume"}.intersection(cat_words) 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 {"puzzle", "riddle", "reason", "reasoning", "logic"}.intersection(cat_words) 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 {"recipe", "food", "cook", "chai", "kitchen", "cooking"}.intersection(cat_words) 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 {"finance", "health", "fit", "wellness", "money", "diet"}.intersection(cat_words) 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"})elif {"math", "calc", "algebra", "arithmetic"}.intersection(cat_words) and len(domain_pools["math_logic"]) < DOMAIN_TARGET_CAP:domain_pools["math_logic"].append({"instruction": inst, "thinking": th or "Step-by-step mathematical reasoning.", "response": resp, "domain": "math_logic"})# Truncate each domain strictly to DOMAIN_TARGET_CAP or IDENTITY_TARGET_CAPmaster_pool = []14 unmodified lines# ------------------------------------------------------------------------------# 6. Stratified Split, Tokenization & Packing (Zero-Masking & Future-Proof)# ------------------------------------------------------------------------------def tokenize_and_pack(master_pool):print("\n⚡ Tokenizing & Packing Dataset with Stratified Split & Masked Loss...")domain_buckets = {d: [] for d in DOMAIN_MAP}for item in master_pool:39 unmodified linesprompt_ids = tokenizer.encode(prompt_str).idsfull_ids = tokenizer.encode(full_str).ids# Zero-Masking Protection: Skip if prompt itself fills or exceeds contextif len(prompt_ids) >= MAX_SEQ_LEN:skipped_count += 1continue1 unmodified linefull_ids = full_ids[:MAX_SEQ_LEN]full_ids[-1] = EOT_ID# Strictly mask prompt tokens with -100 and unmask response/thinkinglabels = [-100] * len(prompt_ids) + full_ids[len(prompt_ids):]labels = labels[:len(full_ids)] # Guaranteed exact matching lengthall_tokens.extend(full_ids)all_labels.extend(labels)11 unmodified linesprint(f" Processed {i+1:,}/{len(split_data):,} samples...")if skipped_count > 0:print(f" ℹ️ Skipped {skipped_count} overlong prompts (len >= {MAX_SEQ_LEN}) to protect training signal.")# Save Binary & JSONL with np.int32 Future-Proofingprint(f"💾 Saving {split_name} binary and JSONL files...")14 unmodified linesn_train_s, n_train_t = process_split(train_pool, "train")n_val_s, n_val_t = process_split(val_pool, "val")metadata = {"version": VERSION,"total_samples": len(master_pool),"train_samples": n_train_s,"val_samples": n_val_s,"total_tokens": n_train_t + n_val_t,1 unmodified line"val_tokens": n_val_t,"max_seq_len": MAX_SEQ_LEN,"vocab_size": tokenizer.get_vocab_size(),"domains": DOMAIN_MAP}with open(os.path.join(output_dir, "metadata.json"), "w", encoding="utf-8") as mf:json.dump(metadata, mf, indent=2)print(f"\n📁 Metadata saved to {os.path.join(output_dir, 'metadata.json')}")def main():start_t = time.time()pool = build_master_pool()tokenize_and_pack(pool)elapsed_min = (time.time() - start_t) / 60print("\n" + "=" * 85)print(f"🎉 SFT {VERSION.upper()} STRICTLY BALANCED DATASET BUILT SUCCESSFULLY (150k+ SCALE)!")print(f"⏱️ Total Build Time: {elapsed_min:.2f} minutes")print(f"📂 Output Location: {output_dir}")print("=" * 85)1234567891011121314151617450 unmodified lines4684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165174 unmodified lines5225235245255265275285295305315325335345355365375385395404 unmodified lines5455465475485495505512 unmodified lines5545555565575585595605615629 unmodified lines5725735745755765775786 unmodified lines5855865875885895905915925935945959 unmodified lines60560660760860961061161261361461561661761861962062162262314 unmodified lines63863964064164264364439 unmodified lines6846856866876886896906911 unmodified line69369469569669769869970070170270370470570670770811 unmodified lines72072172272372472572614 unmodified lines7417427437447457467477487497501 unmodified line752753754755756757758759760761762763764765766767768769770771772773774775# ==============================================================================# 🚀 ViuAI Sarus-500M — SFT v17 Grand Master Dataset Builder (150k+ Scale)# ==============================================================================# KEY UPGRADES & COMPLETE AUDIT RESOLUTIONS:# 1. 🛡️ STRICT TOKEN VALIDATION: Null-checks on <|user|>, <|assistant|>, <|endofturn|>.# 2. 🎯 ZERO-MASKING & BPE BOUNDARY SAFETY: Skip prompts >= MAX_SEQ_LEN - 16, guaranteed min 4 active tokens.# 3. 🚫 PROMPT DEDUPLICATION: Strict instruction normalization & duplicate rejection across all sources.# 4. ⚖️ 100% STRICT UNIFORM BALANCE: All 9 core domains capped at ~16,500, Identity capped at ~3,500.# 5. 🧮 CLEAN MATH ARITHMETIC: Sanitized GSM8K <<...>> tags + removed duplicate answer suffixes.# 6. 🎯 PINPOINT CATEGORY MATCHING: Precise keyword sets (removed overly broad 'instruction'/'format').# 7. 💾 32-BIT FUTURE PROOFING: Saved as np.int32 tokens/labels to prevent overflow.# 8. 📊 ACCURATE METADATA: Metadata tracks actual packed samples and elapsed build time.# 9. 👋 ZERO-OVERTHINKING GREETINGS: 600+ "Hi", "Hello", "How are you" anchors (30x reinforced).# 10. 💻 PYTHON CORE ALGORITHMS: Complete working code (Prime check, Palindrome, Data Structures).# ==============================================================================import os450 unmodified linesdef build_master_pool():raw_dir = resolve_or_download_raw_data_dir()domain_pools = {d: [] for d in DOMAIN_MAP}seen_prompts = set()def add_sample(domain, inst, th, resp):inst_clean = inst.strip()resp_clean = resp.strip()if len(inst_clean) < 2 or len(resp_clean) < 2:return False# Deduplication checknorm_key = re.sub(r"\s+", " ", inst_clean.lower())if norm_key in seen_prompts:return Falseseen_prompts.add(norm_key)domain_pools[domain].append({"instruction": inst_clean,"thinking": th.strip() if th else "Helpful, clear response.","response": resp_clean,"domain": domain})return Trueprint(f"\n📦 Ingesting Raw Data with Strict Deduplication & Equal Balance (~{DOMAIN_TARGET_CAP:,} target per domain)...")# 1. Anchors Ingestionfor item in get_zero_overthinking_greetings_pack():add_sample(item["domain"], item["instruction"], item["thinking"], item["response"])for item in get_clean_python_algorithms_pack():add_sample(item["domain"], item["instruction"], item["thinking"], item["response"])for item in get_authentic_indian_recipes_pack():add_sample(item["domain"], item["instruction"], item["thinking"], item["response"])for item in get_step_by_step_unitary_math_pack():add_sample(item["domain"], item["instruction"], item["thinking"], item["response"])for item in get_updated_contemporary_gk_pack():add_sample(item["domain"], item["instruction"], item["thinking"], item["response"])# 2. 100% Authentic 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)for row in id_data:if len(domain_pools["identity_greetings"]) >= IDENTITY_TARGET_CAP: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")# 3. Authentic Chit-Chat4 unmodified linesfor row in cc_data:if len(domain_pools["empathetic_chitchat"]) >= DOMAIN_TARGET_CAP: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)# 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:if len(domain_pools["math_logic"]) >= DOMAIN_TARGET_CAP: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")4 unmodified linesa = r.get("answer", "").strip()th, clean_resp = sanitize_gsm8k_answer(a)if q and clean_resp:add_sample("math_logic", q, th, clean_resp)except Exception as e:print(f" ⚠️ GSM8K error: {e}")2 unmodified lineswith open(reason_path, "r", encoding="utf-8") as f:reason_data = json.load(f)for row in reason_data:if len(domain_pools["reasoning_domain"]) >= DOMAIN_TARGET_CAP:breakadd_sample("reasoning_domain", row.get("instruction", ""), row.get("thinking", "Logical reasoning and step-by-step premise deduction."), row.get("response", ""))# 6. Coding from CodeAlpacatry:9 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)except Exception as e:print(f" ⚠️ CodeAlpaca error: {e}")6 unmodified linesinst = 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}")# 8. Export All Stratified Fill with Pinpoint Category Matchingexport_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)9 unmodified linescontinueif {"translation", "translate", "trans"}.intersection(cat_words) and len(domain_pools["translation_multilingual"]) < DOMAIN_TARGET_CAP: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_CAP: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_CAP: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_CAP: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_CAP: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_CAP:add_sample("math_logic", inst, th or "Step-by-step mathematical reasoning.", resp)# Truncate each domain strictly to DOMAIN_TARGET_CAP or IDENTITY_TARGET_CAPmaster_pool = []14 unmodified lines# ------------------------------------------------------------------------------# 6. Stratified Split, Tokenization & Packing (Zero-Masking & Future-Proof)# ------------------------------------------------------------------------------def tokenize_and_pack(master_pool, start_time):print("\n⚡ Tokenizing & Packing Dataset with Stratified Split & Masked Loss...")domain_buckets = {d: [] for d in DOMAIN_MAP}for item in master_pool:39 unmodified linesprompt_ids = tokenizer.encode(prompt_str).idsfull_ids = tokenizer.encode(full_str).ids# Zero-Masking Protection: Skip if prompt alone fills context (leaves < 16 tokens)if len(prompt_ids) >= MAX_SEQ_LEN - 16:skipped_count += 1continue1 unmodified linefull_ids = full_ids[:MAX_SEQ_LEN]full_ids[-1] = EOT_ID# Safe boundary matchingprompt_len = min(len(prompt_ids), len(full_ids))labels = [-100] * prompt_len + full_ids[prompt_len:]labels = labels[:len(full_ids)] # Exact matching length# Safety check: skip if there are fewer than 4 active learning tokensactive_tokens = sum(1 for l in labels if l != -100)if active_tokens < 4:skipped_count += 1continueall_tokens.extend(full_ids)all_labels.extend(labels)11 unmodified linesprint(f" Processed {i+1:,}/{len(split_data):,} samples...")if skipped_count > 0:print(f" ℹ️ Skipped {skipped_count} overlong/low-signal samples to guarantee strong training signal.")# Save Binary & JSONL with np.int32 Future-Proofingprint(f"💾 Saving {split_name} binary and JSONL files...")14 unmodified linesn_train_s, n_train_t = process_split(train_pool, "train")n_val_s, n_val_t = process_split(val_pool, "val")elapsed_min = (time.time() - start_time) / 60metadata = {"version": VERSION,"total_samples": n_train_s + n_val_s,"train_samples": n_train_s,"val_samples": n_val_s,"total_tokens": n_train_t + n_val_t,1 unmodified line"val_tokens": n_val_t,"max_seq_len": MAX_SEQ_LEN,"vocab_size": tokenizer.get_vocab_size(),"build_time_minutes": round(elapsed_min, 2),"domains": DOMAIN_MAP}with open(os.path.join(output_dir, "metadata.json"), "w", encoding="utf-8") as mf:json.dump(metadata, mf, indent=2)print(f"\n📁 Metadata saved to {os.path.join(output_dir, 'metadata.json')}")return n_train_s + n_val_s, n_train_t + n_val_t, elapsed_mindef main():start_time = time.time()pool = build_master_pool()total_samples, total_tokens, elapsed_min = tokenize_and_pack(pool, start_time)print("\n" + "=" * 85)print(f"🎉 SFT {VERSION.upper()} STRICTLY BALANCED DATASET BUILT SUCCESSFULLY!")print(f" • Total Samples: {total_samples:,}")print(f" • Total Tokens : {total_tokens:,}")print(f" • Build Time : {elapsed_min:.2f} minutes")print(f"📂 Output Location: {output_dir}")print("=" * 85)
code/build_sft_v17_dataset.py+95-88