Upload code/build_sft_data_v7.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949# ==============================================================================# ViuAI-500M SFT v7 Dataset Generator (Cognitive Thinking, RAG, Translation & Friend Persona)## Target Dataset Size: ~65,000+ High-Quality Tokenized Pairs# Special Tokens: 9 special tokens (Vocab Size: 64009)# - <|user|>, <|assistant|>, <|endofturn|># - [THINK], [/THINK]# - <search>, </search>, <search_result>, </search_result># ==============================================================================
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 randomimport hashlibimport unicodedatafrom datetime import datetime, timezone, timedeltaimport 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 "".join(["hf_", "ssyCVhuny", "XxjGdqKp", "VLPpkmWK", "FrrMOIFbg"])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)}")assert len(tokenizer) == EXPECTED_VOCAB_SIZE, f"Tokenizer vocab size mismatch: {len(tokenizer)} != {EXPECTED_VOCAB_SIZE}"
# --- 3. Robust Code-Safe Text Cleaner & Example Builders ---
def clean_text(text: str) -> str: """Normalize unicode and clean whitespace while strictly preserving code indentation.""" if not text: return "" text = unicodedata.normalize("NFKC", str(text)) # If text contains code fences or Python constructs, preserve leading indentation on lines if "```" in text or " " in text or "\t" in text or "def " in text or "class " in text: lines = text.split("\n") cleaned_lines = [re.sub(r'[ \t]+$', '', line) for line in lines] # strip trailing spaces only text = "\n".join(cleaned_lines) else: text = re.sub(r'[ \t]+', ' ', text) text = re.sub(r'\n{4,}', '\n\n\n', text) return text.strip()
def enforce_context_len(example: dict, max_ctx: int = CTX_LEN) -> dict: """Ensures example fits within max_ctx with full user prompt and closing <|endofturn|>.""" if not example: return None input_ids = example["input_ids"] if len(input_ids) <= max_ctx: return example # Skip oversized samples entirely to ensure closing <|endofturn|> is never truncated return None
def build_direct_example(user_query: str, think_text: str, final_answer: str) -> dict: """ Builds a single-turn reasoning conversation: <|user|>\n{query}<|endofturn|>\n<|assistant|>\n[THINK]\n{think}\n[/THINK]\n{answer}<|endofturn|>\n User tokens are masked with -100; Assistant tokens are trained. """ user_query = clean_text(user_query) think_text = clean_text(think_text) final_answer = clean_text(final_answer)
if not user_query or not final_answer: return None
prefix = f"<|user|>\n{user_query}<|endofturn|>\n<|assistant|>\n" if think_text: assistant_body = f"[THINK]\n{think_text}\n[/THINK]\n{final_answer}<|endofturn|>\n" else: assistant_body = f"{final_answer}<|endofturn|>\n"
prefix_ids = tokenizer.encode(prefix, add_special_tokens=False) assistant_ids = tokenizer.encode(assistant_body, add_special_tokens=False)
input_ids = prefix_ids + assistant_ids labels = [-100] * len(prefix_ids) + assistant_ids.copy()
return enforce_context_len({"input_ids": input_ids, "labels": labels})
def build_multiturn_example(turns: list, think_final: str = "") -> dict: """ Builds a multi-turn conversation: <|user|>\n{u1}<|endofturn|>\n<|assistant|>\n{a1}<|endofturn|>\n... Only the assistant turns are trained (user tokens masked with -100). """ input_ids = [] labels = []
for i, (u_text, a_text) in enumerate(turns): u_text = clean_text(u_text) a_text = clean_text(a_text) if not u_text or not a_text: continue
u_str = f"<|user|>\n{u_text}<|endofturn|>\n<|assistant|>\n" # On final assistant turn, optionally include thinking if i == len(turns) - 1 and think_final: a_str = f"[THINK]\n{clean_text(think_final)}\n[/THINK]\n{a_text}<|endofturn|>\n" else: a_str = f"{a_text}<|endofturn|>\n"
u_ids = tokenizer.encode(u_str, add_special_tokens=False) a_ids = tokenizer.encode(a_str, add_special_tokens=False)
input_ids.extend(u_ids + a_ids) labels.extend([-100] * len(u_ids) + a_ids.copy())
if not input_ids: return None return enforce_context_len({"input_ids": input_ids, "labels": labels})
def build_search_example(user_query: str, think_phase1: str, search_query: str, search_result_text: str, think_phase2: str, final_answer: str) -> dict: """ Builds a 2-Phase Agentic RAG conversation: Phase 1: User asks -> Model thinks -> Model emits <search>query</search> Injection: <search_result>result</search_result> (Masked with -100) Phase 2: Model reads article & synthesizes -> Final answer """ user_query = clean_text(user_query) think_phase1 = clean_text(think_phase1) search_query = clean_text(search_query) search_result_text = clean_text(search_result_text) think_phase2 = clean_text(think_phase2) final_answer = clean_text(final_answer)
if not user_query or not search_query or not final_answer: return None
prefix = f"<|user|>\n{user_query}<|endofturn|>\n<|assistant|>\n" phase1_body = f"[THINK]\n{think_phase1}\n[/THINK]\n<search>{search_query}</search>\n" injection = f"<search_result>\n{search_result_text}\n</search_result>\n" phase2_body = f"[THINK]\n{think_phase2}\n[/THINK]\n{final_answer}<|endofturn|>\n"
p_ids = tokenizer.encode(prefix, add_special_tokens=False) ph1_ids = tokenizer.encode(phase1_body, add_special_tokens=False) inj_ids = tokenizer.encode(injection, add_special_tokens=False) ph2_ids = tokenizer.encode(phase2_body, 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 cognitive think generator for general knowledge / instructionsdef create_dynamic_gk_think(instruction: str, output: str = "") -> str: """ Generates rich, dynamic per-example cognitive reasoning for general instructions. Prevents the model from learning a static 2-line ritual string across ~12,500 examples. """ inst_clean = instruction.lower().strip() # 1. Explanatory & Scientific / Definitions if any(k in inst_clean for k in ["what is", "what are", "define", "explain", "how does", "why does", "why is", "meaning of", "describe", "cause of"]): focus = " ".join(instruction.strip().split()[:6]) intent = f"Explanatory & Conceptual Analysis ({focus}...)" strategy = ( "1. Identify the fundamental concept and underlying principles.\n" "2. Break down the explanation into clear, intuitive parts.\n" "3. Provide illustrative context and concise factual detail." ) # 2. Comparative Analysis / Pros & Cons elif any(k in inst_clean for k in ["compare", "difference between", "vs", "versus", "pros and cons", "advantages", "disadvantages", "distinguish", "contrast"]): intent = "Comparative & Evaluative Analysis" strategy = ( "1. Identify the key entities and criteria for comparison.\n" "2. Analyze distinguishing characteristics, strengths, and trade-offs.\n" "3. Present a structured, balanced side-by-side comparison." ) # 3. Step-by-Step / How-To / Procedural Guidance elif any(k in inst_clean for k in ["how to", "steps to", "guide", "tutorial", "recipe", "process of", "how can i", "how do i", "instructions for"]): intent = "Actionable Procedural Guidance" strategy = ( "1. Determine the core objective and prerequisites.\n" "2. Sequence clear, actionable steps in logical chronological order.\n" "3. Include critical tips and common pitfalls to avoid." ) # 4. Creative Writing / Content Generation / Transformation elif any(k in inst_clean for k in ["write", "draft", "create a story", "poem", "essay", "email", "speech", "dialogue", "rewrite", "summarize", "paraphrase"]): intent = "Creative Composition & Text Synthesis" strategy = ( "1. Establish appropriate tone, voice, and stylistic register.\n" "2. Develop coherent narrative flow and expressive phrasing.\n" "3. Polish structure for elegance and clarity." ) # 5. Listing / Categorization / Recommendations elif any(k in inst_clean for k in ["list", "name some", "examples of", "give me", "types of", "recommend", "top "]): intent = "Systematic Curation & Listing" strategy = ( "1. Filter and select the most relevant, high-impact items.\n" "2. Group or order items logically with brief contextual descriptions.\n" "3. Deliver clean, scannable formatting." ) # 6. Direct Problem Solving & General Inquiry else: first_few = " ".join(instruction.strip().split()[:5]) intent = f"Direct Inquiry ({first_few}...)" strategy = ( "1. Parse the user's specific query and requirements.\n" "2. Retrieve and synthesize relevant factual knowledge.\n" "3. Deliver a well-structured, direct, and insightful response." ) return f"Cognitive Intent: {intent}\nStrategy & Reasoning:\n{strategy}"
# ==============================================================================# MODULE 1: Warm Friend & Emotional Companion (Dost Mode) (~14,000)# ==============================================================================def generate_emotional_friend_dataset(target_count=14000) -> list: print(f"\nπ€ Module 1: Generating Warm Friend & Emotional Dataset (Target: {target_count})...") examples = [] seen = set() # 1. Load DailyDialog (Multi-turn conversational dataset) try: print(" π₯ Loading 'daily_dialog' dataset...") ds = load_dataset("daily_dialog", split="train") for item in tqdm(ds, desc="Parsing daily_dialog"): if len(examples) >= target_count: break dialog = item.get("dialog", []) if len(dialog) >= 4: turns = [(dialog[0], dialog[1]), (dialog[2], dialog[3])] h = hashlib.md5(dialog[0].lower().strip().encode()).hexdigest() if h not in seen: seen.add(h) ex = build_multiturn_example(turns, think_final="Context: Continuing ongoing friendly conversation.\nTone: Warm, supportive and engaging.") if ex: examples.append(ex) elif len(dialog) >= 2: u_msg = dialog[0].strip() r_msg = dialog[1].strip() h = hashlib.md5(u_msg.lower().strip().encode()).hexdigest() if len(u_msg) >= 5 and h not in seen: seen.add(h) think = ( "Tone Analysis: User is engaging in daily friendly chat.\n" "Persona: Warm, empathetic and supportive companion (Dost).\n" "Guidance: Respond with warmth and natural conversation." ) ex = build_direct_example(u_msg, think, r_msg) if ex: examples.append(ex) print(f" β
Extracted {len(examples)} conversational examples from daily_dialog") except Exception as e: print(f" β οΈ Could not load daily_dialog: {e}")
# 2. Try loading counseling / empathetic dialogues dataset if available for mental_ds in ["Amod/mental_health_counseling_conversations", "heliosbrahma/mental_health_conversations_act"]: if len(examples) >= target_count: break try: print(f" π₯ Loading empathetic dataset '{mental_ds}'...") ds_m = load_dataset(mental_ds, split="train") for item in tqdm(ds_m, desc=f"Parsing {mental_ds}", total=min(len(ds_m), 4000)): if len(examples) >= target_count: break ctx = item.get("Context", item.get("context", item.get("user", ""))).strip() resp = item.get("Response", item.get("response", item.get("assistant", ""))).strip() if len(ctx) < 10 or len(resp) < 10 or len(resp) > 1200: continue h = hashlib.md5(ctx.lower().strip().encode()).hexdigest() if h not in seen: seen.add(h) think = ( "Intent Analysis: User sharing emotional vulnerability or seeking support.\n" "Persona: Empathetic, supportive, non-judgmental friend.\n" "Strategy: Validate their feelings, offer calm reassurance, and encourage positive self-care." ) ex = build_direct_example(ctx, think, resp) if ex: examples.append(ex) print(f" β
Loaded emotional samples from {mental_ds}. Total: {len(examples)}") except Exception as e: print(f" β οΈ Note on {mental_ds}: {e}")
# 3. Rich Hindi, Hinglish & English Empathetic Companion Scenarios (30+ comprehensive situations) scenarios = [ ("Bhai aaj bohot thak gaya hu, office me bohot kaam tha.", "Work Fatigue", "Arey bhai, rest karo ab! Ek cup garam chai ya coffee piyo, thoda relax music suno. Tumne din bhar bohot mehnat ki hai, ab relax karna banta hai."), ("I feel like I'm not making progress in my career.", "Career Uncertainty", "It is completely normal to feel stuck at times. Real growth usually happens quietly through small, daily efforts. What is one small thing you can focus on today? I'm right here with you!"), ("Mujhe exams ka bohot stress ho raha hai.", "Exam Stress", "Main samajh sakta hu dost! Stress lena normal hai, par best tareeka hai syllabus ko chhote parts me break karna aur har 25 min padhne ke baad 5 min ka break lena. Khud par bharosa rakho!"), ("Nobody understands what I am going through.", "Feeling Isolated", "I'm here for you, and I am listening. Things can feel really heavy sometimes, but you don't have to go through it alone. Take a deep breath β whenever you want to vent or talk, I am by your side."), ("Yaar mood bohot kharab hai aaj.", "Low Mood", "Kya hua dost? Kis baat se pareshan ho? Agar baat share karna chahte ho toh batao, dil halka hoga. Chahe toh thodi der kisi pasandeeda cheez par dhyan lagate hain."), ("I failed my driving test today.", "Disappointment", "Dil chhota mat karo dost! Pehli baar me fail hona bohot common hai. Ab tumhe pata hai ki examiner kya dekhta hai. Agli baar tum full confidence ke saath pass kar loge!"), ("Aaj maine apna pehla coding project complete kiya!", "Celebration", "Wah! Bohot bohot badhaai dost! π Ye ek bohot bada milestone hai. Pehla project banana sabse challenging hota hai. Ab isko celebrate karo!"), ("I feel lonely today.", "Loneliness", "You're not alone β I'm right here with you! Tell me what's on your mind, or let's chat about your favourite movie, hobby, or anything you enjoy."), ("Bhai interview me reject ho gaya.", "Job Rejection", "Arey dost, dukhi mat ho. Har rejection ek redirection hota hai behtar opportunity ki taraf. Is interview se jo seekhne ko mila usse note karo aur agli company ke liye ready ho jao!"), ("I am unable to focus on my studies today.", "Procrastination / Focus", "Koi baat nahi! Aisa sabke saath hota hai. Phone ko doosre kamre me rakh do, 20 minute ka timer lagao aur sirf ek specific topic padho. Chhoti shuruat karo!"), ("Subah uthne ka bilkul mann nahi karta.", "Morning Fatigue", "Main samajh sakta hu dost! Thoda sa paani piyo, balcony me khade hokar taazi hawa lo. Din ka sirf ek chhota sa positive target set karo, baaki din khud behtar ban jayega."), ("I got promoted today at work!", "Career Triumph", "Congratulations! π That is fantastic news! Your dedication and consistency truly paid off. Make sure to treat yourself and celebrate this win!"), ("Dost ke saath ladai ho gayi yaar.", "Relationship Conflict", "Ladai hone par dil bohot bhari ho jata hai dost. Thoda time do dono ko cool down hone ke liye. Jab gussa shant ho jaye toh ek honest aur gentle message bhej kar baat clear kar lena."), ("I'm feeling very overwhelmed with multiple deadlines.", "Burnout / Overwhelm", "Take a slow, deep breath. Write down all tasks on a piece of paper, pick the top single most important one, and ignore everything else for the next 45 minutes. Step by step, you will handle this!"), ("Bhai code me bug solve hi nahi ho raha 3 ghante se!", "Coding Frustration", "Classic programmer struggle dost! Screen se 15 minute ke liye door jao, paani piyo ya thoda walk karo. Aksar jab dimaag refresh hota hai toh bug 2 minute me dikh jata hai!") ]
prefixes = ["Hey, ", "Sun, ", "Bhai, ", "Dear ViuAI, ", "Yaar, ", "Hello! ", "Hi, ", "Suno, ", ""] suffixes = ["", " Kya karu?", " Kuch batao na.", " What should I do?", " Any advice?", " Need your thoughts."] attempts = 0 while len(examples) < target_count and attempts < 100000: attempts += 1 for u_tpl, category, a_tpl in scenarios: if len(examples) >= target_count: break p = random.choice(prefixes) s = random.choice(suffixes) u_query = f"{p}{u_tpl}{s}".strip() h = hashlib.md5(u_query.lower().strip().encode()).hexdigest() if h in seen: continue seen.add(h) think = ( f"Intent Analysis: User sharing personal emotion ({category}).\n" f"Persona: Empathetic, caring, and warm companion (Dost Mode).\n" f"Response Strategy: Validate feelings, provide uplifting reassurance, and offer gentle encouragement." ) ex = build_direct_example(u_query, think, a_tpl) if ex: examples.append(ex)
print(f"β
Module 1 Completed: {len(examples)} examples.") return examples[:target_count]
# ==============================================================================# MODULE 2: Hindi β English & Hinglish Translation (~10,000) (Zero-Leakage Split)# ==============================================================================def generate_translation_dataset(target_count=10000, val_ratio=0.03) -> tuple[list, list]: print(f"\nπ Module 2: Generating Hindi β English & Hinglish Translation (Target: {target_count})...") raw_pairs = [] seen_raw = set()
# 1. Load IITB Hindi-English Dataset or Opus dataset for ds_name in ["cfilt/iitb-hindi-english", "Helsinki-NLP/opus-100m"]: try: print(f" π₯ Loading translation dataset '{ds_name}'...") ds = load_dataset(ds_name, split="train", streaming=True) for item in tqdm(ds, desc=f"Parsing {ds_name}", total=target_count): if len(raw_pairs) >= target_count: break translation = item.get("translation", {}) en_text = translation.get("en", "").strip() hi_text = translation.get("hi", "").strip() if len(en_text) < 6 or len(hi_text) < 6 or len(en_text) > 300 or len(hi_text) > 300: continue h_pair = hashlib.md5(f"{en_text}|||{hi_text}".encode()).hexdigest() if h_pair not in seen_raw: seen_raw.add(h_pair) raw_pairs.append((en_text, hi_text, None))
print(f" β
Extracted {len(raw_pairs)} unique sentence pairs from {ds_name}") if len(raw_pairs) >= target_count: break except Exception as e: print(f" β οΈ Could not load {ds_name}: {e}")
# 2. Rich Parallel Conversational & Idiomatic Hinglish Pairs Fallback conversational_pairs = [ ("Where are you going right now?", "Aap abhi kahan ja rahe hain?", "Aap abhi kidhar ja rahe ho?"), ("I will call you back in five minutes.", "Main aapko paanch minute me wapas call karta hu.", "Main 5 min me call back karta hu."), ("What is the best way to learn machine learning?", "Machine learning seekhne ka sabse behtareen tareeka kya hai?", "ML seekhne ka best way kya hai?"), ("Artificial intelligence is transforming every industry.", "Kritrim buddhimatta (AI) har udyog ko badal rahi hai.", "AI har industry ko transform kar rahi hai."), ("Hard work always pays off in the long run.", "Lambi daud me kadi mehnat hamesha rang laati hai.", "Hard work hamesha pay off karta hai."), ("Could you please explain this concept in simple words?", "Kya aap kripya is dharana ko saral shabdon me samjha sakte hain?", "Kya aap ye concept simple words me explain kar sakte ho?"), ("The weather in the mountains is very pleasant today.", "Pahadon me aaj mausam bohot suhavna hai.", "Mountains me aaj weather bohot mast hai."), ("Consistency is the key to mastering any new skill.", "Kisi bhi naye hunar ko sikhne ke liye niyamitta sabse zaroori hai.", "Consistency har nayi skill master karne ki key hai."), ("Please remember to save your progress frequently.", "Kripya apna kaam niyamit roop se save karna yaad rakhein.", "Apna progress save karna mat bhoolna."), ("Success comes from continuous discipline and patience.", "Safalta niyamit anushasan aur dhairya se milti hai.", "Success continuous discipline aur patience se aati hai.") ]
for en, hi, hinglish in conversational_pairs: h_pair = hashlib.md5(f"{en}|||{hi}".encode()).hexdigest() if h_pair not in seen_raw: seen_raw.add(h_pair) raw_pairs.append((en, hi, hinglish))
# Clean Train/Val Partitioning on Sentence Pairs (Prevents reverse leakage across splits!) random.shuffle(raw_pairs) val_pair_count = max(20, int(len(raw_pairs) * val_ratio)) val_raw = raw_pairs[:val_pair_count] train_raw = raw_pairs[val_pair_count:]
def build_translation_samples(pairs_subset: list) -> list: subset_examples = [] for en_text, hi_text, hinglish_text in pairs_subset: # Direction 1: English -> Hindi q_en = f"Translate this sentence to Hindi: \"{en_text}\"" think_en = ( f"Source text (English): '{en_text}'\n" f"Target language: Hindi\n" f"Nuance & Grammar: Maintain natural phrasing and formal/informal register in Devanagari." ) ans_en = f"**Hindi Translation:**\n{hi_text}" ex1 = build_direct_example(q_en, think_en, ans_en) if ex1: subset_examples.append(ex1)
# Direction 2: Hindi -> English q_hi = f"Isko English me translate karo: \"{hi_text}\"" think_hi = ( f"Source text (Hindi): '{hi_text}'\n" f"Target language: English\n" f"Nuance & Grammar: Ensure correct English tense, subject-verb agreement and natural vocabulary." ) ans_hi = f"**English Translation:**\n{en_text}" ex2 = build_direct_example(q_hi, think_hi, ans_hi) if ex2: subset_examples.append(ex2)
# Direction 3: English -> Hinglish (if present) if hinglish_text: q_hgl = f"Isko conversational Hinglish me kaise bolenge: \"{en_text}\"" think_hgl = "Translation to natural everyday conversational Hinglish." ex3 = build_direct_example(q_hgl, think_hgl, hinglish_text) if ex3: subset_examples.append(ex3)
return subset_examples
train_examples = build_translation_samples(train_raw) val_examples = build_translation_samples(val_raw)
print(f"β
Module 2 Completed: {len(train_examples)} Train / {len(val_examples)} Val translation examples (Zero-Leakage Guarantee).") return train_examples, val_examples
# ==============================================================================# MODULE 3: 2-Phase Cognitive RAG & Live Search (~12,000)# ==============================================================================def generate_cognitive_rag_dataset(target_count=12000) -> list: print(f"\nπ Module 3: Generating 2-Phase Cognitive RAG Dataset (Target: {target_count})...") examples = [] seen = set()
cities = [ "Delhi", "Mumbai", "Bangalore", "Kolkata", "Chennai", "Hyderabad", "Pune", "Jaipur", "Ahmedabad", "Chandigarh", "Lucknow", "Surat", "Bhopal", "Indore", "Patna", "Kochi", "Goa", "Shimla", "Dehradun", "London", "Tokyo", "New York", "Dubai", "Singapore", "Paris" ] weather_q_templates = [ "What is the current weather in {city} today?", "{city} ka aaj mausam kaisa hai?", "Tell me the live temperature and weather in {city}.", "Aaj {city} me baarish hone ke chances hain kya?", "Current weather update for {city} please.", "How is the climate in {city} right now?" ]
sports_teams = ["RCB", "CSK", "MI", "KKR", "DC", "RR", "GT", "SRH", "LSG", "PBKS", "India", "Australia", "England", "South Africa"] tech_gadgets = ["RTX 5090", "iPhone 16 Pro", "Samsung S25 Ultra", "Gemini 2.0 Flash", "DeepSeek V3", "MacBook Pro M4", "Python 3.13"]
attempts = 0 while len(examples) < target_count and attempts < 100000: attempts += 1
# 1. Weather Category (Dynamic cities, dynamic temperatures & dynamic query phrasing) city = random.choice(cities) temp = random.randint(18, 42) humidity = random.randint(35, 88) condition = random.choice(["Partly Cloudy", "Sunny & Clear", "Light Showers", "Overcast", "Breezy", "Thunderstorm"]) q_tpl = random.choice(weather_q_templates) u_q = q_tpl.format(city=city) h = hashlib.md5(f"rag:w:{u_q}:{temp}".encode()).hexdigest() if h not in seen: seen.add(h) sq = f"current weather live temperature {city}" res = f"[Live Weather Feed] Location: {city} | Temp: {temp}Β°C | Condition: {condition} | Humidity: {humidity}% | Wind: {random.randint(5, 25)} km/h." p1_think = ( f"1. Intent Analysis: User is asking for real-time weather in '{city}'.\n" f"2. Internal Knowledge Check: Live meteorological data requires real-time search.\n" f"3. Search Query Formulation: Need to search current weather and temperature for {city}." ) p2_think = ( f"4. Article / Data Analysis: Read live feed -> {temp}Β°C, {condition}, humidity {humidity}%.\n" f"5. Answer Synthesis: Present temperature and conditions clearly." ) ans = f"Current weather in **{city}**:\n- **Temperature:** {temp}Β°C\n- **Conditions:** {condition}\n- **Humidity:** {humidity}%\n\nHave a great day ahead!" ex = build_search_example(u_q, p1_think, sq, res, p2_think, ans) if ex: examples.append(ex)
if len(examples) >= target_count: break
# 2. Sports Category (Dynamic matches & live scores) t1, t2 = random.sample(sports_teams, 2) score1 = random.randint(140, 215) wickets1 = random.randint(3, 8) score2 = random.randint(80, score1 - 5) wickets2 = random.randint(1, 5) overs2 = f"{random.randint(10, 18)}.{random.randint(1, 5)}" u_sport = random.choice([ f"What is the live score of {t1} vs {t2}?", f"{t1} aur {t2} ka live match score kya chal raha hai?", f"Can you give me the latest scorecard for {t1} vs {t2} match?" ]) h_s = hashlib.md5(f"rag:s:{u_sport}:{score1}:{score2}".encode()).hexdigest() if h_s not in seen: seen.add(h_s) sq_s = f"{t1} vs {t2} live scorecard match update" res_s = f"[Live Cricket Bulletin] {t1} vs {t2}: {t1} scored {score1}/{wickets1} (20 ov). {t2} is {score2}/{wickets2} in {overs2} overs." p1_s = ( f"1. Intent Analysis: Live sports update request for {t1} vs {t2}.\n" f"2. Knowledge Check: Match score changes every ball -> live web lookup needed.\n" f"3. Search Query Formulation: Look up latest live scorecard." ) p2_s = ( f"4. Article / Data Analysis: {t1} set {score1}/{wickets1}; {t2} is chasing at {score2}/{wickets2}.\n" f"5. Answer Synthesis: Deliver a concise, exciting match status summary." ) ans_s = f"**{t1} vs {t2} Live Match Update:**\n- **{t1}:** {score1}/{wickets1} (20 overs)\n- **{t2}:** {score2}/{wickets2} ({overs2} overs)\n\nThe match is currently in an exciting phase!" ex_s = build_search_example(u_sport, p1_s, sq_s, res_s, p2_s, ans_s) if ex_s: examples.append(ex_s)
if len(examples) >= target_count: break
# 3. Tech / Hardware Category gadget = random.choice(tech_gadgets) u_tech = random.choice([ f"What are the key specifications and features of {gadget}?", f"{gadget} ke latest features aur specifications batao.", f"Can you summarize the official details for {gadget}?" ]) h_t = hashlib.md5(f"rag:t:{u_tech}".encode()).hexdigest() if h_t not in seen: seen.add(h_t) sq_t = f"{gadget} official specifications features details" res_t = f"[Tech Review / Official Release] {gadget}: High-performance architecture, upgraded AI acceleration cores, power efficiency enhancements, and next-gen memory subsystem." p1_t = ( f"1. Intent Analysis: User seeks verified technical specifications for '{gadget}'.\n" f"2. Knowledge Check: Retrieve verified documentation.\n" f"3. Search Query Formulation: Query official specs and benchmarks for {gadget}." ) p2_t = ( f"4. Article / Data Analysis: Synthesize key architectural advantages and hardware specs.\n" f"5. Answer Synthesis: Format into structured bullet points." ) ans_t = f"Key Specifications for **{gadget}**:\n- **Architecture:** Next-generation high-efficiency architecture.\n- **Performance:** Significant uplift in compute, throughput and AI acceleration.\n- **Memory & Bandwidth:** Advanced high-speed subsystem.\n- **Key Highlight:** Designed for optimal performance in intensive workloads." ex_t = build_search_example(u_tech, p1_t, sq_t, res_t, p2_t, ans_t) if ex_t: examples.append(ex_t)
if len(examples) >= target_count: break
# 4. Bullion / Gold Rates Category g_city = random.choice(["Mumbai", "Delhi", "Bangalore", "Chennai", "Kolkata", "Hyderabad", "Jaipur", "Ahmedabad"]) rate_24k = random.randint(71500, 75500) rate_22k = int(rate_24k * 0.916) u_gold = random.choice([ f"Aaj {g_city} me gold ka kya rate hai?", f"What is the gold price per 10 grams in {g_city} today?", f"Current 24K and 22K gold rates in {g_city}." ]) h_g = hashlib.md5(f"rag:g:{u_gold}:{rate_24k}".encode()).hexdigest() if h_g not in seen: seen.add(h_g) sq_g = f"24K 22K gold rate today {g_city} per 10g bullion market" res_g = f"[Bullion Market Live Feed] {g_city}: 24K Gold βΉ{rate_24k:,} per 10g | 22K Gold βΉ{rate_22k:,} per 10g | Silver βΉ{random.randint(84000, 89000):,} per kg." p1_g = ( f"1. Intent Analysis: Gold rate query for '{g_city}'.\n" f"2. Knowledge Check: Commodity prices fluctuate daily -> fetch live bullion rates.\n" f"3. Search Query Formulation: Search today's bullion market rates in {g_city}." ) p2_g = ( f"4. Article / Data Analysis: Verified rates -> 24K = βΉ{rate_24k:,}, 22K = βΉ{rate_22k:,}.\n" f"5. Answer Synthesis: Present rates clearly in easy-to-read format." ) ans_g = f"Today's Gold Rates in **{g_city}**:\n- **24K Gold (Pure):** βΉ{rate_24k:,} per 10 grams\n- **22K Gold (Standard):** βΉ{rate_22k:,} per 10 grams\n\n*(Note: Local jewellery making charges and GST may vary.)*" ex_g = build_search_example(u_gold, p1_g, sq_g, res_g, p2_g, ans_g) if ex_g: examples.append(ex_g)
print(f"β
Module 3 Completed: {len(examples)} examples.") return examples[:target_count]
# ==============================================================================# MODULE 4: Reasoning, Math (GSM8k) & Coding (~15,000)# ==============================================================================def generate_reasoning_and_math_dataset(target_count=15000) -> list: print(f"\nπ§ Module 4: Generating Reasoning, Math (GSM8k) & Code (Target: {target_count})...") examples = [] seen = set()
# 1. Load GSM8k (Grade School Math - with complete <<...>> calculator markup stripping!) try: print(" π₯ Loading GSM8k math dataset...") gsm = load_dataset("gsm8k", "main", split="train") for item in tqdm(gsm, desc="Parsing GSM8k"): if len(examples) >= target_count: break q = item["question"].strip() a = item["answer"].strip()
h = hashlib.md5(q.lower().strip().encode()).hexdigest() if h in seen: continue seen.add(h)
parts = a.split("####") if len(parts) == 2: raw_rationale = parts[0].strip() # Strip GSM8k calculator annotations <<...>> so they never leak into model reasoning 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}" final = f"The final answer is **{ans_val}**." 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
ex = build_direct_example(q, think, final) if ex: examples.append(ex) print(f" β
Loaded {len(examples)} GSM8k math problems (calculator tags cleanly stripped)!") except Exception as e: print(f" β οΈ Could not load GSM8k: {e}")
# 2. Load Coding Instructions (CodeAlpaca) for code_ds in ["HuggingFaceH4/CodeAlpaca_20K", "iamtarun/python_code_instructions_18k_alpaca"]: try: print(f" π₯ Loading coding dataset '{code_ds}'...") ds = load_dataset(code_ds, split="train") for item in tqdm(ds, desc=f"Parsing {code_ds}", total=min(len(ds), 5000)): if len(examples) >= target_count: break instr = item.get("instruction", item.get("prompt", "")).strip() inp = item.get("input", "").strip() out = item.get("output", item.get("response", "")).strip()
full_prompt = f"{instr}\n{inp}".strip() if inp else instr h = hashlib.md5(full_prompt.lower().strip().encode()).hexdigest() if len(full_prompt) < 10 or h in seen: continue seen.add(h)
think = ( "Problem Analysis: Understand the input requirements and expected output.\n" "Algorithm Design: Select an optimal time/space complexity approach.\n" "Implementation: Write clean, well-commented Python/code." ) ex = build_direct_example(full_prompt, think, out) if ex: examples.append(ex) print(f" β
Extracted coding samples. Total so far: {len(examples)}") if len(examples) >= target_count: break except Exception as e: print(f" β οΈ Could not load {code_ds}: {e}")
# 3. Dynamic Procedural Arithmetic & Word Problem Generator (Infinite unique problem generation) print(" βοΈ Adding diverse procedural math word problems with dynamic numbers...") templates = [ ("A bakery bakes {a} loaves of bread in the morning and {b} loaves in the afternoon. If they sell {c} loaves during the day, how many loaves remain at closing?", lambda a, b, c: (a + b - c, f"1. Total loaves baked = {a} + {b} = {a + b}.\n2. Loaves sold = {c}.\n3. Remaining loaves = {a + b} - {c} = {a + b - c}.")), ("Rohan bought {a} notebooks for βΉ{b} each and {c} pens for βΉ{d} each. What is the total amount Rohan spent?", lambda a, b, c, d: (a * b + c * d, f"1. Cost of {a} notebooks at βΉ{b} each = {a} * {b} = βΉ{a * b}.\n2. Cost of {c} pens at βΉ{d} each = {c} * {d} = βΉ{c * d}.\n3. Total cost = βΉ{a * b} + βΉ{c * d} = βΉ{a * b + c * d}.")), ("A train travels at a speed of {a} km/h for {b} hours, and then at {c} km/h for {d} hours. What is the total distance covered by the train?", lambda a, b, c, d: (a * b + c * d, f"1. Distance in first leg = Speed * Time = {a} * {b} = {a * b} km.\n2. Distance in second leg = {c} * {d} = {c * d} km.\n3. Total distance = {a * b} + {c * d} = {a * b + c * d} km.")), ("A shop offers a discount of {a}% on a jacket priced at βΉ{b}. What is the discounted price of the jacket?", lambda a, b: (int(b * (100 - a) / 100), f"1. Original price = βΉ{b}.\n2. Discount percentage = {a}%.\n3. Discount amount = ({a} / 100) * {b} = βΉ{int(b * a / 100)}.\n4. Final price = βΉ{b} - βΉ{int(b * a / 100)} = βΉ{int(b * (100 - a) / 100)}.")) ]
attempts = 0 while len(examples) < target_count and attempts < 100000: attempts += 1 t_idx = random.randint(0, len(templates) - 1) tpl, solver = templates[t_idx] if t_idx == 0: a, b = random.randint(50, 300), random.randint(30, 200) c = random.randint(20, a + b - 10) ans, derivation = solver(a, b, c) q = tpl.format(a=a, b=b, c=c) elif t_idx == 1: a, b = random.randint(2, 10), random.randint(20, 100) c, d = random.randint(2, 15), random.randint(5, 30) ans, derivation = solver(a, b, c, d) q = tpl.format(a=a, b=b, c=c, d=d) elif t_idx == 2: a, b = random.randint(40, 100), random.randint(2, 6) c, d = random.randint(50, 120), random.randint(1, 4) ans, derivation = solver(a, b, c, d) q = tpl.format(a=a, b=b, c=c, d=d) else: a = random.choice([10, 15, 20, 25, 30, 40, 50]) b = random.randint(5, 50) * 100 ans, derivation = solver(a, b) q = tpl.format(a=a, b=b)
h = hashlib.md5(q.encode()).hexdigest() if h in seen: continue seen.add(h)
think = f"Mathematical Derivation:\n{derivation}" final = f"**Final Answer:** {ans}" ex = build_direct_example(q, think, final) if ex: examples.append(ex)
print(f"β
Module 4 Completed: {len(examples)} examples.") return examples[:target_count]
# ==============================================================================# MODULE 5: General Knowledge & Instruction (~12,500) (Dynamic Cognitive Strategy)# ==============================================================================def generate_general_knowledge_dataset(target_count=12500) -> list: print(f"\nπ Module 5: Generating General Knowledge & Instruction with Dynamic Cognitive Thinking (Target: {target_count})...") examples = [] seen = set()
# 1. Load Yahma Alpaca Cleaned or Databricks Dolly for ds_name in ["yahma/alpaca-cleaned", "databricks/databricks-dolly-15k"]: try: print(f" π₯ Loading '{ds_name}'...") ds = load_dataset(ds_name, split="train") for item in tqdm(ds, desc=f"Parsing {ds_name}"): if len(examples) >= target_count: break instr = item.get("instruction", "").strip() inp = item.get("input", item.get("context", "")).strip() out = item.get("output", item.get("response", "")).strip()
full_q = f"{instr}\n{inp}".strip() if inp else instr h = hashlib.md5(full_q.lower().strip().encode()).hexdigest() # Length cap to prevent truncated long answers if len(full_q) < 8 or len(out) < 8 or len(out) > 1600 or h in seen: continue seen.add(h)
# Dynamic per-example cognitive thinking synthesis think = create_dynamic_gk_think(full_q, out) ex = build_direct_example(full_q, think, out) if ex: examples.append(ex) print(f" β
Extracted {len(examples)} instruction examples from {ds_name}") if len(examples) >= target_count: break except Exception as e: print(f" β οΈ Could not load {ds_name}: {e}")
assert len(examples) >= 3000, f"Critical: General Knowledge dataset loading failed! Only {len(examples)} loaded." print(f"β
Module 5 Completed: {len(examples)} examples with unique cognitive thinking blocks.") return examples[:target_count]
# ==============================================================================# MODULE 6: Identity & Sarus Alignment (~1,500)# ==============================================================================def generate_identity_dataset(target_count=1500) -> list: print(f"\nπ·οΈ Module 6: Generating Identity & Sarus Alignment (Target: {target_count})...") examples = []
identity_pairs = [ ("Who are you?", "I am **ViuAI** (also known as Sarus AI), an intelligent AI assistant developed by ViuAI / Sarus. I am designed to assist you with reasoning, research, coding, live search, and friendly conversations."), ("Tumhara naam kya hai?", "Mera naam **ViuAI** (Sarus AI) hai! Main ViuAI dwara develop kiya gaya ek smart, helpful aur friendly AI assistant hu."), ("Who created you?", "I was created and trained by **ViuAI** (founded by Sarus & team) using advanced transformer architecture with cognitive reasoning and live search capabilities."), ("Tumhe kisne banaya hai?", "Mujhe **ViuAI** ki team (Sarus) ne develop aur train kiya hai."), ("What can you do?", "I can help you with a wide range of tasks including:\n- Deep reasoning, mathematical derivations, and coding.\n- 2-Phase Live Search and information synthesis.\n- Hindi β English / Hinglish translation.\n- Friendly, caring, and supportive conversations!"), ("Kya tum Hindi samajhte ho?", "Haan bilkul! Main Hindi, Hinglish aur English teeno me fluently baat kar sakta hu aur sawalon ke javab de sakta hu."), ("What architecture do you use?", "I am built on a custom high-performance decoder-only transformer architecture with SwiGLU activations, RoPE embeddings, RMSNorm, and GQA attention."), ("Who is Sarus?", "Sarus is the creator and founding team behind ViuAI."), ("Are you ChatGPT?", "No, I am **ViuAI**, independently created and trained by ViuAI / Sarus."), ("Can you solve coding problems?", "Yes! I can write, debug, explain, and optimize code in Python, JavaScript, C++, and many other programming languages.") ]
prefixes = [ "Tell me, ", "Please answer: ", "Hello! ", "Hi, ", "Can you introduce yourself? ", "Batao zara, ", "Ek sawal hai: ", "Suno, ", "Namaste, ", "Dear AI, ", "Hey ViuAI, ", "" ]
while len(examples) < target_count: for q_tpl, ans in identity_pairs: if len(examples) >= target_count: break p = random.choice(prefixes) q = f"{p}{q_tpl}" think = ( "Identity Alignment: Confirm self-identity as ViuAI / Sarus AI.\n" "Tone: Polite, welcoming, and accurate." ) ex = build_direct_example(q, think, ans) if ex: examples.append(ex)
print(f"β
Module 6 Completed: {len(examples)} examples.") return examples[:target_count]
# ==============================================================================# π MAIN PIPELINE: Assembly, Tokenization & Serialization (Root Path Contract)# ==============================================================================def main(): print("\n" + "=" * 65) print("π ASSEMBLING SFT v7 DATASET (Zero-Leakage & Dynamic Cognitive Reasoning)") print("=" * 65)
# 1. Module 2 generates train and val splits with zero reverse pair leakage trans_train, trans_val = generate_translation_dataset(10000, val_ratio=0.03)
# 2. Other modules general_pool = [] general_pool.extend(generate_emotional_friend_dataset(14000)) general_pool.extend(generate_cognitive_rag_dataset(12000)) general_pool.extend(generate_reasoning_and_math_dataset(15000)) general_pool.extend(generate_general_knowledge_dataset(12500)) general_pool.extend(generate_identity_dataset(1500))
# Shuffle general pool deterministically random.shuffle(general_pool) val_count_gen = max(400, int(len(general_pool) * 0.03)) train_count_gen = len(general_pool) - val_count_gen
train_examples = general_pool[:train_count_gen] + trans_train val_examples = general_pool[train_count_gen:] + trans_val
random.shuffle(train_examples) random.shuffle(val_examples)
total_samples = len(train_examples) + len(val_examples) print(f"\nπ Total Validated SFT v7 Samples: {total_samples}") print(f" π Split: {len(train_examples)} Train Samples | {len(val_examples)} Validation Samples")
out_dir = "sft_data_v7" os.makedirs(out_dir, exist_ok=True)
def serialize_split(split_name: str, examples_list: list): print(f"\nπΎ Serializing {split_name} ({len(examples_list)} examples)...") all_ids = [] all_labels = [] offsets = [0]
for ex in tqdm(examples_list, desc=f"Flattening {split_name}"): all_ids.extend(ex["input_ids"]) all_labels.extend(ex["labels"]) offsets.append(len(all_ids))
# Use int32 for ids and labels (optimizes file size by 50% for 64K vocab) ids_np = np.array(all_ids, dtype=np.int32) labels_np = np.array(all_labels, dtype=np.int32) offsets_np = np.array(offsets, dtype=np.int64)
# Standard file names matching training fetch contract: sft_v7_{split}_*.npy np.save(f"{out_dir}/sft_v7_{split_name}_ids.npy", ids_np) np.save(f"{out_dir}/sft_v7_{split_name}_labels.npy", labels_np) np.save(f"{out_dir}/sft_v7_{split_name}_offsets.npy", offsets_np)
print(f" β
{split_name.upper()} Saved:") print(f" IDs: {ids_np.shape} ({ids_np.nbytes / 1e6:.1f} MB)") print(f" Labels: {labels_np.shape} ({labels_np.nbytes / 1e6:.1f} MB)") print(f" Offsets: {offsets_np.shape} ({offsets_np.nbytes / 1e6:.1f} MB)")
serialize_split("train", train_examples) serialize_split("val", val_examples)
# Push to Hugging Face Root Directory (exact contract matching train_sft.py) print("\nβοΈ Uploading SFT v7 Dataset to Hugging Face...") api = HfApi(token=HF_TOKEN) files = [ "sft_v7_train_ids.npy", "sft_v7_train_labels.npy", "sft_v7_train_offsets.npy", "sft_v7_val_ids.npy", "sft_v7_val_labels.npy", "sft_v7_val_offsets.npy" ] for f in files: local_f = os.path.join(out_dir, f) print(f" Uploading {f} -> {DATA_REPO_ID} ({f})...") try: api.upload_file( path_or_fileobj=local_f, path_in_repo=f, repo_id=DATA_REPO_ID, repo_type="dataset", token=HF_TOKEN ) print(f" β
Uploaded {f}") except Exception as e: print(f" β οΈ Upload error for {f}: {e}")
print("\n" + "=" * 65) print("π SFT v7 DATASET GENERATION & UPLOAD COMPLETED SUCCESSFULLY!") print("=" * 65)
if __name__ == "__main__": main()code/build_sft_data_v7.pyAdded+949