Upload code/build_1m_sft_dataset.py with huggingface_hub
Browse files123456789101112131415161718192021221 unmodified line2425262728299 unmodified lines3940414243444535 unmodified lines8182838485868788894 unmodified lines94959697989910010110210310410510610710810911011111211311410 unmodified lines12512612712812913010 unmodified lines14114214314414514614712 unmodified lines1601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951 unmodified line19719819920020120220320420520620720820921021121221321421521621721821922022122222322417 unmodified lines2422432442452462472482492502512522532542552562572589 unmodified lines2682692702712722732742752763 unmodified lines2802812822832842852862872882892902913 unmodified lines29529629729829930030113 unmodified lines3153163173183193203213223233243253267 unmodified lines33433533633733833934034134234334414 unmodified lines35936036136236336436536636713 unmodified lines38138238338438538612 unmodified lines3994004014024034044054064074084094104114124134144154164174182 unmodified lines421422423424425426427428429# ==============================================================================# ๐ ViuAI Sarus-500M โ MASTER 1-MILLION (1M) SFT DATASET BUILDER & TOKENIZER# ==============================================================================# Packs exactly 1,000,000 high-purity instruction-response pairs into# memory-mapped shards (.npy) ready for code/train_sft.py.## 1,000,000 PAIR CURRICULUM ARCHITECTURE:# โข Pillar 1: STEM, Math & Reasoning (<thought> traces): 300,000 pairs# โข Pillar 2: Hinglish Daily Life & WhatsApp Conversations: 350,000 pairs# โข Pillar 3: English Multi-turn Dialogue (UltraChat & Dolly): 120,000 pairs# โข Pillar 4: English <-> Roman Hinglish Translation: 100,000 pairs# โข Pillar 5: Advanced Hinglish QA & Problem Solving (GPT-4): 100,000 pairs# โข Pillar 6: ViuAI Sarus Persona, Scam Safety & Greetings: 30,000 pairs# TOTAL: 1,000,000 PAIRS## Standards:# - 100% Roman Alphabet only (Strict Devanagari script rejection).# - User tokens masked to -100 (Loss active on <think>/<thought> + response).# - Memory-mapped offsets with [0, len1, len1+len2, ...].# ==============================================================================import os1 unmodified lineimport jsonimport reimport randomimport numpy as npfrom datasets import load_datasetfrom tokenizers import Tokenizer9 unmodified linesASSISTANT_TOKEN = "<|assistant|>"EOT_TOKEN = "<|endofturn|>"MAX_SEQ_LEN = 1024VAL_SPLIT_SAMPLES = 10000 # 10k validation samples, 990k train samplesMIN_RESPONSE_TOKENS = 4HF_TOKEN = os.environ.get("HF_TOKEN")35 unmodified linesreturn prompt_str, resp_strdef build_1m_dataset(target_total: int = 1_000_000):print("=" * 80)print(f"๐ ViuAI Sarus-500M โ Master 1-Million (1M) SFT Dataset Builder")print(f"๐ฏ Target Sample Count: {target_total:,} pairs")print("=" * 80)4 unmodified lineseot_id = tokenizer.token_to_id(EOT_TOKEN)os.makedirs(OUTPUT_DIR, exist_ok=True)# Shard targetst_stem = 300_000 # shreyansh12183/shreyansh-hinglish-english-stem-500kt_hinglish_chat = 350_000 # Abhishekcr448/Hinglish-Everyday-Conversations-1Mt_ultrachat = 120_000 # HuggingFaceH4/ultrachat_200kt_trans = 100_000 # findnitai/english-to-hinglisht_gpt4_hinglish = 100_000 # AashishKumar + arena + DSMJ910t_anchors = 30_000 # identity + greetings + local ncert/safetyprint(f"\n๐ Curriculum Allocation Plan:")print(f" 1. STEM & Math Reasoning (<thought>): {t_stem:,}")print(f" 2. Hinglish Everyday & WhatsApp Chat: {t_hinglish_chat:,}")print(f" 3. English Multi-Turn Dialogue (UltraChat): {t_ultrachat:,}")print(f" 4. English <-> Roman Hinglish Translation: {t_trans:,}")print(f" 5. Advanced Hinglish Dialogue (GPT-4/Arena):{t_gpt4_hinglish:,}")print(f" 6. ViuAI Sarus Identity, Safety & Greetings:{t_anchors:,}")print(f" -------------------------------------------------")print(f" TOTAL TARGET: {target_total:,} pairs\n")10 unmodified linesdef add_pair(prompt_str, resp_str, domain_id):nonlocal collectedp_ids = tokenizer.encode(prompt_str).idsr_ids = tokenizer.encode(resp_str).ids10 unmodified linessample_labels[-1] = eot_id# 10k validation split uniformly distributedis_val = (len(val_offsets) - 1 < VAL_SPLIT_SAMPLES) and (collected % 100 == 0)if is_val:val_tokens.extend(sample_tokens)12 unmodified linesreturn True# --------------------------------------------------------------------------# Pillar 6: ViuAI Sarus Identity & Greetings Anchors + Scam Safety (30k)# --------------------------------------------------------------------------print("๐น [1/6] Loading Identity, Greetings & Scam Safety Anchors...")id_p = os.path.join(BASE_DIR, "data", "sft_identity.json")gr_p = os.path.join(BASE_DIR, "data", "sft_greetings.json")p6_count = 0for path, did in [(id_p, 0), (gr_p, 1)]:if os.path.exists(path):with open(path, "r", encoding="utf-8") as f:data = json.load(f)for item in data:pair = format_qa(item.get("instruction", ""), item.get("response", ""))if pair:p, r = pairif add_pair(p, r, did):p6_count += 1# Local Safety & Logic from sft_v1_rawsafety_files = ["d10_antihallucination_trick_qa.jsonl","d17_finance_budgeting_scam_safety.jsonl","d20_commonsense_practical_logic.jsonl"]for sf in safety_files:p = os.path.join(BASE_DIR, "data", "sft_v1_raw", sf)if os.path.exists(p):with open(p, "r", encoding="utf-8") as f:for line in f:if p6_count >= t_anchors:breaktry:it = json.loads(line)1 unmodified lineif pair:p_str, r_str = pairif add_pair(p_str, r_str, 2):p6_count += 1except Exception:continueprint(f" โ Pillar 6 Ready: {p6_count:,} samples.")# --------------------------------------------------------------------------# Pillar 1: STEM & Math Reasoning (300,000)# --------------------------------------------------------------------------print("\n๐น [2/6] Streaming STEM & Math Reasoning with <thought> traces...")p1_count = 0try:ds_stem = load_dataset("shreyansh12183/shreyansh-hinglish-english-stem-500k",split="train",streaming=True,token=HF_TOKEN)for item in ds_stem:if p1_count >= t_stem:breaktxt = item.get("text", "")# Pattern: <|user|>\n{user}\n<|assistant|>\n<thought>\n{thought}\n</thought>\n\n{resp}if "<|user|>" in txt and "<|assistant|>" in txt:parts = txt.split("<|assistant|>")u_part = parts[0].replace("<|user|>", "").strip()17 unmodified linesprint(f" โ Pillar 1 Ready: {p1_count:,} samples.")# --------------------------------------------------------------------------# Pillar 2: Hinglish Everyday & WhatsApp Conversations (350,000)# --------------------------------------------------------------------------print("\n๐น [3/6] Streaming Hinglish Everyday Conversations...")p2_count = 0try:ds_chat = load_dataset("Abhishekcr448/Hinglish-Everyday-Conversations-1M",split="train",streaming=True,token=HF_TOKEN)for item in ds_chat:if p2_count >= t_hinglish_chat:break9 unmodified linesprint(f" โ Pillar 2 Ready: {p2_count:,} samples.")# --------------------------------------------------------------------------# Pillar 4: English <-> Roman Hinglish Translation (100,000)# --------------------------------------------------------------------------print("\n๐น [4/6] Streaming Bilingual Translation Dataset...")p4_count = 0trans_templates = ["Translate this into natural Roman Hinglish: \"{en}\"",3 unmodified lines"Isko English me convert karo: \"{hi}\""]try:ds_tr = load_dataset("findnitai/english-to-hinglish",split="train",streaming=True,token=HF_TOKEN)for item in ds_tr:if p4_count >= t_trans:break3 unmodified linesif not en or not hi:continue# Bidirectional pairingif random.random() < 0.7:tmpl = random.choice(trans_templates[:3])inst = tmpl.format(en=en)13 unmodified linesprint(f" โ Pillar 4 Ready: {p4_count:,} samples.")# --------------------------------------------------------------------------# Pillar 5: Advanced Hinglish QA & GPT-4 Conversations (100,000)# --------------------------------------------------------------------------print("\n๐น [5/6] Streaming Advanced Hinglish QA (GPT-4 / Arena / DSMJ910)...")p5_count = 0# DSMJ910/hinglish-instruct-10ktry:ds_dsm = load_dataset("DSMJ910/hinglish-instruct-10k", split="train", streaming=True, token=HF_TOKEN)for item in ds_dsm:7 unmodified linesexcept Exception as e:print(f" โ ๏ธ Warning loading DSMJ910: {e}")# AashishKumar/chatml-hinglish-conversation-gpt4try:ds_gpt4 = load_dataset("AashishKumar/chatml-hinglish-conversation-gpt4", split="train", streaming=True, token=HF_TOKEN)for item in ds_gpt4:if p5_count >= t_gpt4_hinglish:breakconvs_raw = item.get("conversations", "")try:14 unmodified linesprint(f" โ Pillar 5 Ready: {p5_count:,} samples.")# --------------------------------------------------------------------------# Pillar 3: English Multi-turn Dialogue (UltraChat 200k + Dolly) (120,000)# --------------------------------------------------------------------------print("\n๐น [6/6] Streaming English Multi-turn Dialogue (UltraChat 200k)...")p3_count = 0try:ds_uc = load_dataset("HuggingFaceH4/ultrachat_200k", split="train_sft", streaming=True, token=HF_TOKEN)13 unmodified linesprint(f" โ ๏ธ Warning loading UltraChat: {e}")print(f" โ Pillar 3 Ready: {p3_count:,} samples.")total_train = len(train_offsets) - 1total_val = len(val_offsets) - 1print("\n" + "=" * 80)12 unmodified linesnp.save(os.path.join(OUTPUT_DIR, "val_domains.npy"), np.array(val_domains, dtype=np.int32))metadata = {"dataset_name": "Sarus_SFT_1M_Master_Bilingual","total_samples": collected,"train_samples": total_train,"val_samples": total_val,"train_tokens": len(train_tokens),"val_tokens": len(val_tokens),"pillars": {"stem_math_thought": p1_count,"hinglish_everyday_chat": p2_count,"english_ultrachat": p3_count,"bilingual_translation": p4_count,"hinglish_gpt4_qa": p5_count,"identity_safety_greetings": p6_count},"max_seq_len": MAX_SEQ_LEN,"loss_masking": "User prompt masked to -100, active loss on <think> + response","language_gate": "100% Roman Alphabet (Zero Devanagari)"2 unmodified lineswith open(os.path.join(OUTPUT_DIR, "metadata.json"), "w", encoding="utf-8") as f:json.dump(metadata, f, indent=2)print("๐ 1-Million SFT Dataset Successfully Built and Tokenized!")print("=" * 80)if __name__ == "__main__":build_1m_dataset()1234567891011121314151617181920212223241 unmodified line262728293031329 unmodified lines4243444546474835 unmodified lines8485868788899091924 unmodified lines97989910010110210310410510610710810911011111211311411511611711811912012112210 unmodified lines13313413513613713813914014110 unmodified lines15215315415515615715812 unmodified lines1711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152161 unmodified line21821922022122222322422522622722822923023123223323423523623723823917 unmodified lines2572582592602612622632642652662672689 unmodified lines2782792802812822832842852863 unmodified lines2902912922932942952963 unmodified lines30030130230330430513 unmodified lines3193203213223233243253263273287 unmodified lines33633733833934034134234334434514 unmodified lines36036136236336436536636736813 unmodified lines38238338438538638738838939039139239339439539639739839940040140240340440540640740840941041112 unmodified lines4244254264274284294304314324334344352 unmodified lines438439440441442443444445446447448449# ==============================================================================# ๐ ViuAI Sarus-500M โ MASTER SFT DATASET BUILDER & TOKENIZER (1M - 1.5M Pairs)# ==============================================================================# Packs up to 1,500,000 high-purity instruction-response pairs into# memory-mapped shards (.npy) ready for code/train_sft.py.## 1,500,000 PAIR CURRICULUM ARCHITECTURE:# โข Pillar 1: STEM, Math & Reasoning (<thought> traces): 400,000 pairs# โข Pillar 2: Hinglish Daily Life & WhatsApp Conversations: 500,000 pairs# โข Pillar 3: English Multi-turn Dialogue (UltraChat & Dolly): 180,000 pairs# โข Pillar 4: English <-> Roman Hinglish Translation: 150,000 pairs# โข Pillar 5: Advanced Hinglish QA & Problem Solving (GPT-4): 70,000 pairs# โข Pillar 6: Curated SLM Instruction Tuning (SmolTalk): 100,000 pairs# โข Pillar 7: Indian Knowledge, NCERT, Typo & Scam Safety: 90,000 pairs# โข Pillar 8: ViuAI Sarus Persona, Identity & Greetings: 10,000 pairs# TOTAL: 1,500,000 PAIRS## Standards:# - 100% Roman Alphabet only (Strict Devanagari script rejection).# - User tokens masked to -100 (Loss active on <think>/<thought> + response).# - Single-Pass (1-Epoch) Paradigm: Max generalization, zero rote memorization.# ==============================================================================import os1 unmodified lineimport jsonimport reimport randomimport argparseimport numpy as npfrom datasets import load_datasetfrom tokenizers import Tokenizer9 unmodified linesASSISTANT_TOKEN = "<|assistant|>"EOT_TOKEN = "<|endofturn|>"MAX_SEQ_LEN = 1024VAL_SPLIT_SAMPLES = 10000 # 10k validation samplesMIN_RESPONSE_TOKENS = 4HF_TOKEN = os.environ.get("HF_TOKEN")35 unmodified linesreturn prompt_str, resp_strdef build_sft_dataset(target_total: int = 1_500_000):print("=" * 80)print(f"๐ ViuAI Sarus-500M โ Master SFT Dataset Builder")print(f"๐ฏ Target Sample Count: {target_total:,} pairs")print("=" * 80)4 unmodified lineseot_id = tokenizer.token_to_id(EOT_TOKEN)os.makedirs(OUTPUT_DIR, exist_ok=True)# Dynamic target scalingscale = target_total / 1_500_000t_stem = int(400_000 * scale)t_hinglish_chat = int(500_000 * scale)t_ultrachat = int(180_000 * scale)t_trans = int(150_000 * scale)t_gpt4 = int(70_000 * scale)t_smol = int(100_000 * scale)t_local_curated = int(90_000 * scale)t_anchors = int(10_000 * scale)print(f"\n๐ Curriculum Allocation Blueprint ({target_total:,} Total):")print(f" 1. STEM & Math Reasoning (<thought>): {t_stem:,}")print(f" 2. Hinglish Everyday & WhatsApp Chat: {t_hinglish_chat:,}")print(f" 3. English Multi-Turn Dialogue (UltraChat): {t_ultrachat:,}")print(f" 4. English <-> Roman Hinglish Translation: {t_trans:,}")print(f" 5. Advanced Hinglish Dialogue (GPT-4/Arena):{t_gpt4:,}")print(f" 6. Curated SLM Instruction Tuning (SmolTalk):{t_smol:,}")print(f" 7. Indian Knowledge, Typo & Scam Safety: {t_local_curated:,}")print(f" 8. ViuAI Sarus Identity, Safety & Greetings:{t_anchors:,}")print(f" -------------------------------------------------")print(f" TOTAL TARGET: {target_total:,} pairs\n")10 unmodified linesdef add_pair(prompt_str, resp_str, domain_id):nonlocal collectedif collected >= target_total:return Falsep_ids = tokenizer.encode(prompt_str).idsr_ids = tokenizer.encode(resp_str).ids10 unmodified linessample_labels[-1] = eot_id# 10k validation split uniformly distributedis_val = (len(val_offsets) - 1 < VAL_SPLIT_SAMPLES) and (collected % 150 == 0)if is_val:val_tokens.extend(sample_tokens)12 unmodified linesreturn True# --------------------------------------------------------------------------# Pillar 8: Identity & Cultural Greetings (10,000)# --------------------------------------------------------------------------print("๐น [1/8] Loading Identity & Greetings Anchors...")p8_count = 0id_p = os.path.join(BASE_DIR, "data", "sft_identity.json")gr_p = os.path.join(BASE_DIR, "data", "sft_greetings.json")for path, did in [(id_p, 0), (gr_p, 1)]:if os.path.exists(path):with open(path, "r", encoding="utf-8") as f:data = json.load(f)for item in data:if p8_count >= t_anchors:breakpair = format_qa(item.get("instruction", ""), item.get("response", ""))if pair:p, r = pairif add_pair(p, r, did):p8_count += 1print(f" โ Pillar 8 Ready: {p8_count:,} samples.")# --------------------------------------------------------------------------# Pillar 7: Indian Knowledge, NCERT, Typo & Scam Safety (90,000)# --------------------------------------------------------------------------print("\n๐น [2/8] Loading Indian Knowledge, Typo Robustness & Safety from local cache...")p7_count = 0curated_files = ["d6_typo_robustness_slangs.jsonl","d10_antihallucination_trick_qa.jsonl","d17_finance_budgeting_scam_safety.jsonl","d2_indian_history_affairs.jsonl","d1_ncert_curriculum.jsonl","d20_commonsense_practical_logic.jsonl"]for cf in curated_files:p = os.path.join(BASE_DIR, "data", "sft_v1_raw", cf)if os.path.exists(p):with open(p, "r", encoding="utf-8") as f:for line in f:if p7_count >= t_local_curated:breaktry:it = json.loads(line)1 unmodified lineif pair:p_str, r_str = pairif add_pair(p_str, r_str, 2):p7_count += 1except Exception:continueprint(f" โ Pillar 7 Ready: {p7_count:,} samples.")# --------------------------------------------------------------------------# Pillar 1: STEM & Math Reasoning (400,000)# --------------------------------------------------------------------------print("\n๐น [3/8] Streaming STEM & Math Reasoning with <thought> traces...")p1_count = 0try:ds_stem = load_dataset("shreyansh12183/shreyansh-hinglish-english-stem-500k", split="train", streaming=True, token=HF_TOKEN)for item in ds_stem:if p1_count >= t_stem:breaktxt = item.get("text", "")if "<|user|>" in txt and "<|assistant|>" in txt:parts = txt.split("<|assistant|>")u_part = parts[0].replace("<|user|>", "").strip()17 unmodified linesprint(f" โ Pillar 1 Ready: {p1_count:,} samples.")# --------------------------------------------------------------------------# Pillar 2: Hinglish Everyday & WhatsApp Conversations (500,000)# --------------------------------------------------------------------------print("\n๐น [4/8] Streaming Hinglish Everyday Conversations...")p2_count = 0try:ds_chat = load_dataset("Abhishekcr448/Hinglish-Everyday-Conversations-1M", split="train", streaming=True, token=HF_TOKEN)for item in ds_chat:if p2_count >= t_hinglish_chat:break9 unmodified linesprint(f" โ Pillar 2 Ready: {p2_count:,} samples.")# --------------------------------------------------------------------------# Pillar 4: English <-> Roman Hinglish Translation (150,000)# --------------------------------------------------------------------------print("\n๐น [5/8] Streaming Bilingual Translation Dataset...")p4_count = 0trans_templates = ["Translate this into natural Roman Hinglish: \"{en}\"",3 unmodified lines"Isko English me convert karo: \"{hi}\""]try:ds_tr = load_dataset("findnitai/english-to-hinglish", split="train", streaming=True, token=HF_TOKEN)for item in ds_tr:if p4_count >= t_trans:break3 unmodified linesif not en or not hi:continueif random.random() < 0.7:tmpl = random.choice(trans_templates[:3])inst = tmpl.format(en=en)13 unmodified linesprint(f" โ Pillar 4 Ready: {p4_count:,} samples.")# --------------------------------------------------------------------------# Pillar 5: Advanced Hinglish QA & GPT-4 Conversations (70,000)# --------------------------------------------------------------------------print("\n๐น [6/8] Streaming Advanced Hinglish QA (GPT-4 / Arena / DSMJ910)...")p5_count = 0try:ds_dsm = load_dataset("DSMJ910/hinglish-instruct-10k", split="train", streaming=True, token=HF_TOKEN)for item in ds_dsm:7 unmodified linesexcept Exception as e:print(f" โ ๏ธ Warning loading DSMJ910: {e}")try:ds_gpt4 = load_dataset("AashishKumar/chatml-hinglish-conversation-gpt4", split="train", streaming=True, token=HF_TOKEN)for item in ds_gpt4:if p5_count >= t_gpt4:breakconvs_raw = item.get("conversations", "")try:14 unmodified linesprint(f" โ Pillar 5 Ready: {p5_count:,} samples.")# --------------------------------------------------------------------------# Pillar 3: English Multi-turn Dialogue (UltraChat 200k) (180,000)# --------------------------------------------------------------------------print("\n๐น [7/8] Streaming English Multi-turn Dialogue (UltraChat 200k)...")p3_count = 0try:ds_uc = load_dataset("HuggingFaceH4/ultrachat_200k", split="train_sft", streaming=True, token=HF_TOKEN)13 unmodified linesprint(f" โ ๏ธ Warning loading UltraChat: {e}")print(f" โ Pillar 3 Ready: {p3_count:,} samples.")# --------------------------------------------------------------------------# Pillar 6: Curated SLM Instruction Tuning (SmolTalk) (100,000)# --------------------------------------------------------------------------if collected < target_total:print("\n๐น [8/8] Streaming SmolTalk Curated SLM Instruction Tuning...")p6_count = 0try:ds_smol = load_dataset("HuggingFaceTB/smoltalk", "all", split="train", streaming=True, token=HF_TOKEN)for item in ds_smol:if p6_count >= t_smol or collected >= target_total:breakmessages = item.get("messages", [])if len(messages) >= 2:u = messages[0].get("content", "")a = messages[1].get("content", "")pair = format_qa(u, a)if pair:p_str, r_str = pairif add_pair(p_str, r_str, 8):p6_count += 1except Exception as e:print(f" โ ๏ธ Warning loading SmolTalk: {e}")print(f" โ Pillar 6 Ready: {p6_count:,} samples.")total_train = len(train_offsets) - 1total_val = len(val_offsets) - 1print("\n" + "=" * 80)12 unmodified linesnp.save(os.path.join(OUTPUT_DIR, "val_domains.npy"), np.array(val_domains, dtype=np.int32))metadata = {"dataset_name": f"Sarus_SFT_{target_total//1000}k_Master_Bilingual","total_samples": collected,"train_samples": total_train,"val_samples": total_val,"train_tokens": len(train_tokens),"val_tokens": len(val_tokens),"max_seq_len": MAX_SEQ_LEN,"loss_masking": "User prompt masked to -100, active loss on <think> + response","language_gate": "100% Roman Alphabet (Zero Devanagari)"2 unmodified lineswith open(os.path.join(OUTPUT_DIR, "metadata.json"), "w", encoding="utf-8") as f:json.dump(metadata, f, indent=2)print(f"๐ {collected:,} SFT Dataset Successfully Built and Tokenized!")print("=" * 80)if __name__ == "__main__":parser = argparse.ArgumentParser()parser.add_argument("--target", type=int, default=1_500_000, help="Target total samples")args = parser.parse_args()build_sft_dataset(target_total=args.target)
code/build_1m_sft_dataset.py+102-82