Upload code/build_sft_v16_dataset.py with huggingface_hub
Browse files9 unmodified lines1011121314151617181920213 unmodified lines25262728293044 unmodified lines7576777879808182838485868788894 unmodified lines94959697989910010110210310410510680 unmodified lines1871881891901911921931941951961976 unmodified lines204205206207208209103 unmodified lines31331431531631731831943 unmodified lines3633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004011 unmodified line4034044054064074084094104114124134144154164174184198 unmodified lines42842943043143243343443543643743843910 unmodified lines4504514524534544554564574584594604616 unmodified lines4684694704714724734744754764776 unmodified lines48448548648748848949049149249320 unmodified lines51451551651751851952052152252327 unmodified lines5515525535545555565575585595605615625635645655665675685695705715725735746 unmodified lines581582583584585586587588589590591592593594595596597598599600601602603604605606607608609139 unmodified lines7497507517527537547559 unmodified lines# 5. 💼 Professional Career, Emails, Resume & Text Polishing (~8k)# 6. 🇮🇳 Indian Daily Utility, Culture & Authentic Recipes (Chai, Food, Life) (~6k)# 7. 💰 Personal Finance, Fitness & Wellness Awareness (~5k)# 8. 👑 Diverse Sarus Identity & Multilingual Natural Greetings (~4.5k)## CRITICAL FIXES APPLIED:# • OVERFLOW FIX: Labels stored as np.int32 (supports vocab > 32767 and -100).# • CLOUD AUTO-BALANCING: Balanced HF repos (Cap Samvaad at 20k, add Alpaca Hindi, Orca Math, OpenHermes).# • IDENTITY CLOUD REINFORCEMENT: Synthetic Sarus/ViuAI identity pack built-in.# • DEDUP FIX: Handcrafted anchor packs bypass dedup so 15x reinforcement works.# • 2048 NATIVE CONTEXT: Strict EOT_ID preservation.# ==============================================================================3 unmodified linesimport reimport jsonimport timeimport randomimport hashlibimport argparse44 unmodified linesprint("=" * 85)print("🚀 ViuAI Sarus-500M — SFT v16 Master Dataset Builder (~88,500+ Scale)")print(" 9 Balanced Domains | int32 Overflow Fix | Cloud Auto-Balanced | 2048 Context")print("=" * 85)# ------------------------------------------------------------------------------# 2. Path Resolution & Cross-Platform Discovery Engine# ------------------------------------------------------------------------------def resolve_local_data_dir(cli_dir=None):"""Dynamically finds local clean data directory across Windows, Linux and Cloud instances."""candidates = [cli_dir,os.environ.get("VIUAI_LOCAL_DATA_DIR"),4 unmodified linesr"c:\Users\IQC-SURBHI\Documents\S-Work\ViuAI\STF Data\Final Clean STF Data"]for c in candidates:if c and os.path.exists(c):resolved = os.path.abspath(c)print(f"📂 Resolved Local Data Directory: {resolved}")return resolvedprint("\nℹ️ Local data directory not found. Using Cloud Open-Source Master Mix.")return None# ------------------------------------------------------------------------------80 unmodified lines# ------------------------------------------------------------------------------# 5. Handcrafted Core Anchor Packs (Empathy, Recipes, Coding, Math, GK, Identity)# ------------------------------------------------------------------------------def get_empathy_and_chitchat_pack():items = [("Mera mood thoda off hai, kuch accha bolo.","User is feeling down and needs warmth, active empathy, and gentle comfort without canned identity introduction.","Arey kya hua dost? Kabhi kabhi din thoda heavy ho jata hai, par yaad rakho ki har buri sham ke baad ek nayi subah aati hai. Chaho to share karo kya hua, dil halka hoga. Aur agar baat nahi karni, to ek mast garam chai piyo aur apna favourite gaana sun kar relax karo. Main yahin hoon tumhare sath!"),6 unmodified lines"User is feeling lonely. Provide genuine warmth, companionship, and uplifting words.","Aap akele nahi hain! Kabhi kabhi bheed me bhi loneliness feel hoti hai, ye bilkul normal hai. Par yaad rakhiye aapki apni ek value hai. Main hamesha yahin hoon aapse baat karne, nayi cheezein seekhne aur aapka din thoda brighter banane ke liye. Chalo batao, aaj sabse pehla thought kya aaya tha dimaag me?"),("Tumhe kaisa lagta hai humans se baat karke?","User asking about the AI's perspective on conversing with humans. Express curiosity, helpfulness, and genuine joy in assisting people.","Mujhe humans se baat karke sach me bohot maza aata hai! Har insaan ke paas ek alag soch, naye sawal, alag emotions aur unique kahani hoti hai. Jab main kisi ka complex code debug karta hoon, koi naya concept samjhata hoon ya kisi ka mood thoda behtar karta hoon, to lagta hai ki main sach me kisi ke kaam aa raha hoon!"),103 unmodified lines" print(key)\n\n""# 3. Sirf Values iterate karna\n""for val in student.values():\n"" print(val)\n""```"),]return [{"instruction": inst, "thinking": th, "response": resp, "language": "hinglish", "domain": "coding_tech"} for inst, th, resp in items]43 unmodified linesreturn [{"instruction": inst, "thinking": th, "response": resp, "language": "hinglish", "domain": "gk_polity_history"} for inst, th, resp in items]def get_synthetic_sarus_identity_pack():"""Generates ~2,000 diverse Sarus/ViuAI identity & greeting pairs for Cloud runs."""greetings = [("Hi", "Hello! Main Sarus hoon, ViuAI dwara develop kiya gaya ek AI assistant. Boliye, aaj main aapki kya madad kar sakta hoon?"),("Hello", "Namaste! Main Sarus hoon, ViuAI ka assistant. Aaj aapko kis topic me help chahiye?"),("Hey there", "Hello! I am Sarus, an AI assistant built by ViuAI. How can I help you today?"),("Who are you?", "I am Sarus, an AI assistant created and trained by ViuAI. I am designed to help with coding, mathematics, reasoning, writing, and everyday conversations."),("Who created you?", "I was created and trained by ViuAI. My name is Sarus!"),("Aapko kisne banaya hai?", "Mujhe ViuAI ne develop aur train kiya hai. Mera naam Sarus hai!"),("Tumhara naam kya hai?", "Mera naam Sarus hai, aur mujhe ViuAI ne banaya hai."),("What can you do?", "I can help you with Python and software programming, step-by-step mathematical reasoning, Indian general knowledge, drafting professional emails, authentic recipes, translations, and daily conversations!"),("Tum kya kya kar sakte ho?", "Main coding, math reasoning, general knowledge, professional writing, recipes aur daily chit-chat me aapki madad kar sakta hoon."),("Good morning", "Good morning! Hope you have a wonderful and productive day ahead. How can I assist you today?"),("Good evening", "Good evening! Kaise hain aap? Boliye, aaj kis topic par baat ya help chahiye?"),("Namaste", "Namaste! Main Sarus hoon. Boliye, aaj aapke liye kya madad kar sakta hoon?")]pack = []for inst, resp in greetings:th = "User greeting / identity inquiry. Respond with warm, helpful Sarus persona created by ViuAI."for _ in range(150):pack.append({"instruction": inst, "thinking": th, "response": resp, "language": "hinglish", "domain": "identity_greetings"})return pack# ------------------------------------------------------------------------------# 6. Ingestion of Open-Source High-Density Datasets & Local Cleaned Data# ------------------------------------------------------------------------------def load_master_dataset_pool(local_data_dir=None):print("\n📦 Step 2/5: Building Balanced Multi-Domain Master Pool...")master_pool = []# 1. Inject Handcrafted Core Anchor Packs (Bypassing dedup so 15x multiplier reinforces weights)print(" -> Ingesting 15x Reinforcement Handcrafted Anchor Packs (Empathy, Food, Code, Math, GK)...")for pack in [get_empathy_and_chitchat_pack(), get_authentic_recipes_pack(),get_coding_essentials_pack(), get_math_logic_pack(), get_gk_polity_pack()]:1 unmodified linefor item in pack:master_pool.append(dict(item))# Ingest Synthetic Sarus Identity Pack (~1,800 samples)print(" -> Ingesting Synthetic Sarus / ViuAI Identity Pack...")master_pool.extend(get_synthetic_sarus_identity_pack())print(f" Reinforced {len(master_pool):,} clean anchor + identity samples.")# 2. Local Clean Datasets (if resolved)if local_data_dir and os.path.exists(local_data_dir):# 2a. Dedicated Sarus Identity Datasetid_path = os.path.join(local_data_dir, "final_viuai_dataset_identity.json")if os.path.exists(id_path):print(f" -> Ingesting Sarus Identity: {id_path}...")with open(id_path, "r", encoding="utf-8") as f:id_data = json.load(f)id_count = 08 unmodified lines"language": lang, "domain": "identity_greetings"})id_count += 1print(f" Retained {id_count:,} identity samples.")# 2b. Cleaned Chit-Chatcc_path = os.path.join(local_data_dir, "final_viuai_dataset_chit_chat.json")if os.path.exists(cc_path):print(f" -> Ingesting & Purging Chit-Chat: {cc_path}...")with open(cc_path, "r", encoding="utf-8") as f:cc_data = json.load(f)cc_clean = 010 unmodified linescc_clean += 1if cc_clean >= 16000:breakprint(f" Retained {cc_clean:,} pristine chit-chat samples.")# 2c. Math Domainmath_path = os.path.join(local_data_dir, "final_viuai_dataset_math_domain.json")if os.path.exists(math_path):print(f" -> Ingesting Math Domain: {math_path}...")with open(math_path, "r", encoding="utf-8") as f:m_data = json.load(f)for d in m_data:6 unmodified lines"language": "english", "domain": "math_logic"})# 2d. Reasoning Domainreason_path = os.path.join(local_data_dir, "final_viuai_dataset_reasoning_domain.json")if os.path.exists(reason_path):print(f" -> Ingesting Reasoning Domain: {reason_path}...")with open(reason_path, "r", encoding="utf-8") as f:r_data = json.load(f)for d in r_data:6 unmodified lines"language": "english", "domain": "reasoning_domain"})# 2e. Master Export Pool (Stratified sampling for GK & Career)export_path = os.path.join(local_data_dir, "export_all_v1.json")if os.path.exists(export_path):print(f" -> Stratified Filtering & Ingestion: {export_path}...")with open(export_path, "r", encoding="utf-8") as f:exp_data = json.load(f)20 unmodified linesmaster_pool.extend(gk_candidates[:18000])master_pool.extend(career_candidates[:10000])print(f" Sampled {min(len(gk_candidates), 18000):,} GK and {min(len(career_candidates), 10000):,} Career samples.")# 3. Hugging Face Open-Source Datasets (CodeAlpaca / GSM8K / Samvaad / Alpaca Hindi)print(" -> Loading Hugging Face Code, Math, GK & Hindi Repos...")# 3a. Codingtry:27 unmodified linesexcept Exception as e:print(f" (GSM8K fallback: {e})")# 3c. Math (Orca Math 200k - sampled 10k)try:orca = load_dataset("microsoft/orca-math-word-problems-200k", split="train")orca_count = 0for item in orca:q = clean_text(item.get("question", ""))a = clean_text(item.get("answer", ""))th = "Analyze word problem, formulate mathematical equation, and calculate step-by-step."if is_clean_sample(q, a, th):master_pool.append({"instruction": q, "thinking": th, "response": a, "language": "english", "domain": "math_logic"})orca_count += 1if orca_count >= 10000:breakprint(f" Loaded {orca_count:,} Orca Math samples.")except Exception as e:print(f" (Orca Math fallback: {e})")# 3d. Samvaad Hindi (Capped at 20k to prevent domain skew)try:samvaad = load_dataset("sarvamai/samvaad-hi-v1", split="train")sam_count = 06 unmodified linesif is_clean_sample(inst, resp, th):master_pool.append({"instruction": inst, "thinking": th, "response": resp, "language": "hindi", "domain": "empathetic_chitchat"})sam_count += 1if sam_count >= 20000:breakprint(f" Loaded {sam_count:,} Samvaad Hindi samples (balanced cap).")except Exception as e:print(f" (Samvaad fallback: {e})")# 3e. Alpaca GPT-4 Hindi (15k samples: GK, Science, Tasks)try:alpaca_hi = load_dataset("FreedomIntelligence/alpaca-gpt4-hindi", split="train")hi_count = 0for item in alpaca_hi:inst = clean_text(item.get("instruction", "") + ("\n" + item.get("input", "") if item.get("input") else ""))resp = clean_text(item.get("output", ""))th = "निर्देश का विश्लेषण करें और विस्तृत, ज्ञानवर्धक उत्तर प्रदान करें।"if is_clean_sample(inst, resp, th):master_pool.append({"instruction": inst, "thinking": th, "response": resp, "language": "hindi", "domain": "gk_polity_history"})hi_count += 1if hi_count >= 15000:breakprint(f" Loaded {hi_count:,} Alpaca Hindi GK/Instruction samples.")except Exception as e:print(f" (Alpaca Hindi fallback: {e})")print(f"\n🎉 Total Master Pool Assembled: {len(master_pool):,} Pristine Samples!")return master_pool139 unmodified linesargs = parser.parse_args()start_t = time.time()resolved_dir = resolve_local_data_dir(args.local_data_dir)pool = load_master_dataset_pool(resolved_dir)tokenize_and_save_dataset(pool)elapsed = time.time() - start_t9 unmodified lines1011121314151617181920213 unmodified lines2526272829303144 unmodified lines7677787980818283848586878889904 unmodified lines959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413580 unmodified lines2162172182192202212222232242252262276 unmodified lines234235236237238239240103 unmodified lines34434534634734834935043 unmodified lines3943953963973983994004014024034044054064074081 unmodified line4104114124134144154164174184194204218 unmodified lines43043143243343443543643743843944044110 unmodified lines4524534544554564574584594604614624636 unmodified lines4704714724734744754764774784796 unmodified lines48648748848949049149249349449520 unmodified lines51651751851952052152252352452527 unmodified lines5535545555565575585596 unmodified lines566567568569570571572573574575576577139 unmodified lines7177187197207217227239 unmodified lines# 5. 💼 Professional Career, Emails, Resume & Text Polishing (~8k)# 6. 🇮🇳 Indian Daily Utility, Culture & Authentic Recipes (Chai, Food, Life) (~6k)# 7. 💰 Personal Finance, Fitness & Wellness Awareness (~5k)# 8. 👑 100% AUTHENTIC Sarus Identity (from final_viuai_dataset_identity.json) (~2.2k)## KEY FEATURES:# • ZERO SYNTHETIC IDENTITY: 100% authentic ViuAI identity dataset used.# • AUTO CLOUD SYNC: Automatically downloads authentic raw data files from HF on Cloud.# • OVERFLOW FIX: Labels stored as np.int32 (supports vocab > 32767 and -100).# • DEDUP FIX: Handcrafted anchor packs bypass dedup so 15x reinforcement works.# • 2048 NATIVE CONTEXT: Strict EOT_ID preservation.# ==============================================================================3 unmodified linesimport reimport jsonimport timeimport shutilimport randomimport hashlibimport argparse44 unmodified linesprint("=" * 85)print("🚀 ViuAI Sarus-500M — SFT v16 Master Dataset Builder (~88,500+ Scale)")print(" 100% Authentic ViuAI Identity | Auto Cloud Sync | int32 Overflow Fix")print("=" * 85)# ------------------------------------------------------------------------------# 2. Path Resolution & Auto Cloud Sync for Authentic Raw Datasets# ------------------------------------------------------------------------------def resolve_or_download_raw_data_dir(cli_dir=None):"""Dynamically finds local clean data directory, or auto-downloads authentic raw files from HF on Cloud."""candidates = [cli_dir,os.environ.get("VIUAI_LOCAL_DATA_DIR"),4 unmodified linesr"c:\Users\IQC-SURBHI\Documents\S-Work\ViuAI\STF Data\Final Clean STF Data"]for c in candidates:if c and os.path.exists(c) and os.path.exists(os.path.join(c, "final_viuai_dataset_identity.json")):resolved = os.path.abspath(c)print(f"📂 Found Local Authentic Raw Data Directory: {resolved}")return resolved# Auto-Download from Hugging Face Hub if on Cloud / Kagglecloud_dest = os.path.join(PROJECT_ROOT, "data", "raw_data")os.makedirs(cloud_dest, exist_ok=True)print(f"\n🌐 Local dataset not found. Auto-downloading authentic raw datasets from Hugging Face Hub ({DATA_REPO_ID}/raw_data)...")raw_files = ["final_viuai_dataset_identity.json","final_viuai_dataset_chit_chat.json","final_viuai_dataset_math_domain.json","final_viuai_dataset_reasoning_domain.json","export_all_v1.json"]for rf in raw_files:dest_f = os.path.join(cloud_dest, rf)if not os.path.exists(dest_f) or os.path.getsize(dest_f) < 1000:try:print(f" ⬇️ Fetching {rf} from cloud...")dl = hf_hub_download(repo_id=DATA_REPO_ID,filename=f"raw_data/{rf}",repo_type="dataset",token=HF_TOKEN)shutil.copy(dl, dest_f)print(f" ✅ Downloaded {rf} ({os.path.getsize(dest_f)/(1024*1024):.2f} MB)")except Exception as e:print(f" ⚠️ Could not fetch {rf}: {e}")return cloud_dest# ------------------------------------------------------------------------------80 unmodified lines# ------------------------------------------------------------------------------# 5. Handcrafted Core Anchor Packs (Empathy, Recipes, Coding, Math, GK)# ------------------------------------------------------------------------------def get_empathy_and_chitchat_pack():items = [# Mood Off / Sadness / Empathy("Mera mood thoda off hai, kuch accha bolo.","User is feeling down and needs warmth, active empathy, and gentle comfort without canned identity introduction.","Arey kya hua dost? Kabhi kabhi din thoda heavy ho jata hai, par yaad rakho ki har buri sham ke baad ek nayi subah aati hai. Chaho to share karo kya hua, dil halka hoga. Aur agar baat nahi karni, to ek mast garam chai piyo aur apna favourite gaana sun kar relax karo. Main yahin hoon tumhare sath!"),6 unmodified lines"User is feeling lonely. Provide genuine warmth, companionship, and uplifting words.","Aap akele nahi hain! Kabhi kabhi bheed me bhi loneliness feel hoti hai, ye bilkul normal hai. Par yaad rakhiye aapki apni ek value hai. Main hamesha yahin hoon aapse baat karne, nayi cheezein seekhne aur aapka din thoda brighter banane ke liye. Chalo batao, aaj sabse pehla thought kya aaya tha dimaag me?"),# Philosophy & Human-AI Connection("Tumhe kaisa lagta hai humans se baat karke?","User asking about the AI's perspective on conversing with humans. Express curiosity, helpfulness, and genuine joy in assisting people.","Mujhe humans se baat karke sach me bohot maza aata hai! Har insaan ke paas ek alag soch, naye sawal, alag emotions aur unique kahani hoti hai. Jab main kisi ka complex code debug karta hoon, koi naya concept samjhata hoon ya kisi ka mood thoda behtar karta hoon, to lagta hai ki main sach me kisi ke kaam aa raha hoon!"),103 unmodified lines" print(key)\n\n""# 3. Sirf Values iterate karna\n""for val in student.values():\n"" print(val)\n\n""```"),]return [{"instruction": inst, "thinking": th, "response": resp, "language": "hinglish", "domain": "coding_tech"} for inst, th, resp in items]43 unmodified linesreturn [{"instruction": inst, "thinking": th, "response": resp, "language": "hinglish", "domain": "gk_polity_history"} for inst, th, resp in items]# ------------------------------------------------------------------------------# 6. Ingestion of Authentic Clean Datasets & Open-Source Repos# ------------------------------------------------------------------------------def load_master_dataset_pool(local_data_dir=None):print("\n📦 Step 2/5: Building Balanced Multi-Domain Master Pool...")master_pool = []# 1. Inject Handcrafted Core Anchor Packsprint(" -> Ingesting 15x Reinforcement Handcrafted Anchor Packs (Empathy, Food, Code, Math, GK)...")for pack in [get_empathy_and_chitchat_pack(), get_authentic_recipes_pack(),get_coding_essentials_pack(), get_math_logic_pack(), get_gk_polity_pack()]:1 unmodified linefor item in pack:master_pool.append(dict(item))# 2. Authentic Clean Datasets (Local or Cloud Auto-Downloaded)if local_data_dir and os.path.exists(local_data_dir):# 2a. 100% AUTHENTIC Sarus Identity Dataset (2,213 samples)id_path = os.path.join(local_data_dir, "final_viuai_dataset_identity.json")if os.path.exists(id_path):print(f" -> Ingesting 100% Authentic Sarus Identity: {id_path}...")with open(id_path, "r", encoding="utf-8") as f:id_data = json.load(f)id_count = 08 unmodified lines"language": lang, "domain": "identity_greetings"})id_count += 1print(f" ✅ Loaded {id_count:,} Authentic Sarus Identity samples.")# 2b. Authentic Cleaned Chit-Chatcc_path = os.path.join(local_data_dir, "final_viuai_dataset_chit_chat.json")if os.path.exists(cc_path):print(f" -> Ingesting Authentic Chit-Chat: {cc_path}...")with open(cc_path, "r", encoding="utf-8") as f:cc_data = json.load(f)cc_clean = 010 unmodified linescc_clean += 1if cc_clean >= 16000:breakprint(f" ✅ Loaded {cc_clean:,} Authentic Chit-Chat samples.")# 2c. Authentic Math Domainmath_path = os.path.join(local_data_dir, "final_viuai_dataset_math_domain.json")if os.path.exists(math_path):print(f" -> Ingesting Authentic Math Domain: {math_path}...")with open(math_path, "r", encoding="utf-8") as f:m_data = json.load(f)for d in m_data:6 unmodified lines"language": "english", "domain": "math_logic"})# 2d. Authentic Reasoning Domainreason_path = os.path.join(local_data_dir, "final_viuai_dataset_reasoning_domain.json")if os.path.exists(reason_path):print(f" -> Ingesting Authentic Reasoning Domain: {reason_path}...")with open(reason_path, "r", encoding="utf-8") as f:r_data = json.load(f)for d in r_data:6 unmodified lines"language": "english", "domain": "reasoning_domain"})# 2e. Authentic Master Export Pool (GK & Career)export_path = os.path.join(local_data_dir, "export_all_v1.json")if os.path.exists(export_path):print(f" -> Stratified Filtering & Ingestion (GK, Career, Life): {export_path}...")with open(export_path, "r", encoding="utf-8") as f:exp_data = json.load(f)20 unmodified linesmaster_pool.extend(gk_candidates[:18000])master_pool.extend(career_candidates[:10000])print(f" ✅ Loaded {min(len(gk_candidates), 18000):,} Authentic GK and {min(len(career_candidates), 10000):,} Career samples.")# 3. Open-Source High-Quality Datasets (CodeAlpaca / GSM8K / Samvaad)print(" -> Loading Hugging Face Code & Math Repos...")# 3a. Codingtry:27 unmodified linesexcept Exception as e:print(f" (GSM8K fallback: {e})")# 3c. Samvaad Hindi (Capped at 15k)try:samvaad = load_dataset("sarvamai/samvaad-hi-v1", split="train")sam_count = 06 unmodified linesif is_clean_sample(inst, resp, th):master_pool.append({"instruction": inst, "thinking": th, "response": resp, "language": "hindi", "domain": "empathetic_chitchat"})sam_count += 1if sam_count >= 15000:breakprint(f" Loaded {sam_count:,} Samvaad Hindi samples.")except Exception as e:print(f" (Samvaad fallback: {e})")print(f"\n🎉 Total Master Pool Assembled: {len(master_pool):,} Pristine Samples!")return master_pool139 unmodified linesargs = parser.parse_args()start_t = time.time()resolved_dir = resolve_or_download_raw_data_dir(args.local_data_dir)pool = load_master_dataset_pool(resolved_dir)tokenize_and_save_dataset(pool)elapsed = time.time() - start_t
code/build_sft_v16_dataset.py+67-99