Upload code/build_sft_v16_dataset.py with huggingface_hub
Browse files11 unmodified lines1213141516171819202122232452 unmodified lines7778798081828317 unmodified lines10110210310410510610710873 unmodified lines1821831841851861871887 unmodified lines1961971981992002012026 unmodified lines20921021121221321421514 unmodified lines230231232233234235236133 unmodified lines3703713723733743759 unmodified lines385386387388389390391103 unmodified lines4954964974984995005015026 unmodified lines50951051151251351412 unmodified lines5275285295305315325335342 unmodified lines53753853954054154254354454554694 unmodified lines64164264364464564664764864911 unmodified lines# 7. 💰 Personal Finance, Fitness & Wellness Awareness (~5k)# 8. 👑 Diverse Sarus Identity & Multilingual Natural Greetings (~4.5k)## CRITICAL REVIEW FIXES APPLIED:# • CROSS-PLATFORM PORTABILITY: Configurable --local_data_dir and VIUAI_LOCAL_DATA_DIR# with dynamic fallback path discovery & explicit missing warnings.# • DEDUP ENGINE FIX: Handcrafted anchor packs bypass dedup so 15x reinforcement works!# General samples deduped on (inst + resp prefix) to allow multiple diverse answers.# • STRATIFIED VALIDATION SPLIT: Strict domain-wise balanced eval dataset.# • TARGET TOKEN SAFEGUARD: Skips remaining < 20 tokens to avoid wasted gradient compute.# • 2048 NATIVE CONTEXT: Strict EOT_ID preservation.# ==============================================================================52 unmodified linesprint("=" * 85)print("🚀 ViuAI Sarus-500M — SFT v16 Master Dataset Builder (~88,500+ Scale)")print(" 9 Balanced Domains | Cross-Platform Portable | Dedup Fix | 2048 Native Context")print("=" * 85)17 unmodified linesprint(f"📂 Resolved Local Data Directory: {resolved}")return resolvedprint("\n⚠️ WARNING: Local clean data directory not found in candidate paths.")print(" If you are running on Linux/Cloud, pass --local_data_dir or set VIUAI_LOCAL_DATA_DIR.")return None73 unmodified linesif bypass_dedup:return True# Dedup on prompt + response prefix to allow diverse variations for common questionsh = hashlib.md5(f"{inst.strip().lower()} ||| {resp.strip().lower()[:150]}".encode("utf-8")).hexdigest()if h in seen_exact_hashes:return False7 unmodified linesdef 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!"),14 unmodified lines"User asking about AI vs human future. Provide a balanced, mature, and reassuring perspective.","Nahi, AI kabhi human creativity, emotions, empathy aur real-life experience ko replace nahi kar sakta. AI ek powerful tool aur assistant hai jo repetitive kaam aur calculations ko aasan banata hai, taaki humans aur bada soch sakein aur naye innovations create kar sakein. Future 'Human vs AI' ka nahi, balki 'Human + AI' ke collaboration ka hai!"),# Casual Banters("Aur bhai, kya chal raha hai?","Casual greeting. Reply in cool, casual, friendly Hinglish.","Bas sab badiya bhai! System fully charged hai aur main ready hoon. Aap batao, aaj kya naya chal raha hai life me?"),133 unmodified linesreturn [{"instruction": inst, "thinking": th, "response": resp, "language": "hinglish", "domain": "gk_polity_history"} for inst, th, resp in items]# ------------------------------------------------------------------------------# 6. Ingestion of Open-Source High-Density Datasets & Local Cleaned Data# ------------------------------------------------------------------------------9 unmodified linesfor rep in range(15):for item in pack:master_pool.append(dict(item))print(f" Reinforced {len(master_pool):,} clean anchor samples.")# 2. Local Clean Datasets (if resolved)if local_data_dir and os.path.exists(local_data_dir):103 unmodified linesmaster_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)print(" -> Loading Hugging Face Code, Math & Hindi Repos...")try:code_ds = load_dataset("sahil2801/CodeAlpaca-20k", split="train")for item in code_ds:6 unmodified linesexcept Exception as e:print(f" (CodeAlpaca fallback: {e})")try:gsm = load_dataset("openai/gsm8k", "main", split="train")for item in gsm:12 unmodified linesexcept Exception as e:print(f" (GSM8K fallback: {e})")try:samvaad = load_dataset("sarvamai/samvaad-hi-v1", split="train")for item in samvaad:convs = item.get("messages", item.get("conversation", []))if len(convs) >= 2:2 unmodified linesth = "उपयोगकर्ता के प्रश्न का विश्लेषण करें और शुद्ध, स्वाभाविक हिंदी में उत्तर दें।"if is_clean_sample(inst, resp, th):master_pool.append({"instruction": inst, "thinking": th, "response": resp, "language": "hindi", "domain": "empathetic_chitchat"})print(f" Loaded {len(samvaad):,} 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_pool94 unmodified linesf.write(json.dumps(row, ensure_ascii=False) + "\n")print(f" 📄 Saved JSONL: {jsonl_file} ({len(jsonl_rows):,} rows)")# Save NPY (uint16 for tokens, int16 for labels, uint32 for offsets, uint8 for domains)tok_arr = np.array(token_list, dtype=np.uint16)lbl_arr = np.array(label_list, dtype=np.int16)off_arr = np.array(offsets, dtype=np.uint32)dom_arr = np.array(domain_ids, dtype=np.uint8)11 unmodified lines121314151617181920212252 unmodified lines7576777879808117 unmodified lines9910010110210310410573 unmodified lines1791801811821831847 unmodified lines1921931941951961976 unmodified lines20420520620720820914 unmodified lines224225226227228229133 unmodified lines3633643653663673683693703713723733743753763773783793803813823833843853863873883893903913929 unmodified lines402403404405406407408409410411412103 unmodified lines5165175185195205215225235245256 unmodified lines53253353453553653753812 unmodified lines5515525535545555565575585595605615625635645655665675685695705715725735745755765772 unmodified lines58058158258358458558658758858959059159259359459559659759859960060160260360460560660760860994 unmodified lines70470570670770870971071171211 unmodified lines# 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.# ==============================================================================52 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)17 unmodified linesprint(f"📂 Resolved Local Data Directory: {resolved}")return resolvedprint("\nℹ️ Local data directory not found. Using Cloud Open-Source Master Mix.")return None73 unmodified linesif bypass_dedup:return Trueh = hashlib.md5(f"{inst.strip().lower()} ||| {resp.strip().lower()[:150]}".encode("utf-8")).hexdigest()if h in seen_exact_hashes:return False7 unmodified linesdef 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!"),14 unmodified lines"User asking about AI vs human future. Provide a balanced, mature, and reassuring perspective.","Nahi, AI kabhi human creativity, emotions, empathy aur real-life experience ko replace nahi kar sakta. AI ek powerful tool aur assistant hai jo repetitive kaam aur calculations ko aasan banata hai, taaki humans aur bada soch sakein aur naye innovations create kar sakein. Future 'Human vs AI' ka nahi, balki 'Human + AI' ke collaboration ka hai!"),("Aur bhai, kya chal raha hai?","Casual greeting. Reply in cool, casual, friendly Hinglish.","Bas sab badiya bhai! System fully charged hai aur main ready hoon. Aap batao, aaj kya naya chal raha hai life me?"),133 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# ------------------------------------------------------------------------------9 unmodified linesfor rep in range(15):for 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):103 unmodified linesmaster_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:code_ds = load_dataset("sahil2801/CodeAlpaca-20k", split="train")for item in code_ds:6 unmodified linesexcept Exception as e:print(f" (CodeAlpaca fallback: {e})")# 3b. Math (GSM8K)try:gsm = load_dataset("openai/gsm8k", "main", split="train")for item in gsm:12 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 = 0for item in samvaad:convs = item.get("messages", item.get("conversation", []))if len(convs) >= 2:2 unmodified linesth = "उपयोगकर्ता के प्रश्न का विश्लेषण करें और शुद्ध, स्वाभाविक हिंदी में उत्तर दें।"if 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_pool94 unmodified linesf.write(json.dumps(row, ensure_ascii=False) + "\n")print(f" 📄 Saved JSONL: {jsonl_file} ({len(jsonl_rows):,} rows)")# Save NPY (uint16 for tokens, int32 for labels [FIX for overflow], uint32 for offsets, uint8 for domains)tok_arr = np.array(token_list, dtype=np.uint16)lbl_arr = np.array(label_list, dtype=np.int32)off_arr = np.array(offsets, dtype=np.uint32)dom_arr = np.array(domain_ids, dtype=np.uint8)
code/build_sft_v16_dataset.py+83-20