Upload code/build_master_sft_v3_dataset_4.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427# ==============================================================================# 🚀 ViuAI Sarus-500M — Master SFT v3 Gold Dataset Builder (~220,000 Samples)# ==============================================================================# Hardened Production-Grade Architecture:# - Verified Special Token Registration & EOT_ID Assertion (Startup Guard)# - Context Window Integrity: Zero Mid-Sentence Cutoffs (<|endofturn|> always preserved)# - Zero NaN Loss Guarantee: All sequences have >= MIN_RESPONSE_TOKENS active labels# - Multi-Turn Conversation Support with Assistant Masking# - Combined Instruction+Response Prefix Deduplication (Preserves Code & Safety Templates)# - Stratified Domain-Wise Validation Split (2% exact representation per domain)# - Memory-Efficient Native Array Packing (array('i'))# - Zero Hardcoded Secret Leaks (HF_TOKEN via os.environ only)# ==============================================================================
import osimport sysimport reimport jsonimport timeimport arrayimport randomimport argparseimport numpy as npfrom typing import Dict, List, Set, Tuplefrom tokenizers import Tokenizerfrom huggingface_hub import HfApi, login
if 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")
USER_TOKEN = "<|user|>"ASSISTANT_TOKEN = "<|assistant|>"EOT_TOKEN = "<|endofturn|>"EOT_ID = 64002MAX_SEQ_LEN = 2048MIN_RESPONSE_TOKENS = 4VAL_SPLIT_RATIO = 0.02
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"}
def clean_and_load_file(filepath: str, max_count: int, domain_id: int, seen_keys: 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: lines = f.readlines()
random.seed(42 + domain_id) random.shuffle(lines)
for line in lines: if not line.strip(): continue try: item = json.loads(line) except Exception: continue
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()
# Check for multi-turn dialogue format (case-insensitive regex split) 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: # Multi-turn dedup key dedup_key = " ".join(u1.lower().split()[:15]) + " || " + " ".join(u2.lower().split()[:15]) if dedup_key in seen_keys: continue seen_keys.add(dedup_key)
collected.append({ "turns": [(u1, a1), (u2, a2)], "domain_id": domain_id }) if len(collected) >= max_count: break continue
# Single-turn length sanity (allow short valid answers like "42", "0", "Yes", "हाँ") if len(inst) < 3 or len(resp) < 1: continue if len(inst) > 6000 or len(resp) > 8000: continue
# Filter out bad synthetic artifacts / excuse loops if "birthday party" in resp_lower and "birthday" not in inst_lower: continue if "sorry, as an ai" in resp_lower and "refuse" not in inst_lower: continue if "[assistant response]:" in inst_lower: continue
# URL filter: Only filter non-coding and non-workplace domains (code/workplace legitimately contain URLs) if domain_id not in (2, 7): if "http://" in inst or "https://" in inst or "www." in inst: continue
# If file is mixed summarization+translation, filter for translation 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
# Combined instruction + response prefix deduplication (preserves code functions & safety refusal templates) inst_prefix = " ".join(inst_lower.split()[:15]) resp_prefix = " ".join(resp_lower.split()[:25]) dedup_key = f"{inst_prefix} || {resp_prefix}" if dedup_key in seen_keys: continue seen_keys.add(dedup_key)
collected.append({ "instruction": inst, "response": resp, "domain_id": domain_id })
if len(collected) >= max_count: break
return collected
def build_dataset(root_dir: str, output_dir: str, upload_to_hf=False, hf_token=None): print("=" * 85) print("🚀 BUILDING MASTER SFT v3 GOLD DATASET (~220,000 SAMPLES)") 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():,}")
# Startup Special Token Verification & Assertions 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 as a single token 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_keys = set() all_samples = []
# Domain Plans (Calibrated for 500M parameter model capacity) plans = [ # Domain 0: Identity & Safety (~2,500) - Tight, non-repetitive persona & safety (0, [ (os.path.join(root_dir, "data", "sarus_sft_raw", "d0_identity_sarus.jsonl"), 1500, False), (os.path.join(root_dir, "data", "sft_v1_raw", "d0_identity_persona.jsonl"), 1000, False), ]), # Domain 1: Translation & Hindi (~35,000) - Parallel translation + rich cultural Devanagari (1, [ (os.path.join(root_dir, "data", "sarus_sft_raw", "d7_summarization_translation.jsonl"), 15000, True), (os.path.join(root_dir, "data", "sarus_sft_raw", "d6_hindi_culture.jsonl"), 22000, False), ]), # Domain 2: Coding & Tech (~36,000) - Python syntax, logic, algorithms (2, [ (os.path.join(root_dir, "data", "sarus_sft_raw", "d3_coding_tech.jsonl"), 30000, False), (os.path.join(root_dir, "data", "sft_v1_raw", "d15_tech_troubleshooting.jsonl"), 6000, False), ]), # Domain 3: NCERT Science & STEM (~32,000) - Physics, Chemistry, Biology (3, [ (os.path.join(root_dir, "data", "sft_v1_raw", "d1_ncert_curriculum.jsonl"), 20000, False), (os.path.join(root_dir, "data", "sarus_sft_raw", "d5_general_stem.jsonl"), 12000, False), ]), # Domain 4: Indian History & Polity (~18,000) - Capped to prevent rote-memorization on 500M (4, [ (os.path.join(root_dir, "data", "sft_v1_raw", "d2_indian_history_affairs.jsonl"), 10000, False), (os.path.join(root_dir, "data", "sarus_sft_raw", "d2_ncert_indian_history.jsonl"), 8000, False), ]), # Domain 5: Mathematics & Logic (~30,000) - Boosted arithmetic & step-by-step reasoning (5, [ (os.path.join(root_dir, "data", "sarus_sft_raw", "d4_math_arithmetic.jsonl"), 30000, False), ]), # Domain 6: Everyday Chat & Empathy (~29,000) - 12k multi-turn conversations (6, [ (os.path.join(root_dir, "data", "sft_v1_raw", "d3_everyday_chat_empathy.jsonl"), 12000, False), (os.path.join(root_dir, "data", "sarus_sft_raw", "d1_greetings_cultural.jsonl"), 5000, False), (os.path.join(root_dir, "data", "sarus_sft_raw", "d8_multiturn_dialogue.jsonl"), 12000, False), ]), # Domain 7: Workplace & Summarization (~22,000) - Formal communication (7, [ (os.path.join(root_dir, "data", "sft_v1_raw", "d8_corporate_workplace_writing.jsonl"), 10000, False), (os.path.join(root_dir, "data", "sft_v1_raw", "d7_summarization_tldr.jsonl"), 6000, False), (os.path.join(root_dir, "data", "sft_v1_raw", "d14_career_guidance_interview.jsonl"), 6000, False), ]), # Domain 8: Cooking & Culture Utility (~15,500) - Heritage, lifestyle (8, [ (os.path.join(root_dir, "data", "sft_v1_raw", "d9_cooking_kitchen_science.jsonl"), 8000, False), (os.path.join(root_dir, "data", "sft_v1_raw", "d16_indian_festivals_heritage.jsonl"), 7500, False), ]), # Domain 9: Anti-Hallucination & Common Sense Logic (~16,000) - Grounded reasoning & scam defense (9, [ (os.path.join(root_dir, "data", "sft_v1_raw", "d10_antihallucination_trick_qa.jsonl"), 5000, False), (os.path.join(root_dir, "data", "sft_v1_raw", "d20_commonsense_practical_logic.jsonl"), 4000, False), (os.path.join(root_dir, "data", "sft_v1_raw", "d11_extraction_table_formatting.jsonl"), 3500, False), (os.path.join(root_dir, "data", "sft_v1_raw", "d17_finance_budgeting_scam_safety.jsonl"), 3500, False), ]), ]
print("\n📦 Loading, filtering, and deduplicating domain 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, cnt, trans_only in sources: sub = clean_and_load_file(fpath, cnt, did, seen_keys, 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):6,d} clean samples")
total_samples = len(all_samples) print(f"\n🎯 Total Curated Samples Ingested: {total_samples:,}")
# Stratified Domain-Wise Validation Split (exact 2% representation 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:])
# Shuffle splits independently random.seed(42) random.shuffle(train_samples) random.shuffle(val_samples)
print(f" • Train: {len(train_samples):,} samples") print(f" • Val: {len(val_samples):,} samples")
# High performance memory-efficient tokenizer and packer using array('i') 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
# Strict Context Window Integrity: # Over-length samples are skipped rather than sliced mid-sentence. # This guarantees: # 1. Model always observes clean <|endofturn|> completion. # 2. Labels never have only -100 (prevents NaN loss). 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
# Append to native arrays (low memory spike) 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) % 50000 == 0 or (idx + 1) == len(samples): pct = ((idx + 1) / len(samples)) * 100 print(f" [{split_name.upper()}] Processed {idx + 1:,} / {len(samples):,} ({pct:4.1f}%) | Tokens: {len(tokens_arr):,}")
print(f" 📊 {split_name.upper()} Stats: Valid={valid_count:,} | Skipped Overlength={skipped_overlength:,} | Skipped Short={skipped_short_resp:,}") print(f" 💾 Saving {split_name} memory-mapped numpy arrays to {output_dir}...") assert tokens_arr.itemsize == 4 and offsets_arr.itemsize == 8, f"Unexpected itemsize: tokens={tokens_arr.itemsize}, offsets={offsets_arr.itemsize}" np.save(os.path.join(output_dir, f"{split_name}_tokens.npy"), np.frombuffer(tokens_arr, dtype=np.int32)) np.save(os.path.join(output_dir, f"{split_name}_labels.npy"), np.frombuffer(labels_arr, dtype=np.int32)) np.save(os.path.join(output_dir, f"{split_name}_offsets.npy"), np.frombuffer(offsets_arr, dtype=np.int64)) np.save(os.path.join(output_dir, f"{split_name}_domains.npy"), np.frombuffer(domains_arr, dtype=np.int16)) print(f" ✅ Saved {split_name} ({valid_count:,} samples, {len(tokens_arr):,} tokens, time: {time.time()-t0:.1f}s)") return valid_count, len(tokens_arr)
print("\n🔨 Tokenizing Training Split...") final_train_cnt, total_train_toks = tokenize_and_pack(train_samples, "train")
print("\n🔨 Tokenizing Validation Split...") final_val_cnt, total_val_toks = tokenize_and_pack(val_samples, "val")
# Save metadata.json metadata = { "version": "v3", "description": "ViuAI Sarus-500M Master SFT v3 Gold Dataset (~220,000 samples, 10 Domains)", "created_at": time.strftime("%Y-%m-%d %H:%M:%S"), "vocab_size": tokenizer.get_vocab_size(), "context_length": MAX_SEQ_LEN, "total_train_samples": final_train_cnt, "total_val_samples": final_val_cnt, "total_train_tokens": total_train_toks, "total_val_tokens": total_val_toks, "domain_names": DOMAIN_MAP, "domain_counts": domain_counts }
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) print(f"\n📄 Saved metadata to {meta_path}")
print("\n" + "=" * 85) print(f"🎉 MASTER SFT v3 DATASET COMPLETED SUCCESSFULLY!") print(f" • Train Samples: {final_train_cnt:,} | Tokens: {total_train_toks:,}") print(f" • Val Samples: {final_val_cnt:,} | Tokens: {total_val_toks:,}") print(f" • Output Directory: {output_dir}") print("=" * 85)
if upload_to_hf: token = hf_token or os.environ.get("HF_TOKEN") if not token: print("⚠️ HF_TOKEN not found in environment or arguments. Skipping Hugging Face upload.") return
dataset_repo = "ViuAI/viuai-500m-sft-tokenized" subfolder = "sft_v3" print(f"\n🌐 Uploading sft_v3 shards to Hugging Face ({dataset_repo}/{subfolder})...") try: api = HfApi(token=token) for fname in [ "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" ]: fpath = os.path.join(output_dir, fname) if os.path.exists(fpath): print(f" ⬆️ Uploading {fname} ({os.path.getsize(fpath)/(1024*1024):.1f} MB)...") api.upload_file( path_or_fileobj=fpath, path_in_repo=f"{subfolder}/{fname}", repo_id=dataset_repo, repo_type="dataset" ) print(f"✅ Successfully uploaded Master SFT v3 Dataset to {dataset_repo}/{subfolder}!") except Exception as e: print(f"⚠️ Hugging Face upload failed: {e}")
if __name__ == "__main__": parser = argparse.ArgumentParser(description="Build Master SFT v3 Gold Dataset (~220,000 samples)") parser.add_argument("--root_dir", type=str, default=".", help="Root directory containing data/ and tokenizer/") parser.add_argument("--output_dir", type=str, default="tokenized_data/sft_v3", help="Output directory for .npy shards") parser.add_argument("--upload_to_hf", action="store_true", default=False, help="Upload shards to Hugging Face") parser.add_argument("--hf_token", type=str, default=None, help="Hugging Face API token") args = parser.parse_args()
build_dataset( root_dir=os.path.abspath(args.root_dir), output_dir=os.path.abspath(args.output_dir), upload_to_hf=args.upload_to_hf, hf_token=args.hf_token )code/build_master_sft_v3_dataset_4.pyAdded+427