Download code/build_master_sft_v3_dataset.py from ViuAI/ViuAI-500M: direct link, hf CLI and curl.
- Browser
- Download file 20.4 kB
-
https://huggingface.co/ViuAI/ViuAI-500M/resolve/main/code/build_master_sft_v3_dataset.py
- Command line
-
hf download hf://ViuAI/ViuAI-500M/code/build_master_sft_v3_dataset.py
-
curl -L -o build_master_sft_v3_dataset.py https://huggingface.co/ViuAI/ViuAI-500M/resolve/main/code/build_master_sft_v3_dataset.py
20.4 kB
| # ============================================================================== | |
| # 🚀 ViuAI Sarus-500M — Master SFT v3 1-Million Dataset Builder | |
| # ============================================================================== | |
| # Hardened Production-Grade Architecture: | |
| # - 100% Real, Trusted, and Verified Datasets Only (Zero Python Synthesis) | |
| # - Competitor Identity Contamination Filter (OpenAI, ChatGPT, Claude, Bard, etc.) | |
| # - Strict Global Response Deduplication: max_resp_freq = 1 | |
| # - Context Window Integrity: MAX_SEQ_LEN = 2048 with complete <|endofturn|> | |
| # - Multi-Turn Preservation: Assistant Loss Masking (labels = -100 on user turns) | |
| # - Stratified Domain-Wise Validation Split (2% exact representation per domain) | |
| # - Memory-Efficient Native Array Packing (array('i')) | |
| # ============================================================================== | |
| import os | |
| import sys | |
| import re | |
| import json | |
| import time | |
| import array | |
| import random | |
| import argparse | |
| import numpy as np | |
| from typing import Dict, List, Set, Tuple | |
| from tokenizers import Tokenizer | |
| from huggingface_hub import HfApi | |
| sys.stdout.reconfigure(encoding='utf-8') | |
| # Target Architectural Constraints | |
| MAX_SEQ_LEN = 2048 | |
| MIN_RESPONSE_TOKENS = 3 | |
| VAL_SPLIT_RATIO = 0.02 | |
| # Special Tokens | |
| USER_TOKEN = "<|user|>" | |
| ASSISTANT_TOKEN = "<|assistant|>" | |
| EOT_TOKEN = "<|endofturn|>" | |
| EOT_ID = 64002 | |
| DOMAIN_MAP = { | |
| 0: "identity_and_safety", | |
| 1: "translation_and_hindi", | |
| 2: "coding_and_tech", | |
| 3: "ncert_science_stem", | |
| 4: "indian_history_polity", | |
| 5: "mathematics_logic", | |
| 6: "everyday_chat_empathy", | |
| 7: "workplace_summarization", | |
| 8: "cooking_culture_utility", | |
| 9: "antihallucination_logic" | |
| } | |
| # Safeguard 1: Competitor Identity Filter | |
| COMPETITOR_PATTERNS = [ | |
| r"\bopenai\b", r"\bchatgpt\b", r"\bgpt-?3(\.5)?\b", r"\bgpt-?4\b", | |
| r"\bclaude\b", r"\banthropic\b", r"\bbard\b", r"\bllama\b", | |
| r"\bmeta ai\b", r"as an ai language model", r"as a language model trained by", | |
| r"trained by openai", r"developed by openai", r"i am a large language model", | |
| r"i am an ai language model", r"sorry, as an ai", r"i am claude" | |
| ] | |
| COMPETITOR_REGEX = re.compile("|".join(COMPETITOR_PATTERNS), re.IGNORECASE) | |
| def is_clean(text: str) -> bool: | |
| if not text: | |
| return False | |
| return not bool(COMPETITOR_REGEX.search(text)) | |
| def clean_and_load_file(filepath: str, domain_id: int, seen_responses: Set[str], seen_pairs: Set[str], is_translation_only=False) -> List[Dict]: | |
| if not os.path.exists(filepath): | |
| print(f" ⚠️ Warning: File not found: {filepath}") | |
| return [] | |
| collected = [] | |
| with open(filepath, "r", encoding="utf-8", errors="ignore") as f: | |
| for line in f: | |
| if not line.strip(): | |
| continue | |
| try: | |
| item = json.loads(line) | |
| except Exception: | |
| continue | |
| # Case A: Multi-turn format | |
| if "turns" in item: | |
| turns = item["turns"] | |
| if not isinstance(turns, (list, tuple)) or len(turns) == 0: | |
| continue | |
| # Verify clean | |
| clean_conv = True | |
| for u_text, a_text in turns: | |
| if not is_clean(a_text) or not is_clean(u_text): | |
| clean_conv = False | |
| break | |
| if not clean_conv: | |
| continue | |
| # Response dedup on final assistant response | |
| last_resp = turns[-1][1].strip() | |
| if not last_resp or len(last_resp) < 2: | |
| continue | |
| if last_resp in seen_responses: | |
| continue | |
| seen_responses.add(last_resp) | |
| collected.append({ | |
| "turns": turns, | |
| "domain_id": domain_id | |
| }) | |
| continue | |
| # Case B: Multi-turn from raw string with [assistant response]: / [user follow-up]: | |
| inst = str(item.get("instruction") or item.get("prompt") or item.get("input") or "").strip() | |
| resp = str(item.get("response") or item.get("output") or item.get("target") or "").strip() | |
| inst_lower = inst.lower() | |
| resp_lower = resp.lower() | |
| if "[assistant response]:" in inst_lower and "[user follow-up]:" in inst_lower: | |
| parts = re.split(r"\[assistant response\]:", inst, flags=re.IGNORECASE) | |
| if len(parts) >= 2: | |
| u1 = parts[0].strip() | |
| rest = re.split(r"\[user follow-up\]:", parts[1], flags=re.IGNORECASE) | |
| if len(rest) >= 2: | |
| a1 = rest[0].strip() | |
| u2 = rest[1].strip() | |
| a2 = resp.strip() | |
| if len(u1) >= 3 and len(a1) >= 1 and len(u2) >= 3 and len(a2) >= 1: | |
| if not is_clean(a1) or not is_clean(a2) or not is_clean(u1) or not is_clean(u2): | |
| continue | |
| if a2 in seen_responses: | |
| continue | |
| seen_responses.add(a2) | |
| collected.append({ | |
| "turns": [(u1, a1), (u2, a2)], | |
| "domain_id": domain_id | |
| }) | |
| continue | |
| # Case C: Single-turn standard format | |
| if len(inst) < 3 or len(resp) < 1: | |
| continue | |
| if len(inst) > 6000 or len(resp) > 8000: | |
| continue | |
| # Competitor filter | |
| if not is_clean(resp) or not is_clean(inst): | |
| continue | |
| # Filter out synthetic excuses | |
| if "sorry, as an ai" in resp_lower: | |
| continue | |
| if "[assistant response]:" in inst_lower: | |
| continue | |
| # URL filter: Allow code, slangs, workplace, and web RAG | |
| if domain_id not in (2, 6, 7, 9): | |
| if "http://" in inst or "https://" in inst or "www." in inst: | |
| continue | |
| # Translation-only filter if mixed file | |
| if is_translation_only: | |
| if not any(k in inst_lower for k in ("translat", "अनुवाद", "hindi mein", "in hindi", "to hindi", "to english", "into hindi", "into english")): | |
| continue | |
| # Strict global deduplication: | |
| # For short constants (math/code answers <= 10 chars), check (inst, resp) pair | |
| if len(resp) <= 10: | |
| pair_key = f"{inst.lower()} || {resp.lower()}" | |
| if pair_key in seen_pairs: | |
| continue | |
| seen_pairs.add(pair_key) | |
| else: | |
| if resp in seen_responses: | |
| continue | |
| seen_responses.add(resp) | |
| collected.append({ | |
| "instruction": inst, | |
| "response": resp, | |
| "domain_id": domain_id | |
| }) | |
| return collected | |
| def build_dataset(root_dir: str, output_dir: str, upload_to_hf=False, hf_token=None): | |
| print("=" * 85) | |
| print("🚀 BUILDING MASTER 1M VERIFIED SFT v3 DATASET") | |
| print("=" * 85) | |
| tok_path = os.path.join(root_dir, "tokenizer", "tokenizer.json") | |
| if not os.path.exists(tok_path): | |
| tok_path = "tokenizer.json" | |
| if not os.path.exists(tok_path): | |
| raise FileNotFoundError(f"Tokenizer not found at {tok_path}") | |
| tokenizer = Tokenizer.from_file(tok_path) | |
| print(f"✅ Tokenizer Loaded. Vocab Size: {tokenizer.get_vocab_size():,}") | |
| for tok_str in [USER_TOKEN, ASSISTANT_TOKEN, EOT_TOKEN]: | |
| tok_id = tokenizer.token_to_id(tok_str) | |
| if tok_id is None: | |
| raise ValueError(f"CRITICAL: Special token {tok_str} is not registered in tokenizer.json!") | |
| assert tokenizer.token_to_id(EOT_TOKEN) == EOT_ID, f"EOT_ID mismatch: expected {EOT_ID}, got {tokenizer.token_to_id(EOT_TOKEN)}" | |
| print(f"✅ Special Tokens Verified: USER={tokenizer.token_to_id(USER_TOKEN)}, ASSISTANT={tokenizer.token_to_id(ASSISTANT_TOKEN)}, EOT={EOT_ID}") | |
| os.makedirs(output_dir, exist_ok=True) | |
| seen_responses: Set[str] = set() | |
| seen_pairs: Set[str] = set() | |
| all_samples = [] | |
| # Comprehensive 1M Ingestion Plan across all 39 verified files: | |
| sarus_raw = os.path.join(root_dir, "data", "sarus_sft_raw") | |
| v1_raw = os.path.join(root_dir, "data", "sft_v1_raw") | |
| hf_raw = os.path.join(root_dir, "data", "hf_verified_raw") | |
| plans = [ | |
| # Domain 0: Identity & Safety | |
| (0, [ | |
| (os.path.join(sarus_raw, "d0_identity_sarus.jsonl"), False), | |
| (os.path.join(v1_raw, "d0_identity_persona.jsonl"), False), | |
| ]), | |
| # Domain 1: Translation & Hindi | |
| (1, [ | |
| (os.path.join(sarus_raw, "d6_hindi_culture.jsonl"), False), | |
| (os.path.join(sarus_raw, "d7_summarization_translation.jsonl"), True), | |
| (os.path.join(hf_raw, "d_indic_align.jsonl"), False), | |
| (os.path.join(hf_raw, "d_aya_hindi.jsonl"), False), | |
| ]), | |
| # Domain 2: Coding & Tech | |
| (2, [ | |
| (os.path.join(sarus_raw, "d3_coding_tech.jsonl"), False), | |
| (os.path.join(v1_raw, "d15_tech_troubleshooting.jsonl"), False), | |
| (os.path.join(hf_raw, "d_python_code.jsonl"), False), | |
| ]), | |
| # Domain 3: NCERT Science & STEM | |
| (3, [ | |
| (os.path.join(v1_raw, "d1_ncert_curriculum.jsonl"), False), | |
| (os.path.join(sarus_raw, "d5_general_stem.jsonl"), False), | |
| ]), | |
| # Domain 4: Indian History & Polity | |
| (4, [ | |
| (os.path.join(v1_raw, "d2_indian_history_affairs.jsonl"), False), | |
| (os.path.join(sarus_raw, "d2_ncert_indian_history.jsonl"), False), | |
| ]), | |
| # Domain 5: Mathematics & Logic | |
| (5, [ | |
| (os.path.join(sarus_raw, "d4_math_arithmetic.jsonl"), False), | |
| (os.path.join(hf_raw, "d_metamath_cot.jsonl"), False), | |
| ]), | |
| # Domain 6: Everyday Chat & Empathy (Multi-Turn Natural Dialogue) | |
| (6, [ | |
| (os.path.join(v1_raw, "d3_everyday_chat_empathy.jsonl"), False), | |
| (os.path.join(sarus_raw, "d1_greetings_cultural.jsonl"), False), | |
| (os.path.join(sarus_raw, "d8_multiturn_dialogue.jsonl"), False), | |
| (os.path.join(v1_raw, "d4_multiturn_dialogue.jsonl"), False), | |
| (os.path.join(v1_raw, "d6_typo_robustness_slangs.jsonl"), False), | |
| (os.path.join(v1_raw, "d18_mental_wellness_exam_habits.jsonl"), False), | |
| (os.path.join(hf_raw, "d_ultrachat_multiturn.jsonl"), False), | |
| (os.path.join(hf_raw, "d_oasst2_dialogue.jsonl"), False), | |
| ]), | |
| # Domain 7: Workplace & Summarization | |
| (7, [ | |
| (os.path.join(v1_raw, "d8_corporate_workplace_writing.jsonl"), False), | |
| (os.path.join(v1_raw, "d7_summarization_tldr.jsonl"), False), | |
| (os.path.join(v1_raw, "d14_career_guidance_interview.jsonl"), False), | |
| (os.path.join(v1_raw, "d5_instruction_following.jsonl"), False), | |
| (os.path.join(v1_raw, "d19_creative_writing_scripts.jsonl"), False), | |
| (os.path.join(hf_raw, "d_dolly_closedqa.jsonl"), False), | |
| ]), | |
| # Domain 8: Cooking & Culture Utility | |
| (8, [ | |
| (os.path.join(v1_raw, "d9_cooking_kitchen_science.jsonl"), False), | |
| (os.path.join(v1_raw, "d16_indian_festivals_heritage.jsonl"), False), | |
| (os.path.join(v1_raw, "d13_health_wellness_remedies.jsonl"), False), | |
| (os.path.join(v1_raw, "d12_comparisons_pros_cons.jsonl"), False), | |
| ]), | |
| # Domain 9: Anti-Hallucination, Web-RAG & Grounded Context QA | |
| (9, [ | |
| (os.path.join(v1_raw, "d10_antihallucination_trick_qa.jsonl"), False), | |
| (os.path.join(v1_raw, "d20_commonsense_practical_logic.jsonl"), False), | |
| (os.path.join(v1_raw, "d11_extraction_table_formatting.jsonl"), False), | |
| (os.path.join(v1_raw, "d17_finance_budgeting_scam_safety.jsonl"), False), | |
| (os.path.join(hf_raw, "d_squad_v2_rag.jsonl"), False), | |
| (os.path.join(hf_raw, "d_ms_marco_rag.jsonl"), False), | |
| ]), | |
| ] | |
| print("\n📦 Loading, filtering, and globally deduplicating all 39 verified files...") | |
| domain_counts = {} | |
| domain_buckets = {did: [] for did in DOMAIN_MAP} | |
| for did, sources in plans: | |
| d_name = DOMAIN_MAP[did] | |
| d_samples = [] | |
| for fpath, trans_only in sources: | |
| sub = clean_and_load_file(fpath, did, seen_responses, seen_pairs, is_translation_only=trans_only) | |
| d_samples.extend(sub) | |
| domain_counts[d_name] = len(d_samples) | |
| domain_buckets[did].extend(d_samples) | |
| all_samples.extend(d_samples) | |
| print(f" • [D{did}: {d_name:26s}]: {len(d_samples):>8,d} clean 100% unique samples") | |
| total_samples = len(all_samples) | |
| print("=" * 85) | |
| print(f"🎯 Total Verified 100% Unique Samples Ingested: {total_samples:,}") | |
| print("=" * 85) | |
| # Stratified Domain-Wise Validation Split (exact 2% per domain) | |
| print("\n🔀 Performing Stratified Domain-Wise Train/Val Split (2% per domain)...") | |
| train_samples = [] | |
| val_samples = [] | |
| for did in sorted(domain_buckets.keys()): | |
| d_items = domain_buckets[did] | |
| random.seed(42 + did) | |
| random.shuffle(d_items) | |
| val_size = max(50, int(len(d_items) * VAL_SPLIT_RATIO)) | |
| val_samples.extend(d_items[:val_size]) | |
| train_samples.extend(d_items[val_size:]) | |
| random.seed(42) | |
| random.shuffle(train_samples) | |
| random.shuffle(val_samples) | |
| print(f" • Train Samples: {len(train_samples):,}") | |
| print(f" • Val Samples: {len(val_samples):,}") | |
| def tokenize_and_pack(samples, split_name): | |
| tokens_arr = array.array('i') | |
| labels_arr = array.array('i') | |
| offsets_arr = array.array('q', [0]) | |
| domains_arr = array.array('h') | |
| t0 = time.time() | |
| skipped_overlength = 0 | |
| skipped_short_resp = 0 | |
| valid_count = 0 | |
| for idx, item in enumerate(samples): | |
| did = item["domain_id"] | |
| if "turns" in item: | |
| # Multi-turn conversation packing | |
| full_tok = [] | |
| full_lbl = [] | |
| turns = item["turns"] | |
| for t_idx, (u_text, a_text) in enumerate(turns): | |
| prefix = "\n" if t_idx > 0 else "" | |
| u_str = f"{prefix}{USER_TOKEN}\n{u_text}{EOT_TOKEN}\n{ASSISTANT_TOKEN}\n" | |
| a_str = f"{a_text}{EOT_TOKEN}" | |
| u_ids = tokenizer.encode(u_str).ids | |
| a_ids = tokenizer.encode(a_str).ids | |
| full_tok.extend(u_ids + a_ids) | |
| full_lbl.extend([-100] * len(u_ids) + a_ids) | |
| else: | |
| # Single-turn conversation packing | |
| inst = item["instruction"] | |
| resp = item["response"] | |
| prompt_str = f"{USER_TOKEN}\n{inst}{EOT_TOKEN}\n{ASSISTANT_TOKEN}\n" | |
| resp_str = f"{resp}{EOT_TOKEN}" | |
| p_ids = tokenizer.encode(prompt_str).ids | |
| r_ids = tokenizer.encode(resp_str).ids | |
| if len(r_ids) < MIN_RESPONSE_TOKENS: | |
| skipped_short_resp += 1 | |
| continue | |
| full_tok = p_ids + r_ids | |
| full_lbl = [-100] * len(p_ids) + r_ids | |
| # Context Window Integrity (MAX_SEQ_LEN = 2048) | |
| if len(full_tok) > MAX_SEQ_LEN: | |
| skipped_overlength += 1 | |
| continue | |
| active_tokens = sum(1 for lbl in full_lbl if lbl != -100) | |
| if active_tokens < MIN_RESPONSE_TOKENS: | |
| skipped_short_resp += 1 | |
| continue | |
| tokens_arr.extend(full_tok) | |
| labels_arr.extend(full_lbl) | |
| offsets_arr.append(offsets_arr[-1] + len(full_tok)) | |
| domains_arr.append(did) | |
| valid_count += 1 | |
| if (idx + 1) % 100000 == 0 or (idx + 1) == len(samples): | |
| pct = ((idx + 1) / len(samples)) * 100 | |
| speed = valid_count / (time.time() - t0 + 1e-6) | |
| print(f" [{split_name.upper()}] Processed {idx + 1:,} / {len(samples):,} ({pct:4.1f}%) | Tokens: {len(tokens_arr):,} | Speed: {speed:,.0f} samples/s") | |
| print(f"\n ✅ [{split_name.upper()}] Packing Completed in {time.time() - t0:.1f}s:") | |
| print(f" • Valid Sequences: {valid_count:,}") | |
| print(f" • Total Tokens: {len(tokens_arr):,}") | |
| print(f" • Over-length (>2048) Skipped: {skipped_overlength:,}") | |
| print(f" • Short-resp Skipped: {skipped_short_resp:,}") | |
| # Save numpy shards (use int32 for labels to support negative -100 mask AND vocab size > 32767) | |
| print(f" 💾 Writing {split_name} numpy binary shards to {output_dir}...") | |
| np.save(os.path.join(output_dir, f"{split_name}_tokens.npy"), np.array(tokens_arr, dtype=np.uint16)) | |
| np.save(os.path.join(output_dir, f"{split_name}_labels.npy"), np.array(labels_arr, dtype=np.int32)) | |
| np.save(os.path.join(output_dir, f"{split_name}_offsets.npy"), np.array(offsets_arr, dtype=np.uint64)) | |
| np.save(os.path.join(output_dir, f"{split_name}_domains.npy"), np.array(domains_arr, dtype=np.uint8)) | |
| return valid_count, len(tokens_arr) | |
| print("\n⚡ Tokenizing and serializing VALIDATION split...") | |
| val_valid, val_tokens = tokenize_and_pack(val_samples, "val") | |
| print("\n⚡ Tokenizing and serializing TRAINING split...") | |
| train_valid, train_tokens = tokenize_and_pack(train_samples, "train") | |
| metadata = { | |
| "dataset_name": "ViuAI Sarus-500M Master SFT v3 (1M Verified)", | |
| "total_train_samples": train_valid, | |
| "total_val_samples": val_valid, | |
| "total_train_tokens": train_tokens, | |
| "total_val_tokens": val_tokens, | |
| "max_seq_len": MAX_SEQ_LEN, | |
| "vocab_size": tokenizer.get_vocab_size(), | |
| "special_tokens": { | |
| "user": USER_TOKEN, | |
| "assistant": ASSISTANT_TOKEN, | |
| "eot": EOT_TOKEN, | |
| "eot_id": EOT_ID | |
| }, | |
| "domain_counts": domain_counts, | |
| "domain_names": DOMAIN_MAP, | |
| "created_at": time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime()) | |
| } | |
| meta_path = os.path.join(output_dir, "metadata.json") | |
| with open(meta_path, "w", encoding="utf-8") as f: | |
| json.dump(metadata, f, indent=2, ensure_ascii=False) | |
| print(f"\n📋 Metadata written to: {meta_path}") | |
| # Hub Upload if requested | |
| if upload_to_hf: | |
| token = hf_token or os.environ.get("HF_TOKEN") | |
| if not token: | |
| print("⚠️ Upload requested but HF_TOKEN not found.") | |
| return metadata | |
| api = HfApi(token=token) | |
| repo_id = "ViuAI/viuai-500m-sft-tokenized" | |
| print(f"\n🚀 Uploading Master SFT v3 (1M Verified) Shards to {repo_id} (folder: sft_v3)...") | |
| upload_files = [ | |
| "train_tokens.npy", "train_labels.npy", "train_offsets.npy", "train_domains.npy", | |
| "val_tokens.npy", "val_labels.npy", "val_offsets.npy", "val_domains.npy", | |
| "metadata.json" | |
| ] | |
| for f in upload_files: | |
| local_p = os.path.join(output_dir, f) | |
| print(f" ⬆️ Uploading {f} ({os.path.getsize(local_p)/(1024*1024):.2f} MB)...") | |
| api.upload_file( | |
| path_or_fileobj=local_p, | |
| path_in_repo=f"sft_v3/{f}", | |
| repo_id=repo_id, | |
| repo_type="dataset" | |
| ) | |
| print("✅ 1M Master SFT v3 Shards Uploaded Successfully to Hugging Face!") | |
| return metadata | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Build 1M Master SFT v3 Gold Dataset") | |
| parser.add_argument("--root_dir", type=str, default=".", help="Project root directory") | |
| parser.add_argument("--output_dir", type=str, default="tokenized_data/sft_v3", help="Output tokenized directory") | |
| parser.add_argument("--upload", action="store_true", help="Upload to Hugging Face Hub") | |
| args = parser.parse_args() | |
| build_dataset(args.root_dir, args.output_dir, upload_to_hf=args.upload) | |
| if __name__ == "__main__": | |
| main() | |