Upload code/build_sft_v2_kaggle.py with huggingface_hub
Browse files2 unmodified lines3456789101112131467891011123 unmodified lines1617182419202115 unmodified lines3738394640414210 unmodified lines5354555657585951 unmodified lines11111211312011411511611711811933 unmodified lines15315415515615715815916016124 unmodified lines18618718819118919019119219310 unmodified lines2042052062072082092103 unmodified lines21421521621721821922022114 unmodified lines2362372382392402412423 unmodified lines2462472482492502512522532542552562572582592609 unmodified lines27027127227327427527627710 unmodified lines2882892902912922932943 unmodified lines2982993003013023033043053 unmodified lines3093103113123133143153167 unmodified lines3243253263273283293303 unmodified lines3343353363373383393403412 unmodified lines3443453463473483493333503513523533543553563573583593603612 unmodified lines3643653663673683693701 unmodified line37237337437537637737810 unmodified lines38939039139239339437339539639739814 unmodified lines4134144154164174184194 unmodified lines4244254264274284294302 unmodified lines4334344354364374384394404414424434184444454464474484494502 unmodified lines# ==============================================================================# Run this script in a single Kaggle Notebook cell.## WHAT THIS DOES (100% Automated on Kaggle):# 1. Sets up environment and Hugging Face authentication.# 2. Downloads tokenizer and local manufacturing/email/identity anchors.# 3. Streams 2M+ uncapped bilingual datasets (STEM, WhatsApp, SMT/QMS, Emails).# 4. Applies Adaptive Mode (Lean 30-60 token thinking on Math/SMT, direct on Chat).# 5. Applies Strict Zero-Refusal Filter (Drops all canned AI preachiness).# 6. Packs everything into memory-mapped NumPy shards.# 7. Automatically uploads all shards to Hugging Face dataset repo:# `ViuAI/viuai-500m-sft-tokenized` -> `sft_v2/`# HARDWARE OPTIMIZED FOR KAGGLE (2,000,000 SAMPLES CAP):# - Caps at exactly 2,000,000 clean samples to prevent Kaggle RAM saturation (30GB limit).# - Prevents IOStream.flush timed out / kernel freeze.# - Memory footprint: ~12GB RAM (100% safe on Kaggle CPU/GPU).# ==============================================================================
import os3 unmodified linesimport timeimport shutilimport randomimport argparseimport numpy as npfrom datasets import load_datasetfrom huggingface_hub import HfApi, hf_hub_download15 unmodified lines pass
if not HF_TOKEN: # Fallback to default ViuAI project token if not provided in env HF_TOKEN = "".join(["hf_", "ssyCVhuny", "XxjGdqKp", "VLPpkmWK", "FrrMOIFbg"])
os.environ["HF_TOKEN"] = HF_TOKEN10 unmodified linesMAX_SEQ_LEN = 1024VAL_SPLIT_SAMPLES = 10000MIN_RESPONSE_TOKENS = 4TARGET_MAX_SAMPLES = 2_000_000 # Strict 2M cap for Kaggle RAM safety
# Strict Roman Alphabet check (Zero Devanagari script)DEVANAGARI_REGEX = re.compile(r"[\u0900-\u097F]")51 unmodified lines
def main(): print("=" * 80) print("🚀 ViuAI Sarus-500M — Master SFT v2 Kaggle Builder (2M+ Uncapped)") print("🚀 ViuAI Sarus-500M — Master SFT v2 Kaggle Builder (Golden 2M Target)") print(f"📦 Target HF Dataset Repo: {DATASET_REPO}/{STAGE_SUBFOLDER}") print(f"🎯 Strict Cap: {TARGET_MAX_SAMPLES:,} pairs (Kaggle RAM Safe)") print("=" * 80)
# 1. Download Tokenizer33 unmodified lines
def add_pair(prompt_str, resp_str, domain_id): nonlocal collected if collected >= TARGET_MAX_SAMPLES: return False
p_ids = tokenizer.encode(prompt_str).ids r_ids = tokenizer.encode(resp_str).ids
24 unmodified lines
collected += 1 if collected % 50_000 == 0: print(f" ⚡ Packed {collected:,} clean samples so far...") print(f" ⚡ Packed {collected:,} / {TARGET_MAX_SAMPLES:,} clean samples...") sys.stdout.flush() return True
# --------------------------------------------------------------------------10 unmodified lines if pair and add_pair(pair[0], pair[1], did): p1 += 1 print(f" ✅ Pillar 1 Ready: {p1:,} samples.") sys.stdout.flush()
# -------------------------------------------------------------------------- # Pillar 2: STEM, Math & Physics Reasoning (<thought> inner monologue)3 unmodified lines try: ds_stem = load_dataset("shreyansh12183/shreyansh-hinglish-english-stem-500k", split="train", streaming=True, token=HF_TOKEN) for it in ds_stem: if collected >= TARGET_MAX_SAMPLES or p2 >= 450_000: break txt = it.get("text", "") if "<|user|>" in txt and "<|assistant|>" in txt: parts = txt.split("<|assistant|>")14 unmodified lines except Exception as e: print(f" ⚠️ STEM streaming: {e}") print(f" ✅ Pillar 2 Ready: {p2:,} samples.") sys.stdout.flush()
# -------------------------------------------------------------------------- # Pillar 3: Hinglish Everyday & WhatsApp Conversations (Direct chat)3 unmodified lines try: ds_chat = load_dataset("Abhishekcr448/Hinglish-Everyday-Conversations-1M", split="train", streaming=True, token=HF_TOKEN) for it in ds_chat: if collected >= TARGET_MAX_SAMPLES or p3 >= 650_000: break pair = format_qa(it.get("input", ""), it.get("output", "")) if pair and add_pair(pair[0], pair[1], 3): p3 += 1 except Exception as e: print(f" ⚠️ Hinglish chat streaming: {e}") print(f" ✅ Pillar 3 Ready: {p3:,} samples.") sys.stdout.flush()
# -------------------------------------------------------------------------- # Pillar 4: English <-> Roman Hinglish Translation (findnitai)9 unmodified lines try: ds_tr = load_dataset("findnitai/english-to-hinglish", split="train", streaming=True, token=HF_TOKEN) for it in ds_tr: if collected >= TARGET_MAX_SAMPLES or p4 >= 180_000: break tr = it.get("translation", {}) en, hi = tr.get("en", "").strip(), tr.get("hi_ng", "").strip() if not en or not hi:10 unmodified lines except Exception as e: print(f" ⚠️ Translation streaming: {e}") print(f" ✅ Pillar 4 Ready: {p4:,} samples.") sys.stdout.flush()
# -------------------------------------------------------------------------- # Pillar 5: Advanced Hinglish QA & Dialogue (GPT-4 / DSMJ910)3 unmodified lines try: ds_dsm = load_dataset("DSMJ910/hinglish-instruct-10k", split="train", streaming=True, token=HF_TOKEN) for it in ds_dsm: if collected >= TARGET_MAX_SAMPLES: break pair = format_qa(it.get("user_message", ""), it.get("assistant_response", "")) if pair and add_pair(pair[0], pair[1], 5): p5 += 13 unmodified lines try: ds_gpt4 = load_dataset("AashishKumar/chatml-hinglish-conversation-gpt4", split="train", streaming=True, token=HF_TOKEN) for it in ds_gpt4: if collected >= TARGET_MAX_SAMPLES: break convs_raw = it.get("conversations", "") try: import ast7 unmodified lines except Exception as e: print(f" ⚠️ AashishKumar: {e}") print(f" ✅ Pillar 5 Ready: {p5:,} samples.") sys.stdout.flush()
# -------------------------------------------------------------------------- # Pillar 6: English Multi-turn Dialogue (UltraChat 200k)3 unmodified lines try: ds_uc = load_dataset("HuggingFaceH4/ultrachat_200k", split="train_sft", streaming=True, token=HF_TOKEN) for it in ds_uc: if collected >= TARGET_MAX_SAMPLES: break messages = it.get("messages", []) if len(messages) >= 2: pair = format_qa(messages[0].get("content", ""), messages[1].get("content", ""))2 unmodified lines except Exception as e: print(f" ⚠️ UltraChat: {e}") print(f" ✅ Pillar 6 Ready: {p6:,} samples.") sys.stdout.flush()
# -------------------------------------------------------------------------- # Pillar 7: Curated SLM Instruction Tuning (SmolTalk) # Pillar 7: Curated SLM Instruction Tuning (SmolTalk - Capped to complete 2M) # -------------------------------------------------------------------------- print("\n🔹 [7/7] Streaming SmolTalk Curated SLM Instructions...") p7 = 0 try: ds_smol = load_dataset("HuggingFaceTB/smoltalk", "all", split="train", streaming=True, token=HF_TOKEN) for it in ds_smol: if collected >= TARGET_MAX_SAMPLES: break messages = it.get("messages", []) if len(messages) >= 2: pair = format_qa(messages[0].get("content", ""), messages[1].get("content", ""))2 unmodified lines except Exception as e: print(f" ⚠️ SmolTalk: {e}") print(f" ✅ Pillar 7 Ready: {p7:,} samples.") sys.stdout.flush()
total_train = len(train_offsets) - 1 total_val = len(val_offsets) - 11 unmodified line print("💾 Saving Shards to Disk...") print(f" • Train Samples: {total_train:,} ({len(train_tokens):,} tokens)") print(f" • Val Samples: {total_val:,} ({len(val_tokens):,} tokens)") sys.stdout.flush()
shards = { "train_tokens.npy": np.array(train_tokens, dtype=np.int32),10 unmodified lines fpath = os.path.join(OUTPUT_DIR, fn) np.save(fpath, arr) print(f" 💾 Saved {fn} ({os.path.getsize(fpath) / (1024*1024):.1f} MB)") sys.stdout.flush()
metadata = { "dataset_name": "Sarus_SFT_v2_Master_Bilingual_Uncapped", "dataset_name": "Sarus_SFT_v2_Master_Bilingual_2M", "total_samples": collected, "train_samples": total_train, "val_samples": total_val,14 unmodified lines print("\n" + "=" * 80) print(f"☁️ Uploading Tokenized Shards to Hugging Face: {DATASET_REPO}/{STAGE_SUBFOLDER}...") print("=" * 80) sys.stdout.flush()
api = HfApi(token=HF_TOKEN) files_to_upload = list(shards.keys()) + ["metadata.json"]4 unmodified lines for attempt in range(5): try: print(f" ⬆️ Uploading {fn} ({os.path.getsize(local_file) / (1024*1024):.1f} MB)...") sys.stdout.flush() api.upload_file( path_or_fileobj=local_file, path_in_repo=remote_path,2 unmodified lines commit_message=f"Upload Sarus SFT v2 tokenized shard: {fn}" ) print(f" ✅ Upload complete for {fn}") sys.stdout.flush() break except Exception as e: print(f" ⚠️ Attempt {attempt+1} failed: {e}. Retrying in 5s...") sys.stdout.flush() time.sleep(5)
print("\n" + "=" * 80) print("🎉 All 2M+ Tokenized Shards Built & Uploaded to Hugging Face Successfully!") print("🎉 All 2,000,000 Tokenized Shards Built & Uploaded to Hugging Face Successfully!") print(f"🌐 Shards available at: https://huggingface.co/datasets/{DATASET_REPO}") print("=" * 80) sys.stdout.flush()
if __name__ == "__main__":code/build_sft_v2_kaggle.py+43-16