Upload code/build_sft_v17_dataset.py with huggingface_hub
Browse files123456789101112131415161718192021222346 unmodified lines707172737475761 unmodified line787980818283844 unmodified lines899091929394347 unmodified lines44244344444544644744823 unmodified lines4724734744754764774784 unmodified lines483484485486487488489105 unmodified lines59559659759859960060160260360460560660760860961061161261361461561661761861913 unmodified lines63363463563663763863922 unmodified lines6626636646656666676686693 unmodified lines6736746756766776786796806816826836846856866876886896906916926936946956966976985 unmodified lines7047057067077087097101 unmodified line712713714715716717718719720721722723724# ==============================================================================# 🚀 ViuAI Sarus-500M — SFT v17 Uniformly Balanced Mega Dataset Builder (150k+ Scale)# ==============================================================================# KEY UPGRADES IN SFT v17 (STRICT EQUAL-SHARE BALANCE: ~152,000 SAMPLES):# 1. ⚖️ STRICT UNIFORM BALANCE: All 9 core domains capped at EXACTLY ~16,500 samples each!# 2. 🤖 HIGH-DENSITY IDENTITY: 3,500+ pure authentic ViuAI Sarus identity & persona anchors (30x).# 3. 👋 ZERO-OVERTHINKING GREETINGS: 600+ "Hi", "Hello", "How are you" anchors (30x 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 osimport reimport sysimport jsonimport randomimport numpy as npfrom datasets import load_dataset46 unmodified lines# ------------------------------------------------------------------------------# 1. Load Tokenizer# ------------------------------------------------------------------------------def load_tokenizer():tok_path = os.path.join(root_dir, "tokenizer", "tokenizer.json")1 unmodified lineprint("⬇️ Fetching tokenizer from Hugging Face Hub (ViuAI/ViuAI-500M)...")os.makedirs(os.path.dirname(tok_path), exist_ok=True)dl = hf_hub_download(repo_id="ViuAI/ViuAI-500M", filename="tokenizer/tokenizer.json")import shutilshutil.copy(dl, tok_path)tok = Tokenizer.from_file(tok_path)print(f"✅ Tokenizer Loaded. Vocab size: {tok.get_vocab_size()} (Expected: 64,003)")4 unmodified linesASSISTANT_TOKEN_ID = tokenizer.token_to_id("<|assistant|>")EOT_ID = tokenizer.token_to_id("<|endofturn|>")# ------------------------------------------------------------------------------# 2. Comprehensive Core Anchor Packs (30x Reinforced)347 unmodified lines"export_all_v1.json"]print(f"\n🌐 Auto-downloading raw clean datasets from Hugging Face Hub (ViuAI/viuai-500m-sft-tokenized/raw_data)...")import shutilfor rf in raw_files:target_path = os.path.join(cloud_dir, rf)if not os.path.exists(target_path) or os.path.getsize(target_path) < 1000:23 unmodified linesdomain_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)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)4 unmodified lines"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")105 unmodified linesfor 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"})elif any(k in cat for k in ["math", "calc", "algebra"]) 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_CAP13 unmodified lines# ------------------------------------------------------------------------------# 6. Stratified Split, Tokenization & Packing# ------------------------------------------------------------------------------def tokenize_and_pack(master_pool):print("\n⚡ Tokenizing & Packing Dataset with Stratified Split & Masked Loss...")22 unmodified linesall_tokens = []all_labels = []offsets = [0]domain_ids = []jsonl_rows = []for i, item in enumerate(split_data):inst = item["instruction"].strip()3 unmodified linesprompt_str = f"<|user|>\n{inst}<|endofturn|>\n<|assistant|>\n"if th:full_str = f"<|user|>\n{inst}<|endofturn|>\n<|assistant|>\n[THINK]\n{th}\n[/THINK]\n{resp}<|endofturn|>"else:full_str = f"<|user|>\n{inst}<|endofturn|>\n<|assistant|>\n{resp}<|endofturn|>"prompt_ids = tokenizer.encode(prompt_str).idsfull_ids = tokenizer.encode(full_str).idsif len(full_ids) > MAX_SEQ_LEN:full_ids = full_ids[:MAX_SEQ_LEN]if full_ids[-1] != EOT_ID:full_ids[-1] = EOT_ID# Strictly mask out prompt tokenslabels = [-100] * min(len(prompt_ids), len(full_ids))labels.extend(full_ids[len(labels):])all_tokens.extend(full_ids)all_labels.extend(labels)offsets.append(len(all_tokens))domain_ids.append(dom_id)jsonl_rows.append({"instruction": inst,5 unmodified linesif (i + 1) % 25000 == 0 or (i + 1) == len(split_data):print(f" Processed {i+1:,}/{len(split_data):,} samples...")# Save Binary & JSONLprint(f"💾 Saving {split_name} binary and JSONL files...")jsonl_path = os.path.join(output_dir, f"{split_name}.jsonl")with open(jsonl_path, "w", encoding="utf-8") as jf:1 unmodified linejf.write(json.dumps(row, ensure_ascii=False) + "\n")print(f" 📄 Saved JSONL: {jsonl_path} ({len(jsonl_rows):,} rows)")np.save(os.path.join(output_dir, f"{split_name}_tokens.npy"), np.array(all_tokens, dtype=np.uint16))np.save(os.path.join(output_dir, f"{split_name}_labels.npy"), np.array(all_labels, dtype=np.int32))np.save(os.path.join(output_dir, f"{split_name}_offsets.npy"), np.array(offsets, dtype=np.uint32))np.save(os.path.join(output_dir, f"{split_name}_domains.npy"), np.array(domain_ids, dtype=np.uint8))print(f" ✅ Saved NPY: {len(split_data):,} samples | {len(all_tokens):,} total tokens")return len(split_data), len(all_tokens)n_train_s, n_train_t = process_split(train_pool, "train")n_val_s, n_val_t = process_split(val_pool, "val")12345678910111213141516171819202122232446 unmodified lines717273747576771 unmodified line7980818283844 unmodified lines8990919293949596979899100347 unmodified lines44844945045145245323 unmodified lines4774784794804814824834 unmodified lines488489490491492493494105 unmodified lines60060160260360460560660760860961061161261361461561661761861962062162262362462513 unmodified lines63964064164264364464522 unmodified lines6686696706716726736746756763 unmodified lines6806816826836846856866876886896906916926936946956966976986997007017027037047057067077087095 unmodified lines7157167177187197207217227237241 unmodified line726727728729730731732733734735736737738# ==============================================================================# 🚀 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 osimport reimport sysimport jsonimport shutilimport randomimport numpy as npfrom datasets import load_dataset46 unmodified lines# ------------------------------------------------------------------------------# 1. Load Tokenizer & Strict Validation# ------------------------------------------------------------------------------def load_tokenizer():tok_path = os.path.join(root_dir, "tokenizer", "tokenizer.json")1 unmodified lineprint("⬇️ Fetching tokenizer from Hugging Face Hub (ViuAI/ViuAI-500M)...")os.makedirs(os.path.dirname(tok_path), exist_ok=True)dl = hf_hub_download(repo_id="ViuAI/ViuAI-500M", filename="tokenizer/tokenizer.json")shutil.copy(dl, tok_path)tok = Tokenizer.from_file(tok_path)print(f"✅ Tokenizer Loaded. Vocab size: {tok.get_vocab_size()} (Expected: 64,003)")4 unmodified linesASSISTANT_TOKEN_ID = tokenizer.token_to_id("<|assistant|>")EOT_ID = tokenizer.token_to_id("<|endofturn|>")# Strict Token ID Validationif EOT_ID is None:raise ValueError("❌ Critical Tokenizer Error: '<|endofturn|>' token is missing in tokenizer.json!")if USER_TOKEN_ID is None or ASSISTANT_TOKEN_ID is None:raise ValueError("❌ Critical Tokenizer Error: '<|user|>' or '<|assistant|>' token is missing in tokenizer.json!")# ------------------------------------------------------------------------------# 2. Comprehensive Core Anchor Packs (30x Reinforced)347 unmodified lines"export_all_v1.json"]print(f"\n🌐 Auto-downloading raw clean datasets from Hugging Face Hub (ViuAI/viuai-500m-sft-tokenized/raw_data)...")for rf in raw_files:target_path = os.path.join(cloud_dir, rf)if not os.path.exists(target_path) or os.path.getsize(target_path) < 1000:23 unmodified linesdomain_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)4 unmodified lines"response": row.get("response", "").strip(),"domain": "identity_greetings"})print(f" ✅ [identity_greetings] : {len(domain_pools['identity_greetings']):,} loaded")# 3. Authentic Chit-Chatcc_path = os.path.join(raw_dir, "final_viuai_dataset_chit_chat.json")105 unmodified linesfor 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_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_CAP13 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...")22 unmodified linesall_tokens = []all_labels = []offsets = [0]sample_domain_ids = []jsonl_rows = []skipped_count = 0for i, item in enumerate(split_data):inst = item["instruction"].strip()3 unmodified linesprompt_str = f"<|user|>\n{inst}<|endofturn|>\n<|assistant|>\n"if th:full_str = f"{prompt_str}[THINK]\n{th}\n[/THINK]\n{resp}<|endofturn|>"else:full_str = f"{prompt_str}{resp}<|endofturn|>"prompt_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 += 1continueif len(full_ids) > MAX_SEQ_LEN:full_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)offsets.append(len(all_tokens))sample_domain_ids.append(dom_id)jsonl_rows.append({"instruction": inst,5 unmodified linesif (i + 1) % 25000 == 0 or (i + 1) == len(split_data):print(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...")jsonl_path = os.path.join(output_dir, f"{split_name}.jsonl")with open(jsonl_path, "w", encoding="utf-8") as jf:1 unmodified linejf.write(json.dumps(row, ensure_ascii=False) + "\n")print(f" 📄 Saved JSONL: {jsonl_path} ({len(jsonl_rows):,} rows)")np.save(os.path.join(output_dir, f"{split_name}_tokens.npy"), np.array(all_tokens, dtype=np.int32))np.save(os.path.join(output_dir, f"{split_name}_labels.npy"), np.array(all_labels, dtype=np.int32))np.save(os.path.join(output_dir, f"{split_name}_offsets.npy"), np.array(offsets, dtype=np.uint32))np.save(os.path.join(output_dir, f"{split_name}_domains.npy"), np.array(sample_domain_ids, dtype=np.uint8))print(f" ✅ Saved NPY: {len(sample_domain_ids):,} samples | {len(all_tokens):,} total tokens")return len(sample_domain_ids), len(all_tokens)n_train_s, n_train_t = process_split(train_pool, "train")n_val_s, n_val_t = process_split(val_pool, "val")
code/build_sft_v17_dataset.py+52-38