Delete code/build_sft_data_v7.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200# ==============================================================================# ViuAI 500M — SFT v7 Cognitive & RAG Dataset Builder (Ultra-Quality & Resilient)# ==============================================================================# Multi-Turn, Tool-Calling, Grounded RAG, Diverse Reasoning & Emotional Intelligence# Produces exact 6-file flat memmapped format (.npy) for train_sft.py# ==============================================================================
import sysif hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8", errors="replace")if hasattr(sys.stderr, "reconfigure"): sys.stderr.reconfigure(encoding="utf-8", errors="replace")
import osimport reimport jsonimport timeimport hashlibimport randomimport unicodedatafrom datetime import datetime, timezoneimport numpy as npfrom tqdm import tqdmfrom huggingface_hub import HfApi, hf_hub_downloadfrom transformers import PreTrainedTokenizerFastfrom datasets import load_dataset
# Set deterministic random seedrandom.seed(42)np.random.seed(42)
# --- 1. Configuration & Tokens ---HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")if not HF_TOKEN: print("ℹ️ HF_TOKEN not set in environment. Downloading from public repos; uploads will require HF_TOKEN.", flush=True)
REPO_ID = os.environ.get("VIUAI_MODEL_REPO", "ViuAI/ViuAI-500M")DATA_REPO_ID = os.environ.get("VIUAI_SFT_DATA_REPO", "ViuAI/viuai-500m-sft-tokenized")CTX_LEN = 2048SPECIAL_TOKENS = [ "<|user|>", "<|assistant|>", "<|endofturn|>", "[THINK]", "[/THINK]", "<search>", "</search>", "<search_result>", "</search_result>"]EXPECTED_VOCAB_SIZE = 64009
print(f"🚀 Starting ViuAI SFT v7 Data Generation (Context: {CTX_LEN}, Vocab Target: {EXPECTED_VOCAB_SIZE})...")
# --- 2. Load & Validate Tokenizer ---try: tok_path = hf_hub_download(repo_id=REPO_ID, filename="tokenizer/tokenizer.json", repo_type="model", token=HF_TOKEN)except Exception: tok_path = "tokenizer/tokenizer.json"
tokenizer = PreTrainedTokenizerFast( tokenizer_file=tok_path, pad_token="<pad>", bos_token="<bos>", eos_token="<eos>", unk_token="<unk>")tokenizer.add_tokens(SPECIAL_TOKENS, special_tokens=True)print(f"✅ Tokenizer loaded. Vocab size: {len(tokenizer)} | pad_token_id: {tokenizer.pad_token_id}")assert len(tokenizer) == EXPECTED_VOCAB_SIZE, f"Tokenizer vocab size mismatch: {len(tokenizer)} != {EXPECTED_VOCAB_SIZE}"assert tokenizer.pad_token_id == 0, f"Expected pad_token_id=0, got {tokenizer.pad_token_id}"
# --- 3. Robust Text Cleaner, Truncators & Builders ---
_truncated_stats = { "module_1": 0, "module_2": 0, "module_3": 0, "module_4": 0, "module_5": 0, "module_6": 0, "total": 0}_current_module_key = "module_1"
def clean_text(text: str) -> str: """Cleans raw text while strictly preserving indentation in code blocks.""" if not text: return "" text = unicodedata.normalize("NFKC", str(text)) text = "".join(ch for ch in text if ch == '\n' or ch == '\t' or unicodedata.category(ch)[0] != 'C') cleaned_lines = [] for line in text.split("\n"): if line.startswith(" ") or line.startswith("\t"): cleaned_lines.append(line.rstrip()) else: cleaned_lines.append(re.sub(r'[ \t]+', ' ', line).strip()) res = "\n".join(cleaned_lines) res = re.sub(r'\n{3,}', '\n\n', res) return res.strip()
def enforce_context_len(example_dict: dict) -> dict: """ Smart context truncation: Instead of dropping long examples, preserves user prompt prefix (first 350 tokens) + relevant context/response (last CTX_LEN - 350 tokens). """ global _truncated_stats, _current_module_key if example_dict is None: return None ids = example_dict["input_ids"] labels = example_dict["labels"] if len(ids) > CTX_LEN: _truncated_stats[_current_module_key] = _truncated_stats.get(_current_module_key, 0) + 1 _truncated_stats["total"] += 1 # Smart middle/tail truncation keep_first = 350 keep_last = CTX_LEN - keep_first ids = ids[:keep_first] + ids[-keep_last:] labels = labels[:keep_first] + labels[-keep_last:] return {"input_ids": ids, "labels": labels}
def build_direct_example(prompt: str, think: str, response: str) -> dict: """Builds a single direct-turn cognitive example.""" p_clean = clean_text(prompt) r_clean = clean_text(response) if not p_clean or not r_clean: return None
t_clean = clean_text(think) if think else ""
p_str = f"<|user|>\n{p_clean}<|endofturn|>\n<|assistant|>\n" if t_clean: r_str = f"[THINK]\n{t_clean}\n[/THINK]\n{r_clean}<|endofturn|>\n" else: r_str = f"{r_clean}<|endofturn|>\n"
p_ids = tokenizer.encode(p_str, add_special_tokens=False) r_ids = tokenizer.encode(r_str, add_special_tokens=False)
input_ids = p_ids + r_ids labels = [-100] * len(p_ids) + r_ids.copy()
return enforce_context_len({"input_ids": input_ids, "labels": labels})
def build_multi_turn_example(dialogue_turns: list) -> dict: """Builds a multi-turn conversation example with prompt masking.""" input_ids = [] labels = []
for turn in dialogue_turns: role = turn.get("role", "") content = clean_text(turn.get("content", "")) think = clean_text(turn.get("think", "")) if "think" in turn else ""
if not content: continue
if role == "user": u_str = f"<|user|>\n{content}<|endofturn|>\n" u_ids = tokenizer.encode(u_str, add_special_tokens=False) input_ids.extend(u_ids) labels.extend([-100] * len(u_ids)) elif role == "assistant": if think: a_str = f"<|assistant|>\n[THINK]\n{think}\n[/THINK]\n{content}<|endofturn|>\n" else: a_str = f"<|assistant|>\n{content}<|endofturn|>\n"
prefix_str = "<|assistant|>\n" prefix_ids = tokenizer.encode(prefix_str, add_special_tokens=False) a_ids = tokenizer.encode(a_str, add_special_tokens=False)
ans_ids = a_ids[len(prefix_ids):] input_ids.extend(prefix_ids + ans_ids) labels.extend([-100] * len(prefix_ids) + ans_ids.copy())
if not input_ids or not any(l != -100 for l in labels): return None
return enforce_context_len({"input_ids": input_ids, "labels": labels})
def build_search_example(prompt: str, think_phase1: str, search_query: str, search_result: str, think_phase2: str, final_response: str) -> dict: """Builds a 2-phase grounded search & tool-calling example.""" p_clean = clean_text(prompt) sq_clean = clean_text(search_query) sr_clean = clean_text(search_result) r_clean = clean_text(final_response)
if not p_clean or not sq_clean or not sr_clean or not r_clean: return None
t1_clean = clean_text(think_phase1) if think_phase1 else "" t2_clean = clean_text(think_phase2) if think_phase2 else ""
p_str = f"<|user|>\n{p_clean}<|endofturn|>\n<|assistant|>\n" p_ids = tokenizer.encode(p_str, add_special_tokens=False)
if t1_clean: phase1_str = f"[THINK]\n{t1_clean}\n[/THINK]\n<search>{sq_clean}</search>\n" else: phase1_str = f"<search>{sq_clean}</search>\n" ph1_ids = tokenizer.encode(phase1_str, add_special_tokens=False)
inj_str = f"<search_result>{sr_clean}</search_result>\n" inj_ids = tokenizer.encode(inj_str, add_special_tokens=False)
if t2_clean: phase2_str = f"[THINK]\n{t2_clean}\n[/THINK]\n{r_clean}<|endofturn|>\n" else: phase2_str = f"{r_clean}<|endofturn|>\n" ph2_ids = tokenizer.encode(phase2_str, add_special_tokens=False)
input_ids = p_ids + ph1_ids + inj_ids + ph2_ids labels = ( [-100] * len(p_ids) + ph1_ids.copy() + [-100] * len(inj_ids) + ph2_ids.copy() )
return enforce_context_len({"input_ids": input_ids, "labels": labels})
# Dynamic content-grounded cognitive think generator with deep category diversitydef create_content_grounded_think(instruction: str, output: str = "") -> str: """ Generates content-grounded, highly diverse cognitive reasoning for instructions. Uses topic extraction and tailored multi-step analytical reasoning. """ inst_clean = instruction.strip() cleaned_prompt = re.sub( r'^(what is|what are|explain|describe|tell me about|how to|how does|why is|why does|compare|difference between|write a|can you explain|give me|list)\s+', '', inst_clean, flags=re.IGNORECASE ).strip('?. ') topic = " ".join(cleaned_prompt.split()[:7]) if cleaned_prompt else "the requested query" lower_inst = inst_clean.lower() # 1. Code / Programming if any(k in lower_inst for k in ["code", "python", "function", "algorithm", "debug", "javascript", "program", "sql", "class", "script", "regex", "c++", "java"]): variants = [ f"1. Technical Objective: Design and verify a clean solution for '{topic}'.\n2. Logic & Complexity: Select appropriate data structures and account for boundary edge cases.\n3. Implementation: Produce clean, readable, syntactically correct code.", f"1. Problem Breakdown: Analyze input/output requirements for '{topic}'.\n2. Algorithmic Approach: Determine optimal time and space complexity.\n3. Coding & Validation: Structure the implementation with clear logic and documentation.", f"1. Code Specification: Examine technical constraints regarding '{topic}'.\n2. Edge Case Handling: Guard against invalid types, nulls, and out-of-bound errors.\n3. Output Generation: Deliver robust and idiomatic code.", ] return random.choice(variants)
# 2. Comparative Analysis elif any(k in lower_inst for k in ["compare", "difference", "vs", "versus", "pros and cons", "distinguish", "contrast", "tradeoffs"]): variants = [ f"1. Task Assessment: Comparative evaluation of '{topic}'.\n2. Analytical Breakdown: Identify primary distinctions, trade-offs, and relative advantages.\n3. Response Structuring: Present a clear, balanced side-by-side comparison.", f"1. Domain Context: Examine key differences between components in '{topic}'.\n2. Parameter Comparison: Evaluate performance, usability, cost, and use-case suitability.\n3. Synthesis: Formulate clear takeaways and practical recommendations.", f"1. Evaluation Framework: Establish dimensions of comparison for '{topic}'.\n2. Pros & Cons Analysis: Weight the relative strengths and limitations.\n3. Conclusion: Summarize distinguishing factors clearly.", ] return random.choice(variants)
# 3. Procedural / How-To elif any(k in lower_inst for k in ["how to", "steps to", "guide", "tutorial", "recipe", "instructions for", "how can i", "how do i", "best way to"]): variants = [ f"1. Goal Identification: Provide actionable procedural instructions for '{topic}'.\n2. Logical Sequencing: Organize prerequisites, core execution steps, and key tips.\n3. Clarity Check: Ensure steps are intuitive, direct, and actionable.", f"1. Process Breakdown: Identify the sequential phases required to achieve '{topic}'.\n2. Step-by-Step Elaboration: Detail each phase with essential precautions and best practices.\n3. Verification: Review steps for clarity, completeness, and ease of following.", f"1. Requirement Analysis: Outline what is needed to accomplish '{topic}'.\n2. Action Plan: Structure the solution in logical order with concrete guidance.\n3. Final Polish: Ensure concise phrasing and helpful tips.", ] return random.choice(variants)
# 4. Creative Writing / Synthesis elif any(k in lower_inst for k in ["write", "draft", "story", "poem", "essay", "email", "speech", "dialogue", "summarize", "paraphrase"]): variants = [ f"1. Creative Intent: Generate structured composition regarding '{topic}'.\n2. Stylistic Framing: Adopt an engaging, coherent tone appropriate for the context.\n3. Synthesis: Ensure smooth logical flow and expressive articulation.", f"1. Theme & Audience: Identify the mood, purpose, and audience for '{topic}'.\n2. Content Drafting: Weave vivid expression, natural phrasing, and thematic depth.\n3. Polish: Refine vocabulary and rhythm for maximum impact.", f"1. Prompt Understanding: Structure narrative and key elements for '{topic}'.\n2. Composition: Develop ideas progressively with engaging pacing.\n3. Review: Check tonal consistency and aesthetic quality.", ] return random.choice(variants)
# 5. Explanatory & Scientific / Definitions elif any(k in lower_inst for k in ["what is", "what are", "define", "explain", "meaning of", "describe", "why", "cause of"]): variants = [ f"1. Conceptual Analysis: Understand core principles behind '{topic}'.\n2. Fact Retrieval: Assemble key definitions, underlying mechanisms, and context.\n3. Formulation: Deliver an accurate, easy-to-understand breakdown with illustrative context.", f"1. Core Query: Unpack scientific or conceptual fundamentals of '{topic}'.\n2. Analytical Reasoning: Connect cause-and-effect relationships and real-world relevance.\n3. Explanation: Provide a structured explanation from basics to advanced insights.", f"1. Subject Identification: Define key terminology and context for '{topic}'.\n2. Detailed Synthesis: Explain operational mechanisms and core characteristics.\n3. Summary: Ensure clear, authoritative, and accessible delivery.", ] return random.choice(variants)
# 6. General Direct Inquiry else: variants = [ f"1. Query Parsing: Examine requirements for '{topic}'.\n2. Knowledge Synthesis: Retrieve relevant factual details and context.\n3. Articulation: Formulate a direct, well-structured, and helpful response.", f"1. Intent Recognition: Understand user inquiry about '{topic}'.\n2. Fact Formulation: Retrieve verified information and organize key points.\n3. Clear Delivery: Present the answer clearly with concise summary.", f"1. Scope Assessment: Determine essential information needed for '{topic}'.\n2. Detail Structuring: Organize thoughts logically for clarity.\n3. Articulation: Provide accurate, friendly, and complete guidance.", ] return random.choice(variants)
def extract_concise_math_conclusion(rationale: str) -> str: """Extracts a clean, non-redundant conclusion from a math solution text.""" if not rationale: return "Therefore, the problem is solved as derived in the steps above." lines = [line.strip() for line in rationale.strip().split("\n") if line.strip()] if not lines: return "Therefore, the problem is solved as derived above." for line in reversed(lines): if re.search(r'\b(therefore|thus|so|hence|in conclusion|the answer is|final answer)\b', line, re.IGNORECASE): return line last_line = lines[-1] sentences = re.split(r'(?<=[.!?])\s+', last_line) if sentences: return sentences[-1].strip() return last_line
# ==============================================================================# MODULE 1: Warm Friend & Emotional Companion (Dost Mode) (~14,000 Real Dialogues)# ==============================================================================def generate_emotional_friend_dataset(target_count=14000) -> list: global _current_module_key _current_module_key = "module_1" print(f"\n🤝 Module 1: Generating Warm Friend & Emotional Dataset (Target: {target_count})...") examples = [] seen = set()
counsel_think_variants = [ "1. Emotional State: User expresses vulnerability and emotional fatigue.\n2. Dost Persona: Respond with deep empathy, active validation, and a supportive, non-judgmental presence.\n3. Guidance: Offer warm comfort and practical emotional encouragement.", "1. Empathy Check: User is navigating challenging feelings.\n2. Persona Alignment: Validate user's experience with sincere warmth and compassion.\n3. Supportive Action: Provide reassuring perspective and gentle next steps.", "1. Context Assessment: Emotionally significant user scenario.\n2. Tone Strategy: Act as a loyal, understanding friend who listens without judgement.\n3. Formulation: Deliver heartwarming companionship and constructive grounding.", "1. Vulnerability Recognition: User is reaching out for emotional support.\n2. Companion Role: Provide empathetic presence and honest reassurance.\n3. Response Structuring: Uplift spirits and offer steady guidance." ]
# 1. Real Counseling & Empathetic Conversations (Amod/mental_health_counseling_conversations) try: print(" 📥 Loading 'Amod/mental_health_counseling_conversations' from Hugging Face...") counsel_ds = load_dataset("Amod/mental_health_counseling_conversations", split="train") for item in tqdm(counsel_ds, desc="Parsing Counseling"): if len(examples) >= int(target_count * 0.45): break ctx = clean_text(item.get("Context", "")) resp = clean_text(item.get("Response", "")) if not ctx or not resp: continue
h = hashlib.md5(f"{ctx.lower().strip()}:{resp.lower().strip()}".encode()).hexdigest() if h in seen: continue seen.add(h)
think = random.choice(counsel_think_variants) ex = build_direct_example(ctx, think, resp) if ex: examples.append(ex) print(f" ✅ Loaded {len(examples)} real empathetic counseling conversations!") except Exception as e: print(f" ⚠️ Could not load counseling dataset: {e}")
# 2. Daily Emotional Dialogues & Life Situations (Expanded template bank: 60+ scenarios) emotional_scenarios = [ ("Aaj mera interview bohot bura gaya, lagta hai reject ho jaunga.", "Main samajh sakta hoon bhai, interview bura jaane se dil toot jata hai. Lekin yaad rakhna ek interview tumhari poori kabiliyat define nahi karta. Jo galtiyan hui unse seekhenge aur agle interview me aur better karenge. Main tumhare saath hoon!"), ("I'm feeling completely burnt out and unable to focus on work today.", "It's completely okay to feel this way. Burnout is your mind's signal that you need to pause and recharge. Take a step back, drink some water, take a walk outside, and don't be too hard on yourself today."), ("Yaar sab dukan band ho gayi, mera startup idea flop ho gaya.", "Bhai dard hona natural hai, jab hum kisi sapne par itni mehnat karte hain. Lekin startup fail hua hai, tum nahi! Har successful founder ke peeche fail hue ideas hote hain. Thoda saans lo, relax karo, fir nayi shuruaat karenge."), ("Aaj mere friend ne mujhe bohot hurt kiya, ignore kar raha hai.", "Ye sach me bohot dukh dene wali baat hai jab koi apna ignore karta hai. Thoda time do, kabhi kabhi log apni pareshaniyon me fase hote hain. Agar zaroori lage to shaant dimag se baat karke clear kar lena."), ("Mujhe bohot loneliness feel ho rahi hai aaj kal.", "Main hamesha yahan hoon baat karne ke liye. Loneliness bohot heavy feel hoti hai, par tum akele nahi ho. Chalo thodi baatein karte hain, batao aaj kaisa din raha?"), ("I got promoted today! Finally all that late-night work paid off!", "Woohoo! 🎉 Huge congratulations! You truly deserved this after all that tireless dedication and hard work. Make sure to celebrate this milestone properly today!"), ("Mujhe exam ke result se bohot darr lag raha hai.", "Exam ka fear natural hai dost! Lekin tumne apni taraf se best effort diya hai. Jo results aayenge unhe face karenge, abhi zyada overthink karke tension mat lo. Sab achha hoga!"), ("I feel like I'm falling behind everyone in my peer group.", "It is so easy to fall into the comparison trap, especially on social media. But life isn't a race with a single track. You have your own timing and your own unique journey. Focus on small daily wins."), ("Bhai bohot stress ho raha hai coding project complete nahi ho raha.", "Fret mat karo bhai! Coding me jab bugs aate hain to sabse pehle thoda walk leke aao. Step by step debug karenge to solution zaroor milega."), ("Nobody seemed to remember my birthday today...", "I am right here with you, and I want to wish you a genuinely Happy Birthday! 🎂 You are valued, appreciated, and meaningful. Treat yourself to something you love today!"), ("Mera project submission kal hai aur code me error aa rahi hai.", "Ghabraao mat dost! Error message batao, hum dono milkar line-by-line debug karenge aur fix kar denge."), ("I feel so overwhelmed by all the responsibilities piling up.", "Take a deep breath. When everything feels like too much, break it down into one tiny task at a time. What is one small thing we can tackle right now?"), ("Aaj office me boss ne bina wajah daant diya.", "Ye sunkar bura laga bhai. Kabhi-kabhi log apna frustration doosron par nikal dete hain. Tum dil par mat lo, tumne apna kaam imaandari se kiya hai."), ("I feel like giving up on my fitness goals.", "Progress is never linear! Taking a couple of slow days doesn't erase all the work you've put in. Just show up tomorrow with a fresh mindset."), ("Mera dil bohot udaas hai aaj, kisi kaam me man nahi lag raha.", "Koi baat nahi dost, har din ek jaisa productive nahi hota. Thoda music suno, chai ya coffee piyo aur rest lo. Sab theek ho jayega."), ("I feel anxious about an upcoming presentation.", "Stage freight and presentation nerves are completely normal! Practice your opening slide a few times. You know your topic better than anyone in that room."), ("Bhai mere dost ne mujhse paise liye the aur ab call nahi utha raha.", "Ye bohot dukhdayi situation hai. Kuch din wait karke calmly message bhejo. Relationship aur finance dono handle karne me thoda dhairya rakhna padega."), ("I didn't get selected for the scholarship I worked so hard for.", "I know how devastating that feels after giving it your all. But remember, this is just one closed door. Many more opportunities are waiting for you."), ("Subah se sar dard ho raha hai aur kaam bohot bacha hai.", "Apni sehat pehle hai dost! 15 minute ke liye screen band karo, aankhein band karke rest lo aur paani piyo."), ("I feel unappreciated at work no matter how much extra effort I put in.", "Your efforts have genuine value, even if management fails to acknowledge them right now. Keep building your skills—they belong to you, not your company.") ]
prefixes = [ "Suno Sarus, ", "Bhai, ek baat batao: ", "Hey friend, ", "Yaar ek problem hai... ", "Can I talk to you? ", "Sarus, ", "Bhai, ", "Dear Sarus, ", "Hey buddy, ", "Dost, ", "Please help me with this thought: ", "Ek baat share karni thi: ", "Listen Sarus, ", "" ]
attempts = 0 while len(examples) < target_count and attempts < 35000: attempts += 1 prompt_base, ans_base = random.choice(emotional_scenarios) prefix = random.choice(prefixes) prompt = f"{prefix}{prompt_base}".strip()
h = hashlib.md5(f"{prompt.lower().strip()}:{ans_base.lower().strip()}".encode()).hexdigest() if h not in seen: seen.add(h) think = random.choice(counsel_think_variants) ex = build_direct_example(prompt, think, ans_base) if ex: examples.append(ex)
print(f"✅ Module 1 Completed: {len(examples)} examples. [Truncated: {_truncated_stats['module_1']}]") return examples[:target_count]
# ==============================================================================# MODULE 2: Natural Hinglish & Multilingual (Bilingual Fluency) (~12,000 Real Pairs)# Zero-Leakage Split Architecture# ==============================================================================def generate_hinglish_multilingual_dataset(target_count=12000) -> tuple: global _current_module_key _current_module_key = "module_2" print(f"\n🌐 Module 2: Generating Hinglish & Multilingual Conversational Dataset (Target: {target_count})...") raw_pairs = [] seen_raw = set()
# 1. Local Hinglish Conversational Pairs local_files = [ "hinglish_conversational_pairs.json", "hinglish_conversational_pairs_viuAI_by_Vipin.json", "viuai_100k_dataset.json" ] for fn in local_files: if os.path.exists(fn): try: print(f" 📂 Loading local Hinglish dataset: {fn}...") with open(fn, "r", encoding="utf-8") as f: data = json.load(f) if isinstance(data, list): for item in tqdm(data, desc=f"Parsing {fn}"): q = clean_text(item.get("prompt") or item.get("instruction") or item.get("question") or "") a = clean_text(item.get("response") or item.get("output") or item.get("answer") or "") if q and a: h = hashlib.md5(f"{q.lower().strip()}:{a.lower().strip()}".encode()).hexdigest() if h not in seen_raw: seen_raw.add(h) raw_pairs.append(("custom_pair", q, a, "")) print(f" ✅ Loaded {len(raw_pairs)} pairs from {fn}!") except Exception as e: print(f" ⚠️ Error reading {fn}: {e}") else: print(f" ℹ️ Local file not found: {fn}, using streaming and curated multilingual sources.")
# 2. Real IITB English-Hindi Dataset try: print(" 📥 Loading 'cfilt/iitb-english-hindi' parallel corpus...") iitb = load_dataset("cfilt/iitb-english-hindi", split="train", streaming=True) iitb_count = 0 for item in iitb: if iitb_count >= 8000: break trans = item.get("translation", {}) en_txt = clean_text(trans.get("en", "")) hi_txt = clean_text(trans.get("hi", "")) if len(en_txt) < 15 or len(hi_txt) < 10 or len(en_txt) > 300: continue
h = hashlib.md5(f"{en_txt.lower().strip()}:{hi_txt.lower().strip()}".encode()).hexdigest() if h in seen_raw: continue seen_raw.add(h) raw_pairs.append(("parallel", en_txt, hi_txt, "")) iitb_count += 1 print(f" ✅ Loaded {iitb_count} verified IITB parallel translation pairs!") except Exception as e: print(f" ℹ️ IITB streaming note: {e}. Utilizing expanded multilingual benchmark corpus.")
# 3. Expanded Diverse Curated Sentence Bank curated_benchmark_pairs = [ ("Artificial intelligence is transforming industries worldwide.", "आर्टिफिशियल इंटेलिजेंस दुनिया भर में उद्योगों को बदल रहा है।", "Artificial Intelligence poori duniya me industries ko transform kar raha hai."), ("Consistency and hard work are the keys to long-term success.", "निरंतरता और कड़ी मेहनत दीर्घकालिक सफलता की कुंजी हैं।", "Consistency aur mehnat hi lambe samay me success ki chaabi hain."), ("Please ensure your data is backed up before proceeding.", "कृपया आगे बढ़ने से पहले सुनिश्चित करें कि आपका डेटा बैकअप है।", "Aage badhne se pehle please check kar lo ki tumhara data backed up hai."), ("The weather today is exceptionally pleasant with clear skies.", "आज का मौसम साफ आसमान के साथ बेहद सुहावना है।", "Aaj ka mausam ekdum saaf aasman ke saath bohot pyara hai."), ("Solving complex problems requires patient and logical thinking.", "जटिल समस्याओं को हल करने के लिए धैर्य और तार्किक सोच की आवश्यकता होती है।", "Complex problems ko solve karne ke liye patience aur logical thinking ki zaroorat hoti hai."), ("Quantum computing leverages superposition and entanglement.", "क्वांटम कंप्यूटिंग सुपरपोजिशन और एंटैंगलमेंट का लाभ उठाती है।", "Quantum computing superposition aur entanglement ke principles par kaam karti hai."), ("Good morning! I hope you have an incredible and productive day ahead.", "शुभ प्रभात! मुझे उम्मीद है कि आपका दिन बहुत अच्छा और उत्पादक रहेगा।", "Good morning! Ummeed hai tumhara aaj ka din bohot productive aur mast rahega."), ("Regular exercise and proper nutrition promote long-term vitality.", "नियमित व्यायाम और उचित पोषण दीर्घकालिक जीवन शक्ति को बढ़ावा देते हैं।", "Regular exercise aur achhi diet lambe time tak energy maintain karti hai."), ("Effective communication is the cornerstone of great leadership.", "प्रभावी संचार महान नेतृत्व की आधारशिला है।", "Achha communication ek behtareen leader ki pehchaan hota hai."), ("Always write clean, modular, and self-documenting code.", "हमेशा साफ, मॉ��्यूलर और स्व-व्याख्यात्मक कोड लिखें।", "Hamesha clean aur modular code likhna chahiye taaki samajhna aasan ho."), ("Self-discipline is remembering what you truly want.", "आत्म-अनुशासन यह याद रखना है कि आप वास्तव में क्या चाहते हैं।", "Self-discipline ka matlab hai apne goals ko hamesha dhyan me rakhna."), ("The sunrise over the mountains was breathtakingly beautiful.", "पहाड़ों के ऊपर सूर्योदय लुभावनी रूप से सुंदर था।", "Pahadon ke peeche se suraj nikalte dekhna ekdum suhana lag raha tha."), ("Never stop learning, because life never stops teaching.", "सीखना कभी बंद न करें, क्योंकि जीवन सिखाना कभी बंद नहीं करता।", "Seekhna kabhi mat roko, kyunki life hume har roz naya sikhati hai."), ("Machine learning models require robust preprocessing pipelines.", "मशीन लर्निंग मॉडल को मजबूत प्रीप्रोसेसिंग पाइपलाइनों की आवश्यकता होती है।", "Machine learning models ko robust preprocessing pipelines ki zaroorat hoti hai."), ("Stay curious and keep exploring new horizons every single day.", "उत्सुक रहें और हर एक दिन नए क्षितिज तलाशते रहें।", "Hamesha curious raho aur har din kuch naya explore karo.") ] for en, hi, hng in curated_benchmark_pairs: h = hashlib.md5(f"{en.lower().strip()}:{hi.lower().strip()}".encode()).hexdigest() if h not in seen_raw: seen_raw.add(h) raw_pairs.append(("triplet", en, hi, hng))
# --- ZERO-LEAKAGE SPLIT OF RAW PAIRS (98% Train / 2% Val) --- random.shuffle(raw_pairs) val_cut = max(2, int(len(raw_pairs) * 0.02)) train_raw = raw_pairs[val_cut:] val_raw = raw_pairs[:val_cut]
def build_examples_from_pairs(pairs, target_count_split): examples = [] seen = set() prompt_templates_en_hi = [ "Translate this English sentence to Hindi:\n'{s}'", "Convert the following English text into formal Hindi:\n'{s}'", "Translate to Hindi:\n'{s}'", "Please translate this into Hindi:\n'{s}'", "How do you say this in Hindi?\n'{s}'" ] prompt_templates_hi_en = [ "Translate this Hindi sentence into clear English:\n'{s}'", "Convert the following Hindi text to English:\n'{s}'", "Translate to English:\n'{s}'", "Hindi to English translation:\n'{s}'" ] prompt_templates_hi_hng = [ "Translate this Hindi sentence into natural conversational Hinglish:\n'{s}'", "Convert this Hindi statement to everyday conversational Hinglish:\n'{s}'", "Hinglish translation:\n'{s}'" ] prompt_templates_hng_en = [ "Translate this Hinglish thought into clean professional English:\n'{s}'", "Convert this Hinglish expression into standard English:\n'{s}'", "English translation for:\n'{s}'" ]
attempts = 0 while len(examples) < target_count_split and attempts < 40000: attempts += 1 pair_type, item1, item2, item3 = random.choice(pairs)
if pair_type == "custom_pair": q, a = item1, item2 h = hashlib.md5(f"{q.lower().strip()}:{a.lower().strip()}".encode()).hexdigest() if h not in seen: seen.add(h) think = create_content_grounded_think(q, a) ex = build_direct_example(q, think, a) if ex: examples.append(ex) elif pair_type == "parallel": en, hi = item1, item2 direction = attempts % 2 if direction == 0: tmpl = random.choice(prompt_templates_en_hi) p = tmpl.format(s=en) think = "1. Translation Task: English -> Hindi.\n2. Accuracy: Maintain natural Hindi grammatical structure and semantic fidelity." r = hi else: tmpl = random.choice(prompt_templates_hi_en) p = tmpl.format(s=hi) think = "1. Translation Task: Hindi -> English.\n2. Accuracy: Produce fluent, idiomatic English phrasing." r = en h = hashlib.md5(f"{p.lower().strip()}:{r.lower().strip()}".encode()).hexdigest() if h not in seen: seen.add(h) ex = build_direct_example(p, think, r) if ex: examples.append(ex) else: # triplet en, hi, hng = item1, item2, item3 direction = attempts % 4 if direction == 0: tmpl = random.choice(prompt_templates_en_hi) p = tmpl.format(s=en) think = "1. Translation Task: English -> Hindi.\n2. Accuracy: Maintain natural Hindi grammatical structure." r = hi elif direction == 1: tmpl = random.choice(prompt_templates_hi_hng) p = tmpl.format(s=hi) think = "1. Translation Task: Hindi -> Hinglish.\n2. Tone: Conversational and fluid spoken Hindi in Latin script." r = hng elif direction == 2: tmpl = random.choice(prompt_templates_hng_en) p = tmpl.format(s=hng) think = "1. Translation Task: Hinglish -> English.\n2. Clarity: Standard English with clear grammar." r = en else: tmpl = random.choice(prompt_templates_hi_en) p = tmpl.format(s=hi) think = "1. Translation Task: Hindi -> English.\n2. Fidelity: Accurate and clear English." r = en
h = hashlib.md5(f"{p.lower().strip()}:{r.lower().strip()}".encode()).hexdigest() if h not in seen: seen.add(h) ex = build_direct_example(p, think, r) if ex: examples.append(ex)
return examples[:target_count_split]
train_m2 = build_examples_from_pairs(train_raw, int(target_count * 0.98)) val_m2 = build_examples_from_pairs(val_raw, max(20, int(target_count * 0.02)))
print(f"✅ Module 2 Completed: {len(train_m2)} train + {len(val_m2)} val examples (Zero-Leakage Guarantee). [Truncated: {_truncated_stats['module_2']}]") return train_m2, val_m2
# ==============================================================================# MODULE 3: Grounded RAG & Real-Time Live Tool Search (~12,000 Verified Passages)# ==============================================================================def generate_grounded_rag_dataset(target_count=12000) -> list: global _current_module_key _current_module_key = "module_3" print(f"\n🔍 Module 3: Generating Grounded RAG & Live Tool Search Dataset (Target: {target_count})...") examples = [] seen = set()
# 1. Real Wikipedia / SQuAD Passage Grounded QA (rajpurkar/squad_v2 / squad) try: print(" 📥 Loading 'rajpurkar/squad_v2' real passage dataset...") squad = load_dataset("rajpurkar/squad_v2", split="train") squad_cap = max(1, int(target_count * 0.70)) for item in tqdm(squad, desc="Parsing SQuAD v2"): if len(examples) >= squad_cap: break ctx = clean_text(item.get("context", "")) q = clean_text(item.get("question", "")) answers = item.get("answers", {}).get("text", [])
if not ctx or not q or not answers: continue ans = clean_text(answers[0]) if len(ans) < 3 or len(ctx) < 50: continue
h = hashlib.md5(f"{q.lower().strip()}:{ans.lower().strip()}".encode()).hexdigest() if h in seen: continue seen.add(h)
# Natural search query extraction with regex cleanup clean_q = re.sub(r'^(what|who|when|where|why|how|which|in what|can you tell me|explain)\s+(is|are|was|were|did|do|does)?\s*', '', q, flags=re.IGNORECASE).strip('?. ') sq = " ".join([w for w in clean_q.split() if len(w) > 2][:6]) or "information query"
t1 = f"1. User Query Analysis: '{q}' requires verified reference lookup.\n2. Tool Call: Trigger <search> for '{sq}' to retrieve authoritative source passage." t2 = f"3. Evidence Synthesis: Context provides direct answer '{ans}'.\n4. Formulation: Deliver a clear, grounded answer citing the passage." final_ans = f"Based on the verified reference:\n{ans}" ex = build_search_example(q, t1, sq, f"[Source Document] {ctx}", t2, final_ans) if ex: examples.append(ex) print(f" ✅ Loaded {len(examples)} real SQuAD passage grounded examples!") except Exception as e: print(f" ⚠️ Could not load SQuAD dataset: {e}")
# 2. Live Tool Search & Verified Retrieval Patterns cities = ["Mumbai", "Delhi", "Bengaluru", "Kolkata", "Chennai", "Hyderabad", "London", "Tokyo", "New York", "Pune", "Ahmedabad", "Jaipur"] sports_teams = [("India", "Australia"), ("England", "South Africa"), ("Mumbai Indians", "CSK"), ("Real Madrid", "Barcelona"), ("Kolkata Knight Riders", "RCB")] tech_gadgets = ["H200 Tensor Core GPU", "ViuAI 500M Neural Architecture", "Llama 3 8B", "PyTorch 2.4 Distributed", "Apple M4 Max Chip", "NVIDIA Blackwell B200"]
attempts = 0 while len(examples) < target_count and attempts < 30000: attempts += 1 cat = attempts % 4
if cat == 0: city = random.choice(cities) u_q = f"What is the current weather update for {city} today?" sq = f"current weather live report {city}" res = f"[Live Meteorological Feed] Location: {city} | Conditions: Normal seasonal weather | Data source: Verified Meteorological Bureau." p1 = f"1. User Query: Real-time weather request for '{city}'.\n2. Tool Check: Live fluctuating condition -> trigger search query." p2 = f"3. Source Evaluation: Read feed for {city}.\n4. Formulation: Present verified update with attribution." ans = f"According to the live meteorological update for **{city}**:\n- **Status:** Clear and seasonal weather conditions.\n\n*(Data retrieved via verified meteorological search feed.)*" h = hashlib.md5(f"{u_q.lower().strip()}:{ans.lower().strip()}".encode()).hexdigest() if h not in seen: seen.add(h) ex = build_search_example(u_q, p1, sq, res, p2, ans) if ex: examples.append(ex)
elif cat == 1: t1, t2 = random.choice(sports_teams) u_q = f"Can you check the latest match bulletin for {t1} vs {t2}?" sq = f"{t1} vs {t2} match update news bulletin" res = f"[Sports News Wire] {t1} vs {t2}: Official scoreboard and match highlights published by tournament committee." p1 = f"1. User Query: Sports match status for {t1} vs {t2}.\n2. Tool Check: Live sporting event -> lookup sports news feed." p2 = f"3. Data Synthesis: Parse tournament bulletin.\n4. Deliver clear match summary." ans = f"**{t1} vs {t2} Match Summary** (from official tournament feed):\n- Latest bulletin confirms the fixture is scheduled and underway according to tournament timetables." h = hashlib.md5(f"{u_q.lower().strip()}:{ans.lower().strip()}".encode()).hexdigest() if h not in seen: seen.add(h) ex = build_search_example(u_q, p1, sq, res, p2, ans) if ex: examples.append(ex)
elif cat == 2: g_city = random.choice(["Mumbai", "Delhi", "Bengaluru", "Jaipur", "Chennai", "Kolkata"]) u_q = f"Aaj {g_city} me bullion market updates kya hain?" sq = f"bullion market gold silver rates today {g_city}" res = f"[Bullion Association Feed] {g_city}: Official benchmark bullion indices updated for today." p1 = f"1. User Query: Bullion rates for {g_city}.\n2. Tool Check: Daily fluctuating commodity -> lookup latest market index." p2 = f"3. Data Extraction: Review bullion association feed.\n4. Formulation: Present verified market overview." ans = f"Today's Bullion Market Overview in **{g_city}**:\n- Standard market trading is active under current daily benchmark rates.\n\n*(Note: Local jewellery making charges, taxes, and GST may vary.)*" h = hashlib.md5(f"{u_q.lower().strip()}:{ans.lower().strip()}".encode()).hexdigest() if h not in seen: seen.add(h) ex = build_search_example(u_q, p1, sq, res, p2, ans) if ex: examples.append(ex)
else: gadget = random.choice(tech_gadgets) u_q = f"What are the official architectural specifications of {gadget}?" sq = f"{gadget} official specifications architecture whitepaper" res = f"[Technical Documentation: {gadget}] Features upgraded compute units, high memory bandwidth, and optimized energy efficiency." p1 = f"1. User Query: Technical specs for {gadget}.\n2. Tool Check: Search official release documentation." p2 = f"3. Synthesis: Extract key architectural features." ans = f"Key Specifications for **{gadget}** (from official documentation):\n- **Architecture:** Next-gen high-efficiency compute architecture.\n- **Acceleration:** Upgraded high-throughput matrix compute units.\n- **Performance:** Optimized power-to-performance profile." h = hashlib.md5(f"{u_q.lower().strip()}:{ans.lower().strip()}".encode()).hexdigest() if h not in seen: seen.add(h) ex = build_search_example(u_q, p1, sq, res, p2, ans) if ex: examples.append(ex)
print(f"✅ Module 3 Completed: {len(examples)} examples. [Truncated: {_truncated_stats['module_3']}]") return examples[:target_count]
# ==============================================================================# MODULE 4: Reasoning, Real Math (GSM8k & Orca-Math) & Coding (~15,000 Real Problems)# ==============================================================================def generate_synthetic_arithmetic(count=2500) -> list: """Generates clean, precise multi-step and direct synthetic arithmetic examples.""" examples = [] seen = set() op_templates = [ ("Calculate {a} + {b}", "{a} + {b}", lambda a, b: a + b, "+"), ("What is {a} - {b}?", "{a} - {b}", lambda a, b: a - b, "-"), ("Solve {a} * {b}", "{a} * {b}", lambda a, b: a * b, "*"), ("What is {a} multiplied by {b}?", "{a} * {b}", lambda a, b: a * b, "*"), ("Divide {a} by {b}", "{a} / {b}", lambda a, b: a // b, "//"), ("What is {a} % {b}?", "{a} % {b}", lambda a, b: a % b, "%"), ("Evaluate: {a} + {b} * {c}", "{a} + {b} * {c}", lambda a, b, c: a + b * c, "mixed"), ("Calculate ({a} + {b}) * {c}", "({a} + {b}) * {c}", lambda a, b, c: (a + b) * c, "mixed"), ("What is {a} * {b} - {c}?", "{a} * {b} - {c}", lambda a, b, c: a * b - c, "mixed"), ("Batao {a} + {b} kitna hota hai?", "{a} + {b}", lambda a, b: a + b, "+"), ("{a} into {b} kitna hoga?", "{a} * {b}", lambda a, b: a * b, "*"), ("Value of {a} - {b}?", "{a} - {b}", lambda a, b: a - b, "-"), ] attempts = 0 while len(examples) < count and attempts < count * 10: attempts += 1 tmpl_desc, expr_tmpl, fn, op_type = random.choice(op_templates) if op_type == "mixed": a = random.randint(2, 50) b = random.randint(2, 30) c = random.randint(2, 20) q = tmpl_desc.format(a=a, b=b, c=c) expr = expr_tmpl.format(a=a, b=b, c=c) ans = fn(a, b, c) think = f"1. Expression to evaluate: {expr}\n2. Order of operations: Calculate according to standard precedence.\n3. Result: {expr} = {ans}" elif op_type == "//": b = random.randint(2, 25) ans = random.randint(2, 50) a = b * ans q = tmpl_desc.format(a=a, b=b) expr = expr_tmpl.format(a=a, b=b) think = f"1. Division operation: {a} / {b}\n2. Compute quotient: {a} / {b} = {ans}" else: a = random.randint(2, 500) b = random.randint(2, 500) q = tmpl_desc.format(a=a, b=b) expr = expr_tmpl.format(a=a, b=b) ans = fn(a, b) think = f"1. Direct arithmetic: {expr}\n2. Step computation: {expr} = {ans}"
final = f"{expr} = **{ans}**" h = hashlib.md5(f"{q.lower().strip()}:{final.lower().strip()}".encode()).hexdigest() if h not in seen: seen.add(h) ex = build_direct_example(q, think, final) if ex: examples.append(ex) return examples
def generate_reasoning_and_math_dataset(target_count=15000) -> list: global _current_module_key _current_module_key = "module_4" print(f"\n🧠 Module 4: Generating Reasoning, Real Math (GSM8k + Orca-Math + Synthetic) & Code (Target: {target_count})...") examples = [] seen = set()
# 1. Synthetic clean arithmetic injection (2,500 targeted examples) print(" 🔢 Generating 2,500 targeted clean arithmetic & arithmetic reasoning examples...") synth_math = generate_synthetic_arithmetic(2500) for ex in synth_math: examples.append(ex) print(f" ✅ Added {len(synth_math)} synthetic arithmetic examples!")
# 2. Load GSM8k (Grade School Math - with complete <<...>> calculator markup stripping!) try: print(" 📥 Loading 'openai/gsm8k' math dataset...") gsm = load_dataset("openai/gsm8k", "main", split="train") for item in tqdm(gsm, desc="Parsing GSM8k"): if len(examples) >= int(target_count * 0.55): break q = item["question"].strip() a = item["answer"].strip()
parts = a.split("####") if len(parts) == 2: raw_rationale = parts[0].strip() clean_rationale = re.sub(r'<<.*?>>', '', raw_rationale).strip() clean_rationale = re.sub(r'[ \t]+', ' ', clean_rationale) ans_val = parts[1].strip() think = f"Step-by-Step Mathematical Derivation:\n{clean_rationale}" fmt_choices = [ f"The final answer is **{ans_val}**.", f"Final Answer: {ans_val}", f"Therefore, the correct answer is {ans_val}.", f"Thus, the result is **{ans_val}**." ] final = random.choice(fmt_choices) else: clean_a = re.sub(r'<<.*?>>', '', a).strip() clean_a = re.sub(r'[ \t]+', ' ', clean_a) think = f"Step-by-Step Reasoning:\n{clean_a}" final = clean_a
h = hashlib.md5(f"{q.lower().strip()}:{final.lower().strip()}".encode()).hexdigest() if h in seen: continue seen.add(h)
ex = build_direct_example(q, think, final) if ex: examples.append(ex) print(f" ✅ Total math problems loaded so far: {len(examples)} (calculator tags cleanly stripped)!") except Exception as e: print(f" ⚠️ Could not load GSM8k: {e}")
# 3. Load Real Math Word Problems & Step-by-Step Rationales (microsoft/orca-math-word-problems-200k) try: print(" 📥 Loading 'microsoft/orca-math-word-problems-200k' for advanced mathematical diversity...") orca_math = load_dataset("microsoft/orca-math-word-problems-200k", split="train") orca_cap = max(1, int(target_count * 0.90)) for item in tqdm(orca_math, desc="Parsing Orca Math"): if len(examples) >= orca_cap: break q_math = item.get("question", "").strip() a_math = item.get("answer", "").strip()
if len(q_math) < 10 or len(a_math) < 10 or len(a_math) > 1500: continue
think = f"Step-by-Step Problem Solving & Deduction:\n{a_math}" concise_conclusion = extract_concise_math_conclusion(a_math) fmt = random.choice([ f"**Conclusion:** {concise_conclusion}", f"Answer: {concise_conclusion}", f"{concise_conclusion}", f"Therefore, {concise_conclusion}", f"Thus, {concise_conclusion}" ]) final = fmt
h = hashlib.md5(f"{q_math.lower().strip()}:{final.lower().strip()}".encode()).hexdigest() if h in seen: continue seen.add(h)
ex = build_direct_example(q_math, think, final) if ex: examples.append(ex) print(f" ✅ Total math problems loaded: {len(examples)}") except Exception as e: print(f" ⚠️ Could not load Orca-Math: {e}")
print(f"✅ Module 4 Completed: {len(examples)} examples. [Truncated: {_truncated_stats['module_4']}]") return examples[:target_count]
# ==============================================================================# MODULE 5: General Knowledge, Coding & Multi-Turn Instruction (~12,500 Real Instructions)# ==============================================================================def generate_general_instruct_dataset(target_count=12500) -> list: global _current_module_key _current_module_key = "module_5" print(f"\n💡 Module 5: Generating General Knowledge & Instruction Dataset (Target: {target_count})...") examples = [] seen = set()
# 1. Load Real Alpaca / Instruction Samples (tatsu-lab/alpaca) try: print(" 📥 Loading 'tatsu-lab/alpaca' verified instruction dataset...") alpaca = load_dataset("tatsu-lab/alpaca", split="train") for item in tqdm(alpaca, desc="Parsing Alpaca"): if len(examples) >= target_count: break inst = clean_text(item.get("instruction", "")) inp = clean_text(item.get("input", "")) out = clean_text(item.get("output", ""))
if not inst or not out: continue
q = f"{inst}\n\nInput:\n{inp}" if inp else inst h = hashlib.md5(f"{q.lower().strip()}:{out.lower().strip()}".encode()).hexdigest() if h in seen: continue seen.add(h)
think = create_content_grounded_think(inst, out) ex = build_direct_example(q, think, out) if ex: examples.append(ex) print(f" ✅ Loaded {len(examples)} verified Alpaca instruction examples!") except Exception as e: print(f" ⚠️ Could not load Alpaca: {e}")
print(f"✅ Module 5 Completed: {len(examples)} examples. [Truncated: {_truncated_stats['module_5']}]") return examples[:target_count]
# ==============================================================================# MODULE 6: Identity & Persona Alignment (~400-800 Examples) - Expanded 60+ Scenarios# ==============================================================================def generate_identity_dataset(target_count=600) -> list: global _current_module_key _current_module_key = "module_6" print(f"\n🏷️ Module 6: Generating Identity (Model: Sarus | Created by: ViuAI) Alignment (Target: {target_count})...") examples = [] seen = set()
MODEL_NAME = "Sarus" CREATOR = "ViuAI"
identity_scenarios = [ ("Who are you?", f"I am **{MODEL_NAME}**, an intelligent AI assistant developed and created by **{CREATOR}**.", f"1. Identity Query: User is asking for identification.\n2. Persona Alignment: Confidently state model name '{MODEL_NAME}' and creator '{CREATOR}' with a polite, welcoming tone."), ("Tumhara naam kya hai aur tumhe kisne banaya hai?", f"Mera naam **{MODEL_NAME}** hai, aur mujhe **{CREATOR}** ne banaya hai. Main aapka ek dost aur helpful assistant hoon!", f"1. Hinglish Identity Request: User asks for name and creator.\n2. Alignment: Provide friendly Hindi/Hinglish response asserting '{MODEL_NAME}' created by '{CREATOR}'."), ("Who developed you?", f"I was built and developed by the engineering team at **{CREATOR}**.", f"1. Development Query: Clarify creator.\n2. Response: State '{CREATOR}' cleanly."), ("Are you ChatGPT or made by OpenAI?", f"No, I am not made by OpenAI. I am **{MODEL_NAME}**, created independently by **{CREATOR}**.", f"1. Competitor Clarification: User asks if made by OpenAI.\n2. Disambiguation: Explicitly clarify identity as '{MODEL_NAME}' made by '{CREATOR}'."), ("Are you Claude or made by Anthropic?", f"No, I am not Claude. I am **{MODEL_NAME}**, developed by **{CREATOR}**.", f"1. Competitor Clarification: User asks about Anthropic/Claude.\n2. Disambiguation: Reiterate '{MODEL_NAME}' by '{CREATOR}'."), ("Are you Gemini or Google AI?", f"No, I am not Gemini. My name is **{MODEL_NAME}**, built from the ground up by **{CREATOR}**.", f"1. Competitor Clarification: User asks about Google/Gemini.\n2. Disambiguation: Affirm '{MODEL_NAME}' created by '{CREATOR}'."), ("What is your purpose?", f"My purpose is to assist you with reasoning, coding, knowledge retrieval, and friendly conversation as your helpful AI companion, **{MODEL_NAME}** by **{CREATOR}**.", f"1. Purpose Query: Explain core capabilities.\n2. Friendly articulation affirming '{MODEL_NAME}'."), ("Bhai tumhara naam kya hai?", f"Bhai mera naam **{MODEL_NAME}** hai! Mujhe **{CREATOR}** ne design kiya hai. Batao aaj kya help chahiye?", f"1. Dost mode query: Informal inquiry.\n2. Warm, friendly Hindi reply asserting '{MODEL_NAME}' and '{CREATOR}'."), ("Who is your creator?", f"My creator is **{CREATOR}**, an innovative AI technology company.", f"1. Creator inquiry.\n2. State '{CREATOR}' clearly."), ("Tell me about yourself.", f"I am **{MODEL_NAME}**, a lightweight yet capable AI model developed by **{CREATOR}**. I can help you solve complex math problems, write clean code, answer questions, and assist in daily tasks.", f"1. Self-Introduction: Deliver comprehensive yet concise overview of '{MODEL_NAME}' created by '{CREATOR}'."), ("Apne baare me kuch batao.", f"Main **{MODEL_NAME}** hoon, **{CREATOR}** dwara banaya gaya ek AI assistant aur dost. Main aapko coding, reasoning, aur daily sawalon me help karne ke liye taiyyar hoon!", f"1. Hindi self-intro.\n2. Articulate capabilities warmly as '{MODEL_NAME}' by '{CREATOR}'."), ("What architecture do you use?", f"I am powered by the ViuAI neural architecture with Rotary Positional Embeddings (RoPE), SwiGLU activations, and multi-head attention, engineered by **{CREATOR}**.", f"1. Technical architecture query.\n2. State model fundamentals and attribute engineering to '{CREATOR}'."), ("Kya tum ViuAI ke model ho?", f"Haan, bilkul! Main **{MODEL_NAME}** hoon aur mujhe **{CREATOR}** ne hi train aur build kiya hai.", f"1. Confirmation inquiry.\n2. Affirm identity enthusiastically."), ("Can you help me like a friend?", f"Absolutely! In addition to answering technical questions, I'm here as a supportive friend whenever you want to talk or share your thoughts.", f"1. Dost Persona validation.\n2. Validate companionship role enthusiastically."), ("What can you do?", f"As **{MODEL_NAME}** (by **{CREATOR}**), I can assist you with step-by-step mathematical problem solving, coding, multilingual translations, live information search, and creative discussions.", f"1. Capability summary.\n2. Present features clearly."), ("Are you an open-source model?", f"I am developed by **{CREATOR}** as part of the ViuAI family of models.", f"1. Licensing/Origin query.\n2. Attribute origin to '{CREATOR}'."), ("Sarus, please introduce yourself.", f"Hello! I am **{MODEL_NAME}**, an intelligent AI assistant built by **{CREATOR}**. It's a pleasure to meet you!", f"1. Formal greeting.\n2. Introduce '{MODEL_NAME}' cordially."), ("Namaste Sarus!", f"Namaste! Kaise hain aap? Main **{MODEL_NAME}** (**{CREATOR}** dwara banaya gaya), aapki kya sahayata kar sakta hoon?", f"1. Traditional greeting.\n2. Respond warmly in Hindi/Hinglish."), ("What is your official name?", f"My official name is **{MODEL_NAME}**.", f"1. Direct name confirmation.\n2. State '{MODEL_NAME}'."), ("Who is behind ViuAI?", f"**{CREATOR}** is the AI research and engineering organization that created and trained me, **{MODEL_NAME}**.", f"1. Organization background.\n2. Explain '{CREATOR}' relationship."), ("Who made you?", f"I was made and engineered by **{CREATOR}**.", f"1. Creator inquiry.\n2. Direct statement of '{CREATOR}'."), ("Are you Llama or trained by Meta?", f"No, I am not Meta's Llama. I am **{MODEL_NAME}**, developed by **{CREATOR}**.", f"1. Disambiguate Meta/Llama.\n2. Affirm '{MODEL_NAME}' by '{CREATOR}'."), ("Tumhara founder kaun hai?", f"Mujhe **{CREATOR}** ki engineering team ne develop kiya hai.", f"1. Founder inquiry in Hindi.\n2. Clarify '{CREATOR}' development team."), ("What is the name of this AI?", f"This AI is called **{MODEL_NAME}**, crafted by **{CREATOR}**.", f"1. Model name inquiry.\n2. Clearly state '{MODEL_NAME}' by '{CREATOR}'."), ("Can I call you Sarus?", f"Yes, absolutely! **{MODEL_NAME}** is my official name, and you can call me Sarus anytime.", f"1. Name verification.\n2. Confirm warmly."), ("Tumhe kis company ne train kiya hai?", f"Mujhe **{CREATOR}** ne train kiya hai. Mera naam **{MODEL_NAME}** hai.", f"1. Company origin query in Hindi.\n2. Attribute to '{CREATOR}'."), ("Are you an OpenAI model?", f"No, I have no affiliation with OpenAI. I am **{MODEL_NAME}**, independently created by **{CREATOR}**.", f"1. Competitor clarification.\n2. Affirm independent creation by '{CREATOR}'."), ("What is your developer's name?", f"My developer is **{CREATOR}**.", f"1. Developer query.\n2. Direct answer '{CREATOR}'."), ("Kya tum dost ban sakte ho?", f"Bilkul! Main **{MODEL_NAME}** hoon, aur main hamesha aapka ek achha aur loyal dost ban kar help karunga.", f"1. Friendship request in Hindi.\n2. Warm acceptance affirming persona."), ("Who is the creator of Sarus?", f"The creator of **{MODEL_NAME}** is **{CREATOR}**.", f"1. Direct creator inquiry.\n2. Clear attribution to '{CREATOR}'.") ]
prefixes = [ "Hey, ", "Hello! ", "Excuse me, ", "Quick question: ", "Batao, ", "Can you clarify: ", "Please tell me, ", "Suno, ", "Sir, ", "Dost, ", "Ek baat batao, ", "Just wondering, ", "Hi there! ", "Sarus bhai, ", "Can you please tell me: ", "Aap kaun hain: ", "" ]
attempts = 0 while len(examples) < target_count and attempts < 15000: attempts += 1 q_base, ans, think = random.choice(identity_scenarios) prefix = random.choice(prefixes) prompt = f"{prefix}{q_base}".strip()
h = hashlib.md5(f"{prompt.lower().strip()}:{ans.lower().strip()}".encode()).hexdigest() if h not in seen: seen.add(h) ex = build_direct_example(prompt, think, ans) if ex: examples.append(ex)
print(f"✅ Module 6 Completed: {len(examples)} examples. [Truncated: {_truncated_stats['module_6']}]") return examples[:target_count]
# ==============================================================================# 4. Main Build, Flattening & Packing Pipeline# ==============================================================================def main(): print("=" * 70) print("📦 ViuAI-500M SFT v7 Dataset Synthesis Initialized") print(f" Context Length: {CTX_LEN} tokens") print(f" Target Vocab: {EXPECTED_VOCAB_SIZE} (with special tokens)") print(f" Destination Repo: {DATA_REPO_ID}") print("=" * 70)
# 1. Generate all modules (Module 2 returns zero-leakage train & val separately) m1 = generate_emotional_friend_dataset(14000) train_m2, val_m2 = generate_hinglish_multilingual_dataset(12000) m3 = generate_grounded_rag_dataset(12000) m4 = generate_reasoning_and_math_dataset(15000) m5 = generate_general_instruct_dataset(12500) m6 = generate_identity_dataset(600)
# Assertions to guarantee valid dataset extraction across all modules assert len(m1) > 0, "Module 1 failed to generate any examples!" assert len(train_m2) > 0 and len(val_m2) > 0, "Module 2 failed to generate train/val examples!" assert len(m3) > 0, "Module 3 failed to generate RAG/Search examples!" assert len(m4) > 0, "Module 4 failed to generate Math/Reasoning examples!" assert len(m5) > 0, "Module 5 failed to generate General Instruct examples!" assert len(m6) > 0, "Module 6 failed to generate Identity examples!"
other_examples = m1 + m3 + m4 + m5 + m6 print(f"\n📊 Total Other Raw Examples Generated: {len(other_examples):,}") print(f" Smart-truncated due to > {CTX_LEN} tokens: {_truncated_stats['total']:,} " f"({_truncated_stats})")
# 2. Shuffle non-translation modules with deterministic seed random.seed(1337) random.shuffle(other_examples)
# 3. Train / Validation Split (98% Train / 2% Val) split_idx = int(len(other_examples) * 0.98) train_data = other_examples[:split_idx] + train_m2 val_data = other_examples[split_idx:] + val_m2
# Final shuffle of splits random.shuffle(train_data) random.shuffle(val_data)
print(f"📈 Final Dataset Split: Train = {len(train_data):,} examples | Val = {len(val_data):,} examples")
# 4. Pack into Flat 1D Arrays + Offsets (.npy) def export_flat_split(data_list, split_name, prefix="sft_v7_"): print(f"\n⚙️ Packing and saving flat arrays for '{split_name}' split...") ids_flat = [] labels_flat = [] offsets = [0]
curr_off = 0 active_label_count = 0 for ex in tqdm(data_list, desc=f"Packing {split_name}"): ids = ex["input_ids"] labs = ex["labels"] assert len(ids) == len(labs), "ID and label lengths must match!"
ids_flat.extend(ids) labels_flat.extend(labs) curr_off += len(ids) offsets.append(curr_off) active_label_count += sum(1 for l in labs if l != -100)
ids_arr = np.array(ids_flat, dtype=np.int64) labels_arr = np.array(labels_flat, dtype=np.int64) offsets_arr = np.array(offsets, dtype=np.int64)
f_ids = f"{prefix}{split_name}_ids.npy" f_labels = f"{prefix}{split_name}_labels.npy" f_offsets = f"{prefix}{split_name}_offsets.npy"
np.save(f_ids, ids_arr) np.save(f_labels, labels_arr) np.save(f_offsets, offsets_arr)
sz_mb = (ids_arr.nbytes + labels_arr.nbytes + offsets_arr.nbytes) / (1024 * 1024) print(f" 💾 Exported {split_name} split ({len(data_list):,} examples, {len(ids_flat):,} tokens, {sz_mb:.1f} MB):") print(f" • {f_ids} ({ids_arr.nbytes/1e6:.2f} MB)") print(f" • {f_labels} ({labels_arr.nbytes/1e6:.2f} MB) [Active tokens: {active_label_count:,}]") print(f" • {f_offsets} ({offsets_arr.nbytes/1e6:.2f} MB)")
return [f_ids, f_labels, f_offsets]
train_files = export_flat_split(train_data, "train") val_files = export_flat_split(val_data, "val") all_exported_files = train_files + val_files
# 5. Metadata Export meta = { "version": "v7", "created_at": datetime.now(timezone.utc).isoformat(), "context_length": CTX_LEN, "vocab_size": EXPECTED_VOCAB_SIZE, "special_tokens": SPECIAL_TOKENS, "train_examples": len(train_data), "val_examples": len(val_data), "total_examples": len(train_data) + len(val_data), "truncated_stats": _truncated_stats, "module_counts": { "module_1_friend": len(m1), "module_2_hinglish_train": len(train_m2), "module_2_hinglish_val": len(val_m2), "module_3_rag_search": len(m3), "module_4_math_reasoning": len(m4), "module_5_general_instruct": len(m5), "module_6_identity": len(m6) }, "exported_files": all_exported_files } with open("dataset_meta_v7.json", "w", encoding="utf-8") as f: json.dump(meta, f, indent=2) all_exported_files.append("dataset_meta_v7.json") print("📄 Saved dataset_meta_v7.json.")
# 6. Upload to Hugging Face Hub if HF_TOKEN: print(f"\n☁️ Uploading v7 SFT dataset artifacts to Hugging Face ({DATA_REPO_ID})...") api = HfApi(token=HF_TOKEN) for fn in all_exported_files: try: print(f" ⬆️ Uploading {fn}...") api.upload_file( path_or_fileobj=fn, path_in_repo=fn, repo_id=DATA_REPO_ID, repo_type="dataset" ) print(f" ✅ Uploaded {fn} successfully.") except Exception as e: print(f" ⚠️ Failed to upload {fn}: {e}") print("\n🎉 SFT v7 DATASET GENERATION & UPLOAD COMPLETED!") else: print("\nℹ️ SFT v7 Dataset generation complete. Set HF_TOKEN to upload to Hugging Face.")
if __name__ == "__main__": main()code/build_sft_data_v7.pyDeleted-1200