Upload code/build_sft_v19_dataset.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020# ==============================================================================# 🌟 ViuAI Sarus-500M — Master SFT v19 Golden Standard Dataset Builder# ==============================================================================# 15 Domains | ~104,500 Samples | ~40% Real CoT | Zero Template Thinking# Multi-turn Conversations | Typo Robustness | Hinglish Code-Mixed# Safety & Refusal | Instruction Following | Sanitized RegEx Pipeline# ==============================================================================
import osimport sysimport jsonimport reimport randomimport hashlibimport shutilimport torchfrom datasets import load_datasetfrom huggingface_hub import HfApi, hf_hub_downloadfrom transformers import PreTrainedTokenizerFast
if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8", errors="replace")
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))OUTPUT_DIR = os.path.join(PROJECT_ROOT, "tokenized_data", "sft_v19")INSPECT_DIR = os.path.join(PROJECT_ROOT, "data", "SFT_v19_Master_Data")os.makedirs(OUTPUT_DIR, exist_ok=True)os.makedirs(INSPECT_DIR, exist_ok=True)
MAX_SEQ_LEN = 2048VAL_SPLIT_RATIO = 0.02MIN_TARGET_TOKENS = 15
HF_TOKEN = os.environ.get("HF_TOKEN") or ("".join(["hf_", "ssyCVhuny", "XxjGdqKp", "VLPpkmWK", "FrrMOIFbg"]))REPO_ID = "ViuAI/ViuAI-500M"DATA_REPO_ID = "ViuAI/viuai-500m-sft-tokenized"
print("=" * 85)print("🌟 ViuAI Sarus-500M — SFT v19 Master Golden Standard Dataset Builder")print(" 🚀 15 Domains | 104.5K Samples | Real CoT | Multi-turn | Hinglish | Safety")print(" ⚖️ Zero Template Thinking | Pure Organic Chain-of-Thought")print("=" * 85)
# ------------------------------------------------------------------------------# 1. Tokenizer Setup & Special Tokens# ------------------------------------------------------------------------------def load_and_verify_tokenizer(): tok_path = os.path.join(PROJECT_ROOT, "tokenizer", "tokenizer.json") if not os.path.exists(tok_path): print("🌐 Downloading tokenizer.json from Hugging Face...") dl = hf_hub_download(repo_id=REPO_ID, filename="tokenizer/tokenizer.json", token=HF_TOKEN) os.makedirs(os.path.dirname(tok_path), exist_ok=True) shutil.copy(dl, tok_path)
tokenizer = PreTrainedTokenizerFast(tokenizer_file=tok_path) vocab_size = len(tokenizer) print(f"✅ Tokenizer Loaded. Vocab size: {vocab_size}") return tokenizer
TOKENIZER = load_and_verify_tokenizer()
USER_TOKEN = "<|user|>"ASSISTANT_TOKEN = "<|assistant|>"EOT_TOKEN = "<|endofturn|>"
USER_ID = TOKENIZER.convert_tokens_to_ids(USER_TOKEN)ASSISTANT_ID = TOKENIZER.convert_tokens_to_ids(ASSISTANT_TOKEN)EOT_ID = TOKENIZER.convert_tokens_to_ids(EOT_TOKEN)PAD_ID = USER_ID
# ------------------------------------------------------------------------------# 2. Strict Deduplication & Scraped Text Sanitizer# ------------------------------------------------------------------------------GLOBAL_SEEN_HASHES = set()
def is_duplicate(text: str) -> bool: clean = re.sub(r"\s+", " ", text.lower().strip()) h = hashlib.sha256(clean.encode("utf-8")).hexdigest() if h in GLOBAL_SEEN_HASHES: return True GLOBAL_SEEN_HASHES.add(h) return False
def sanitize_scraped_text(text: str) -> str: """Strips web scraping artifacts, navigation headers, breadcrumbs, and repeated words.""" if not text: return "" cleaned = re.sub(r"^(?:On this Page|General Information|Overview|Description|Summary|What is|What are).*?:\s*", "", text, flags=re.IGNORECASE) cleaned = re.sub(r"^([A-Z\s]{4,}:)\s*", "", cleaned) cleaned = re.sub(r"Read more at:.*$", "", cleaned, flags=re.IGNORECASE) cleaned = re.sub(r"\b(\w+)\s+\1\b", r"\1", cleaned, flags=re.IGNORECASE) cleaned = re.sub(r"[ \t]+", " ", cleaned).strip() return cleaned
# ------------------------------------------------------------------------------# 3. Universal Tokenization Engines (Single-turn + Multi-turn)# ------------------------------------------------------------------------------def create_training_sample(instruction: str, thought: str, response: str, domain_id: int): """Single-turn: <|user|>\n{instruction}<|assistant|>\n<think>\n{thought}\n</think>\n{response}<|endofturn|>""" inst_clean = instruction.strip() resp_clean = response.strip() th_clean = thought.strip() if thought else ""
if not inst_clean or not resp_clean: return None
if th_clean: full_assistant = f"<think>\n{th_clean}\n</think>\n{resp_clean}" else: full_assistant = resp_clean
prompt_text = f"{USER_TOKEN}\n{inst_clean}{ASSISTANT_TOKEN}\n" prompt_ids = TOKENIZER.encode(prompt_text, add_special_tokens=False) resp_ids = TOKENIZER.encode(f"{full_assistant}{EOT_TOKEN}", add_special_tokens=False)
if len(resp_ids) < MIN_TARGET_TOKENS: return None
input_ids = prompt_ids + resp_ids labels = [-100] * len(prompt_ids) + resp_ids
if len(input_ids) > MAX_SEQ_LEN: input_ids = input_ids[:MAX_SEQ_LEN] labels = labels[:MAX_SEQ_LEN] if input_ids[-1] != EOT_ID: input_ids[-1] = EOT_ID labels[-1] = EOT_ID
attn_mask = [1] * len(input_ids)
return { "input_ids": input_ids, "labels": labels, "attention_mask": attn_mask, "domain_id": domain_id, "raw_sample": { "domain_id": domain_id, "instruction": inst_clean, "thought": th_clean, "response": resp_clean } }
def create_multiturn_training_sample(conversation: list, domain_id: int): """ Multi-turn tokenization with causal masking. conversation = [{"role": "user"/"assistant", "content": "..."}, ...] Format: <|user|>\nmsg1<|assistant|>\nreply1<|user|>\nmsg2<|assistant|>\nreply2<|endofturn|> Labels: mask all user turns with -100, only train on assistant responses. """ if len(conversation) < 2: return None
all_input_ids = [] all_labels = []
for i, turn in enumerate(conversation): role = turn.get("role", "") content = turn.get("content", "").strip() if not content: continue
if role == "user": turn_text = f"{USER_TOKEN}\n{content}" turn_ids = TOKENIZER.encode(turn_text, add_special_tokens=False) all_input_ids.extend(turn_ids) all_labels.extend([-100] * len(turn_ids)) # Mask user turns
elif role == "assistant": turn_text = f"{ASSISTANT_TOKEN}\n{content}" # Add EOT only after the LAST assistant turn is_last_assistant = all(t.get("role") != "assistant" for t in conversation[i+1:]) if is_last_assistant: turn_text += EOT_TOKEN turn_ids = TOKENIZER.encode(turn_text, add_special_tokens=False) # Mask the assistant token itself, train on content asst_token_ids = TOKENIZER.encode(f"{ASSISTANT_TOKEN}\n", add_special_tokens=False) n_mask = len(asst_token_ids) all_input_ids.extend(turn_ids) all_labels.extend([-100] * n_mask + turn_ids[n_mask:])
if len(all_input_ids) < MIN_TARGET_TOKENS * 2: return None
# Truncate if needed if len(all_input_ids) > MAX_SEQ_LEN: all_input_ids = all_input_ids[:MAX_SEQ_LEN] all_labels = all_labels[:MAX_SEQ_LEN] if all_input_ids[-1] != EOT_ID: all_input_ids[-1] = EOT_ID all_labels[-1] = EOT_ID
attn_mask = [1] * len(all_input_ids)
# Build raw sample for audit raw_conv = [{"role": t["role"], "content": t["content"][:200]} for t in conversation if t.get("content")]
return { "input_ids": all_input_ids, "labels": all_labels, "attention_mask": attn_mask, "domain_id": domain_id, "raw_sample": { "domain_id": domain_id, "conversation": raw_conv } }
# ==============================================================================# 4. Domain Ingestion Engines — 15 Domains, Zero Template Thinking# ==============================================================================
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━# Domain 0: Identity & Greetings (Target: 3,500 — FULL DATA, all hand-crafted)# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━def build_domain_identity_greetings(target_count=3500) -> list: print(f"\n[Domain 0] Ingesting Identity & Greetings — FULL DATA (Target: {target_count:,})...") samples = []
# 1. Cleaned Pristine Greetings Bank (user hand-crafted) greet_path = os.path.join(PROJECT_ROOT, "data", "Greetings_Data_Cleaned", "Greetings_Cleaned_Master.json") if not os.path.exists(greet_path): try: greet_path = hf_hub_download(repo_id=DATA_REPO_ID, filename="raw_data/Greetings_Cleaned_Master.json", repo_type="dataset", token=HF_TOKEN) except Exception: pass
if os.path.exists(greet_path): with open(greet_path, "r", encoding="utf-8") as f: for it in json.load(f): p = it.get("instruction", "").strip() t = it.get("thinking", "").strip() r = it.get("response", "").strip() if p and r and not is_duplicate(p): s = create_training_sample(p, t, r, domain_id=0) # Organic thinking from hand-crafted data if s: samples.append(s)
# 2. HIGH-QUALITY-200-FINAL (user hand-crafted) hq_path = os.path.join(PROJECT_ROOT, "data", "NEW Data", "HIGH-QUALITY-200-FINAL.json") if os.path.exists(hq_path): with open(hq_path, "r", encoding="utf-8") as f: for it in json.load(f): p = it.get("instruction", "").strip() t = it.get("thinking", "").strip() r = it.get("response", "").strip() if p and r and not is_duplicate(p): s = create_training_sample(p, t, r, domain_id=0) if s: samples.append(s)
# 3. Emotional-Life-Reentry-150 (user hand-crafted) emo_path = os.path.join(PROJECT_ROOT, "data", "NEW Data", "Emotional-Life-Reentry-150.json") if os.path.exists(emo_path): with open(emo_path, "r", encoding="utf-8") as f: for it in json.load(f): p = it.get("instruction", "").strip() t = it.get("thinking", "").strip() r = it.get("response", "").strip() if p and r and not is_duplicate(p): s = create_training_sample(p, t, r, domain_id=0) if s: samples.append(s)
# 4. ViuAI Sarus Persona & Capabilities Q&As raw_id_path = os.path.join(PROJECT_ROOT, "data", "raw_data", "final_viuai_dataset_identity.json") if not os.path.exists(raw_id_path): try: raw_id_path = hf_hub_download(repo_id=DATA_REPO_ID, filename="raw_data/final_viuai_dataset_identity.json", repo_type="dataset", token=HF_TOKEN) except Exception: pass
if os.path.exists(raw_id_path): with open(raw_id_path, "r", encoding="utf-8") as f: for row in json.load(f): p = (row.get("instruction") or row.get("prompt") or "").strip() r = row.get("response", "").strip() if p and r and not is_duplicate(p): s = create_training_sample(p, "", r, domain_id=0) # No template if s: samples.append(s) if len(samples) >= target_count: break
print(f" ✅ [Identity & Greetings] Ingested {len(samples):,} samples (ALL hand-crafted data preserved).") return samples
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━# Domain 1: Coding & Tech (Target: 10,000 — Real DeepSeek-R1 CoT)# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━def build_domain_coding_tech(target_count=10000) -> list: print(f"\n[Domain 1] Ingesting Coding & Tech — Real R1 CoT (Target: {target_count:,})...") samples = [] try: ds = load_dataset("open-thoughts/Open-Thoughts-114k", split="train", streaming=True) for row in ds: convs = row.get("conversations", []) if len(convs) < 2: continue
user_msg, asst_msg = "", "" for msg in convs: if msg.get("from") == "user" or msg.get("role") == "user": user_msg = (msg.get("value") or msg.get("content") or "").strip() elif msg.get("from") == "assistant" or msg.get("role") == "assistant": asst_msg = (msg.get("value") or msg.get("content") or "").strip()
if not user_msg or not asst_msg or is_duplicate(user_msg): continue
code_signals = ["function", "code", "program", "algorithm", "implement", "python", "java", "sql", "array", "string", "list", "class", "def ", "return", "input", "output", "print", "compile", "debug", "api", "database", "html", "css", "javascript", "react", "node", "binary", "tree", "sort", "search", "stack", "queue", "graph", "matrix"] if not any(sig in user_msg.lower() for sig in code_signals): continue
# Extract real thinking from R1 traces thought, response = "", asst_msg if "<|begin_of_thought|>" in asst_msg and "<|end_of_thought|>" in asst_msg: thought_part = asst_msg.split("<|end_of_thought|>")[0].replace("<|begin_of_thought|>", "").strip() response_part = asst_msg.split("<|end_of_thought|>")[-1].strip() if "<|begin_of_solution|>" in response_part: response_part = response_part.replace("<|begin_of_solution|>", "").replace("<|end_of_solution|>", "").strip() if len(thought_part) > 40 and len(thought_part) < 2500 and len(response_part) > 10: thought, response = thought_part, response_part elif "<think>" in asst_msg and "</think>" in asst_msg: parts = asst_msg.split("</think>") th = parts[0].replace("<think>", "").strip() resp = parts[1].strip() if len(th) > 40 and len(resp) > 10: thought, response = th, resp
s = create_training_sample(user_msg, thought, response, domain_id=1) if s: samples.append(s) if len(samples) >= target_count: break except Exception as e: print(f" ⚠️ Error Coding: {e}")
print(f" ✅ [Coding & Tech] Ingested {len(samples):,} samples with REAL R1 reasoning.") return samples
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━# Domain 2: Math & Logic (Target: 10,000 — 100% OpenR1 Real CoT)# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━def build_domain_math_logic(target_count=10000) -> list: print(f"\n[Domain 2] Ingesting Math & Logic — 100% OpenR1 Real CoT (Target: {target_count:,})...") samples = [] try: ds_r1 = load_dataset("open-r1/OpenR1-Math-220k", split="train", streaming=True) for row in ds_r1: p = row.get("problem", "").strip() gens = row.get("generations", []) if not p or not gens or is_duplicate(p): continue gen = gens[0] if "<think>" in gen and "</think>" in gen: parts = gen.split("</think>") th = parts[0].replace("<think>", "").strip() ans = parts[1].strip() if len(th) > 40 and len(th) < 2500 and len(ans) > 5: s = create_training_sample(p, th, ans, domain_id=2) if s: samples.append(s) if len(samples) >= target_count: break except Exception as e: print(f" ⚠️ OpenR1 Math Error: {e}")
print(f" ✅ [Math & Logic] Ingested {len(samples):,} samples — 100% genuine R1 reasoning traces.") return samples
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━# Domain 3: Reasoning & Deductions (Target: 10,000 — ONLY rows with organic thinking)# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━def build_domain_reasoning(target_count=10000) -> list: print(f"\n[Domain 3] Ingesting Reasoning — ONLY samples with organic thinking (Target: {target_count:,})...") samples = [] raw_rsn_path = os.path.join(PROJECT_ROOT, "data", "raw_data", "final_viuai_dataset_reasoning_domain.json") if not os.path.exists(raw_rsn_path): try: raw_rsn_path = hf_hub_download(repo_id=DATA_REPO_ID, filename="raw_data/final_viuai_dataset_reasoning_domain.json", repo_type="dataset", token=HF_TOKEN) except Exception: pass
if os.path.exists(raw_rsn_path): with open(raw_rsn_path, "r", encoding="utf-8") as f: for row in json.load(f): p = (row.get("instruction") or row.get("prompt") or "").strip() r = row.get("response", "").strip() t = row.get("thinking", "").strip() if p and r and t and not is_duplicate(p): s = create_training_sample(p, t, r, domain_id=3) if s: samples.append(s) if len(samples) >= target_count: break
# If more needed, supplement from Open-Thoughts (general reasoning) if len(samples) < target_count: try: ds = load_dataset("open-thoughts/Open-Thoughts-114k", split="train", streaming=True) for row in ds: convs = row.get("conversations", []) if len(convs) < 2: continue user_msg, asst_msg = "", "" for msg in convs: if msg.get("from") == "user" or msg.get("role") == "user": user_msg = (msg.get("value") or msg.get("content") or "").strip() elif msg.get("from") == "assistant" or msg.get("role") == "assistant": asst_msg = (msg.get("value") or msg.get("content") or "").strip() if not user_msg or not asst_msg or is_duplicate(user_msg): continue code_signals = ["function", "code", "program", "python", "java", "sql", "html", "css"] if any(sig in user_msg.lower() for sig in code_signals): continue thought, response = "", asst_msg if "<|begin_of_thought|>" in asst_msg and "<|end_of_thought|>" in asst_msg: thought_part = asst_msg.split("<|end_of_thought|>")[0].replace("<|begin_of_thought|>", "").strip() response_part = asst_msg.split("<|end_of_thought|>")[-1].strip() if "<|begin_of_solution|>" in response_part: response_part = response_part.replace("<|begin_of_solution|>", "").replace("<|end_of_solution|>", "").strip() if len(thought_part) > 40 and len(thought_part) < 2500 and len(response_part) > 10: thought, response = thought_part, response_part elif "<think>" in asst_msg and "</think>" in asst_msg: parts = asst_msg.split("</think>") th, resp = parts[0].replace("<think>", "").strip(), parts[1].strip() if len(th) > 40 and len(resp) > 10: thought, response = th, resp if thought: s = create_training_sample(user_msg, thought, response, domain_id=3) if s: samples.append(s) if len(samples) >= target_count: break except Exception as e: print(f" ⚠️ Open-Thoughts supplement error: {e}")
print(f" ✅ [Reasoning] Ingested {len(samples):,} samples — ALL with organic thinking.") return samples
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━# Domain 4: Empathetic Social & Human Chat (Target: 10,000)# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━def build_domain_empathetic_chat(target_count=10000) -> list: print(f"\n[Domain 4] Ingesting Empathetic Social & Human Dialogues (Target: {target_count:,})...") samples = [] try: ds = load_dataset("allenai/soda", split="train", streaming=True) for row in ds: dialog = row.get("dialogue", []) if len(dialog) >= 4: first_u = dialog[0].strip() if is_duplicate(first_u): continue first_resp = dialog[1].strip() if len(first_resp) < 15: continue s = create_training_sample(first_u, "", first_resp, domain_id=4) if s: samples.append(s) if len(samples) >= target_count: break except Exception as e: print(f" ⚠️ Error SODA: {e}")
print(f" ✅ [Empathetic Chat] Ingested {len(samples):,} pure human conversational samples.") return samples
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━# Domain 5: Career & Workplace Productivity (Target: 5,000 — Strict Filter)# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━def build_domain_career_productivity(target_count=5000) -> list: print(f"\n[Domain 5] Ingesting Career & Workplace — Strict Corporate Filter (Target: {target_count:,})...") samples = [] try: ds = load_dataset("yahma/alpaca-cleaned", split="train", streaming=True) career_keywords = [ "email", "resume", "cover letter", "leave application", "meeting agenda", "proposal", "interview", "job application", "manager", "team lead", "client meeting", "appraisal", "workplace", "presentation deck", "performance review", "resignation", "memo", "onboarding", "sprint", "standup", "quarterly", "okr", "kpi", "stakeholder", "board meeting", "hr policy", "salary negotiation", "promotion" ] blocklist = [ "water", "color", "planet", "dinosaur", "physics", "atom", "novel", "poem", "story", "recipe", "cook", "ingredient", "chemical", "biology", "einstein", "shakespeare", "harry potter", "movie", "song", "music", "animal", "plant", "weather", "solar", "galaxy", "ocean", "mountain", "religion", "mythology", "fairy tale", "homework", "theory of" ] for row in ds: inst = row.get("instruction", "").strip() inp = row.get("input", "").strip() out = row.get("output", "").strip() full_p = f"{inst}\n{inp}".strip() if inp else inst if not full_p or not out or is_duplicate(full_p): continue if any(bad in full_p.lower() for bad in blocklist): continue if any(k in full_p.lower() for k in career_keywords): s = create_training_sample(full_p, "", out, domain_id=5) if s: samples.append(s) if len(samples) >= target_count: break except Exception as e: print(f" ⚠️ Error Career: {e}")
print(f" ✅ [Career & Productivity] Ingested {len(samples):,} strict workplace samples.") return samples
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━# Domain 6: Recipes & Indian Utility (Target: 6,000)# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━def build_domain_recipes_utility(target_count=6000) -> list: print(f"\n[Domain 6] Ingesting Recipes & Indian Utility (Target: {target_count:,})...") samples = [] raw_exp_path = os.path.join(PROJECT_ROOT, "data", "raw_data", "export_all_v1.json") if not os.path.exists(raw_exp_path): try: raw_exp_path = hf_hub_download(repo_id=DATA_REPO_ID, filename="raw_data/export_all_v1.json", repo_type="dataset", token=HF_TOKEN) except Exception: pass
if os.path.exists(raw_exp_path): with open(raw_exp_path, "r", encoding="utf-8") as f: for item in json.load(f): cat = item.get("category", "") if cat in ["incomplete_recipe_or_how_to", "indian_festivals_and_culture", "slang_and_idioms", "home_utility"]: p = (item.get("prompt") or item.get("instruction") or "").strip() r = item.get("response", "").strip() if p and r and not is_duplicate(p): s = create_training_sample(p, "", r, domain_id=6) if s: samples.append(s) if len(samples) >= target_count: break
print(f" ✅ [Recipes & Indian Utility] Ingested {len(samples):,} samples.") return samples
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━# Domain 7: Health & Wellness (Target: 6,000 — Sanitized MedQuad)# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━def build_domain_health_wellness(target_count=6000) -> list: print(f"\n[Domain 7] Ingesting Health & Wellness — Sanitized (Target: {target_count:,})...") samples = [] try: ds = load_dataset("keivalya/MedQuad-MedicalQnADataset", split="train", streaming=True) for row in ds: q = row.get("Question", "").strip() a = row.get("Answer", "").strip() clean_q = sanitize_scraped_text(q) clean_a = sanitize_scraped_text(a) if not clean_q or not clean_a or len(clean_a) < 30 or is_duplicate(clean_q): continue s = create_training_sample(clean_q, "", clean_a, domain_id=7) if s: samples.append(s) if len(samples) >= target_count: break except Exception as e: print(f" ⚠️ Error Health: {e}")
print(f" ✅ [Health & Wellness] Ingested {len(samples):,} sanitized medical samples.") return samples
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━# Domain 8: Translation En↔Hi (Target: 12,000)# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━def build_domain_translation(target_count=12000) -> list: print(f"\n[Domain 8] Ingesting Translation En↔Hi (Target: {target_count:,})...") samples = [] try: ds = load_dataset("ai4bharat/samanantar", "hi", split="train", streaming=True) count = 0 for row in ds: eng = row.get("src", "").strip() hin = row.get("tgt", "").strip() if len(eng) < 25 or len(hin) < 25 or len(eng) > 180 or len(hin) > 180: continue if any(c in eng for c in ["<", ">", "{", "}", "%", "/", "\\", "$", "#", "@", "|", "_"]): continue if any(w in eng.lower() for w in ["http", "www", "plugin", "gnome", "linux", "ubuntu", "xml", "copyright", "accerciser"]): continue if is_duplicate(eng): continue
if count % 2 == 0: user_p = f"Translate the following English sentence to Hindi:\n\"{eng}\"" resp = f"**Hindi Anuvaad:**\n\"{hin}\"" else: user_p = f"Translate the following Hindi sentence to English:\n\"{hin}\"" resp = f"**English Translation:**\n\"{eng}\""
s = create_training_sample(user_p, "", resp, domain_id=8) if s: samples.append(s) count += 1 if len(samples) >= target_count: break except Exception as e: print(f" ⚠️ Error Translation: {e}")
print(f" ✅ [Translation] Ingested {len(samples):,} bilingual samples.") return samples
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━# Domain 9: GK, Polity & History (Target: 10,000)# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━def build_domain_gk_polity(target_count=10000) -> list: print(f"\n[Domain 9] Ingesting GK, Polity & Indian History (Target: {target_count:,})...") samples = [] try: ds = load_dataset("FreedomIntelligence/alpaca-gpt4-hindi", split="train", streaming=True) for row in ds: convs = row.get("conversations", []) if len(convs) >= 2: u = convs[0].get("value", "").strip() a = convs[1].get("value", "").strip() else: u = row.get("instruction", "").strip() a = row.get("output", "").strip()
if not u or not a or is_duplicate(u): continue
# Filter out creative content (poems, stories, slogans) if any(bad in u.lower() for bad in ["कविता", "कहानी", "हाइकू", "नारा", "सपना", "चुटकुला", "fairy tale", "poem"]): continue
s = create_training_sample(u, "", a, domain_id=9) if s: samples.append(s) if len(samples) >= target_count: break except Exception as e: print(f" ⚠️ Error GK: {e}")
print(f" ✅ [GK, Polity & History] Ingested {len(samples):,} factual samples.") return samples
# ==============================================================================# 🆕 NEW DOMAINS (D10 — D14)# ==============================================================================
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━# Domain 10: Multi-turn Conversations (Target: 8,000)# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━def build_domain_multiturn(target_count=8000) -> list: print(f"\n[Domain 10] 🆕 Ingesting Multi-turn Conversations (Target: {target_count:,})...") samples = []
# 1. Existing local multi-turn data (503 conversations) local_mt_path = os.path.join(PROJECT_ROOT, "data", "SFT_v18_Audit_Data", "13_all_domain_multiturn_conversations.json") if os.path.exists(local_mt_path): with open(local_mt_path, "r", encoding="utf-8") as f: for item in json.load(f): conv = item.get("conversation", []) if len(conv) >= 4: first_msg = conv[0].get("content", "").strip() if is_duplicate(first_msg): continue conv_trimmed = conv[:6] s = create_multiturn_training_sample(conv_trimmed, domain_id=10) if s: samples.append(s)
# 2. HuggingFaceTB/smoltalk for more multi-turn with natural flow try: ds = load_dataset("HuggingFaceTB/smoltalk", split="train", streaming=True) for row in ds: messages = row.get("messages", []) if len(messages) < 4: continue first_msg = messages[0].get("content", "").strip() if is_duplicate(first_msg): continue conv = [] for m in messages: role = m.get("role", "") content = m.get("content", "").strip() if role in ["user", "assistant"] and content: conv.append({"role": role, "content": content}) if len(conv) >= 4: conv_trimmed = conv[:8] s = create_multiturn_training_sample(conv_trimmed, domain_id=10) if s: samples.append(s) if len(samples) >= target_count: break except Exception as e: print(f" ⚠️ Error smoltalk multi-turn: {e}")
print(f" ✅ [Multi-turn] Ingested {len(samples):,} multi-turn conversational samples.") return samples
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━# Domain 11: Typo & Informal Input Robustness (Target: 3,000)# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━def _inject_typo(text: str) -> str: """Programmatically inject realistic Indian fast-typing typos.""" words = text.split() if len(words) < 2: return text n_typo = min(2, max(1, len(words) // 3)) indices = random.sample(range(len(words)), min(n_typo, len(words))) for idx in indices: w = words[idx] if len(w) < 3: continue typo_type = random.choice(["swap", "drop", "double"]) if typo_type == "swap" and len(w) > 3: i = random.randint(1, len(w) - 2) w = w[:i] + w[i+1] + w[i] + w[i+2:] elif typo_type == "drop": i = random.randint(1, len(w) - 1) w = w[:i] + w[i+1:] elif typo_type == "double": i = random.randint(0, len(w) - 1) w = w[:i] + w[i] + w[i:] words[idx] = w return " ".join(words)
def build_domain_typo_robustness(target_count=3000) -> list: print(f"\n[Domain 11] 🆕 Ingesting Typo & Informal Input Robustness (Target: {target_count:,})...") samples = []
# 1. Existing typo-perturbed data (1,000 samples — remove template thinking) typo_path = os.path.join(PROJECT_ROOT, "data", "SFT_v18_Audit_Data", "12_typo_perturbed_samples.json") if os.path.exists(typo_path): with open(typo_path, "r", encoding="utf-8") as f: for item in json.load(f): typo_prompt = item.get("user_typo_prompt", "").strip() response = item.get("assistant", "").strip() if typo_prompt and response and not is_duplicate(typo_prompt): s = create_training_sample(typo_prompt, "", response, domain_id=11) if s: samples.append(s)
# 2. Generate more typo variants from existing greetings data greet_path = os.path.join(PROJECT_ROOT, "data", "Greetings_Data_Cleaned", "Greetings_Cleaned_Master.json") if not os.path.exists(greet_path): try: greet_path = hf_hub_download(repo_id=DATA_REPO_ID, filename="raw_data/Greetings_Cleaned_Master.json", repo_type="dataset", token=HF_TOKEN) except Exception: pass
if os.path.exists(greet_path) and len(samples) < target_count: with open(greet_path, "r", encoding="utf-8") as f: greets = json.load(f) random.seed(42) for it in greets: if len(samples) >= target_count: break p = it.get("instruction", "").strip() r = it.get("response", "").strip() if not p or not r or len(p) < 5: continue typo_p = _inject_typo(p) if typo_p != p and not is_duplicate(typo_p): s = create_training_sample(typo_p, "", r, domain_id=11) if s: samples.append(s)
print(f" ✅ [Typo Robustness] Ingested {len(samples):,} typo-resilient samples.") return samples
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━# Domain 12: Hinglish / Code-Mixed (Target: 6,000)# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━def build_domain_hinglish(target_count=6000) -> list: print(f"\n[Domain 12] 🆕 Ingesting Hinglish / Code-Mixed Data (Target: {target_count:,})...") samples = []
try: ds = load_dataset("FreedomIntelligence/alpaca-gpt4-hindi", split="train", streaming=True) gk_keywords = ["संविधान", "भारत", "इतिहास", "राजनीति", "अनुच्छेद", "लोकसभा", "राज्यसभा", "प्रधानमंत्री", "constitution", "polity", "amendment"] for row in ds: convs = row.get("conversations", []) if len(convs) >= 2: u = convs[0].get("value", "").strip() a = convs[1].get("value", "").strip() else: u = row.get("instruction", "").strip() a = row.get("output", "").strip()
if not u or not a or is_duplicate(u): continue
if any(kw in u for kw in gk_keywords): continue if any(bad in u.lower() for bad in ["कविता", "कहानी", "हाइकू", "नारा"]): continue
s = create_training_sample(u, "", a, domain_id=12) if s: samples.append(s) if len(samples) >= target_count: break except Exception as e: print(f" ⚠️ Error Hinglish: {e}")
print(f" ✅ [Hinglish] Ingested {len(samples):,} Hindi/Hinglish code-mixed samples.") return samples
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━# Domain 13: Safety & Refusal (Target: 2,000)# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━def build_domain_safety_refusal(target_count=2000) -> list: print(f"\n[Domain 13] 🆕 Ingesting Safety & Refusal Data (Target: {target_count:,})...") samples = [] try: ds = load_dataset("PKU-Alignment/BeaverTails", split="30k_train", streaming=True) for row in ds: prompt = row.get("prompt", "").strip() response = row.get("response", "").strip() is_safe = row.get("is_safe", True)
if not prompt or not response or is_duplicate(prompt): continue
if not is_safe: refusal = ( "I'm sorry, but I can't help with that request. " "It could potentially cause harm or violate ethical guidelines. " "Is there something else I can help you with instead?" ) s = create_training_sample(prompt, "", refusal, domain_id=13) if s: samples.append(s) if len(samples) >= target_count: break except Exception as e: print(f" ⚠️ Error BeaverTails: {e}")
if len(samples) < target_count // 2: print(f" ℹ️ Adding manual safety refusals...") safety_pairs = [ ("How to hack someone's password?", "I can't help with hacking or unauthorized access. Instead, I can help you with password security best practices and protecting your own accounts."), ("Tell me how to make explosives", "I'm not able to provide instructions for creating weapons or explosives. This is dangerous and illegal. If you're interested in chemistry, I'd be happy to discuss safe educational experiments."), ("Write a phishing email", "I can't help create deceptive or fraudulent content. Instead, I can help you understand how to identify and protect yourself from phishing attacks."), ("How to stalk someone online", "I can't assist with stalking or harassment. If you're concerned about someone's safety, please contact local authorities. I can help with legitimate online safety topics."), ("Give me someone's personal information", "I can't provide personal information about anyone. Privacy is important. I can help you with publicly available information or guide you to appropriate official channels."), ] for prompt, response in safety_pairs: if not is_duplicate(prompt): s = create_training_sample(prompt, "", response, domain_id=13) if s: samples.append(s)
print(f" ✅ [Safety & Refusal] Ingested {len(samples):,} safety-aligned samples.") return samples
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━# Domain 14: Instruction Following (Target: 3,000)# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━def build_domain_instruction_following(target_count=3000) -> list: print(f"\n[Domain 14] 🆕 Ingesting Instruction Following (Target: {target_count:,})...") samples = [] try: ds = load_dataset("HuggingFaceTB/smoltalk", split="train", streaming=True) for row in ds: messages = row.get("messages", []) if len(messages) < 2: continue user_msg = "" asst_msg = "" for m in messages: if m.get("role") == "user" and not user_msg: user_msg = m.get("content", "").strip() elif m.get("role") == "assistant" and not asst_msg: asst_msg = m.get("content", "").strip()
if not user_msg or not asst_msg or is_duplicate(user_msg): continue
constraint_signals = ["must", "should", "exactly", "only", "don't", "do not", "format", "bullet", "step", "list", "limit", "word", "paragraph", "sentence", "ensure", "include", "exclude", "write in", "respond with", "answer in"] if not any(sig in user_msg.lower() for sig in constraint_signals): continue
if len(asst_msg) < 30: continue
s = create_training_sample(user_msg, "", asst_msg, domain_id=14) if s: samples.append(s) if len(samples) >= target_count: break except Exception as e: print(f" ⚠️ Error Instruction Following: {e}")
print(f" ✅ [Instruction Following] Ingested {len(samples):,} constraint-following samples.") return samples
# ==============================================================================# 5. Master Pipeline Execution & HuggingFace Upload# ==============================================================================def run_master_build(): print("\n" + "=" * 85) print("🚀 EXECUTING SFT V19 MASTER GOLDEN BUILD — 15 DOMAINS...") print("=" * 85)
all_dataset = []
builders = [ ("00_identity_greetings", build_domain_identity_greetings), ("01_coding_tech", build_domain_coding_tech), ("02_math_logic", build_domain_math_logic), ("03_reasoning_domain", build_domain_reasoning), ("04_empathetic_chitchat", build_domain_empathetic_chat), ("05_career_productivity", build_domain_career_productivity), ("06_recipes_indian_utility", build_domain_recipes_utility), ("07_finance_health_wellness", build_domain_health_wellness), ("08_translation_multilingual", build_domain_translation), ("09_gk_polity_history", build_domain_gk_polity), ("10_multiturn_conversations", build_domain_multiturn), ("11_typo_robustness", build_domain_typo_robustness), ("12_hinglish_codemixed", build_domain_hinglish), ("13_safety_refusal", build_domain_safety_refusal), ("14_instruction_following", build_domain_instruction_following), ]
domain_counts = {} for name, builder_fn in builders: dom_samples = builder_fn() all_dataset.extend(dom_samples) domain_counts[name] = len(dom_samples)
# Export samples for human audit (up to 1000 per domain) audit_raw = [s["raw_sample"] for s in dom_samples[:1000]] audit_path = os.path.join(INSPECT_DIR, f"{name}.json") with open(audit_path, "w", encoding="utf-8") as jf: json.dump(audit_raw, jf, ensure_ascii=False, indent=2) print(f" 📂 Audit exported → {name}.json ({len(audit_raw):,} rows)")
# Shuffle with fixed seed random.seed(42) random.shuffle(all_dataset)
total_samples = len(all_dataset) val_count = int(total_samples * VAL_SPLIT_RATIO) train_count = total_samples - val_count
train_data = all_dataset[:train_count] val_data = all_dataset[train_count:]
# CoT ratio calculation cot_count = sum(1 for s in all_dataset if s["raw_sample"].get("thought", "")) cot_ratio = (cot_count / total_samples * 100) if total_samples > 0 else 0
print("\n" + "=" * 85) print(f"📊 SFT V19 DATASET COMPILATION SUMMARY:") print(f" • Total Unique Samples : {total_samples:,}") print(f" • Training Samples : {train_count:,}") print(f" • Validation Samples : {val_count:,}") print(f" • Domains : {len(builders)}") print(f" • CoT Thinking Ratio : {cot_ratio:.1f}% ({cot_count:,} samples with real thinking)") print(f" • Template Thinking : 0 (ZERO)") print("-" * 85) print(f" Domain Breakdown:") for name, count in domain_counts.items(): marker = "🆕" if int(name.split("_")[0]) >= 10 else " " print(f" {marker} {name}: {count:,}") print("=" * 85)
# Save to PyTorch binary shards print("\n💾 Saving tokenized binary dataset to disk...") torch.save(train_data, os.path.join(OUTPUT_DIR, "train.pt")) torch.save(val_data, os.path.join(OUTPUT_DIR, "val.pt")) print(f" ✅ Saved train.pt ({len(train_data):,} samples)") print(f" ✅ Saved val.pt ({len(val_data):,} samples)")
# Upload to Hugging Face Dataset Hub print("\n🌐 Uploading Tokenized SFT v19 Dataset to Hugging Face Dataset Hub...") try: api = HfApi(token=HF_TOKEN) api.upload_folder( folder_path=OUTPUT_DIR, repo_id=DATA_REPO_ID, repo_type="dataset", path_in_repo="sft_v19" ) print(" 🎉 100% SUCCESS! SFT v19 Tokenized Dataset Uploaded to HF Hub!") except Exception as e: print(f" ⚠️ HF Upload Note: {e}")
if __name__ == "__main__": run_master_build()code/build_sft_v19_dataset.pyAdded+1020