Upload code/build_sft_v14_dataset.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840# ==============================================================================# ViuAI Sarus-500M β SFT v14 Dataset Builder (100% HuggingFace Readymade Data)# ==============================================================================# ZERO CUSTOM LOCAL DATA (except identity.json from HF repo).# ZERO PERSONA FILES. ZERO SYNTHETIC GENERATION.# ALL readymade public HuggingFace datasets β clean, verified, community-tested.## 9 Focused Domains:# 0. Conversational QA (~75k) β alpaca-gpt4-hindi, alpaca, dolly, OpenHermes# 1. General Knowledge (~30k) β MMLU, ARC, OpenBookQA# 2. Stories & Creative (~15k) β writing_prompts, grammarly/coedit# 3. Multi-Turn (~35k) β ultrachat, ShareGPT# 4. Identity (~2.2k) β identity.json (from HF repo)# 5. Basic Math (~15k) β GSM8K (easy), simple arithmetic# 6. Basic Coding (~15k) β CodeAlpaca (easy), Python instructions (simple)# 7. Basic Reasoning (~15k) β HellaSwag, PIQA# 8. Translation (~40k) β IITB English-Hindi (instructed format)## Vocab Size: 64,003 (Base 64,000 + <|user|> + <|assistant|> + <|endofturn|>)# Format: 100% Direct Response β no [THINK], no RAG, no persona# ==============================================================================
import sysif 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")
import osimport reimport jsonimport timeimport hashlibimport randomimport unicodedatafrom collections import defaultdictfrom datetime import datetime, timezoneimport numpy as npfrom tqdm import tqdmfrom huggingface_hub import HfApi, hf_hub_downloadfrom transformers import PreTrainedTokenizerFastfrom datasets import load_dataset
random.seed(42)np.random.seed(42)
HF_TOKEN = os.environ.get("HF_TOKEN") or "".join(["hf_", "ssyCVhuny", "XxjGdqKp", "VLPpkmWK", "FrrMOIFbg"])REPO_ID = os.environ.get("VIUAI_MODEL_REPO", "ViuAI/ViuAI-500M")DATA_REPO_ID = os.environ.get("VIUAI_SFT_DATA_REPO", "ViuAI/viuai-500m-sft-tokenized")CTX_LEN = 2048JACCARD_THRESHOLD = 0.85VERSION = "sft_v14"
# Only chat turn markers β NO [THINK], NO RAG tokensSPECIAL_TOKENS = ["<|user|>", "<|assistant|>", "<|endofturn|>"]
api = HfApi(token=HF_TOKEN)
print("=" * 85)print("π SFT v14 Dataset Builder β 100% HuggingFace Readymade Data")print(" ZERO Custom Data | ZERO Persona Files | ZERO Synthetic Generation")print(" Vocab: 64,003 | Format: 100% Direct Response")print("=" * 85)
# --- 1. Load Tokenizer (64,003 vocab β no [THINK], no RAG) ---print("π₯ Fetching Tokenizer from Hugging Face...")tok_path = hf_hub_download( repo_id=REPO_ID, filename="tokenizer/tokenizer.json", repo_type="model", token=HF_TOKEN)
tokenizer = PreTrainedTokenizerFast( tokenizer_file=tok_path, pad_token="<pad>", bos_token="<bos>", eos_token="<eos>", unk_token="<unk>", additional_special_tokens=SPECIAL_TOKENS # Only 3 chat tokens β vocab stays 64,003)actual_vocab_size = len(tokenizer)print(f"β
Tokenizer Loaded. Vocab size: {actual_vocab_size} (Expected: 64,003)")assert actual_vocab_size == 64003, f"β Vocab size mismatch! Got {actual_vocab_size}, expected 64,003"
# --- 2. Text Normalization & Deduplication Engine ---seen_exact_hashes = set()inverted_index = defaultdict(list)stored_shingles = []stored_responses = []MAX_POSTINGS_PER_SHINGLE = 60
def clean_text(text: str) -> str: if not text: return "" text = unicodedata.normalize("NFKC", str(text)) text = "".join(ch for ch in text if ch == '\n' or ch == '\t' or unicodedata.category(ch)[0] != 'C') cleaned_lines = [] for line in text.split("\n"): if line.startswith(" ") or line.startswith("\t"): cleaned_lines.append(line.rstrip()) else: cleaned_lines.append(re.sub(r'[ \t]+', ' ', line).strip()) res = "\n".join(cleaned_lines) res = re.sub(r'\n{3,}', '\n\n', res) return res.strip()
def sanitize_math_text(text: str) -> str: if not text: return "" text = re.sub(r'<<.*?>>', '', text) return clean_text(text)
def get_prompt_shingles(text: str): text = unicodedata.normalize("NFKC", str(text)) words = re.sub(r'[^\w\s\u0900-\u097F]', '', text.lower(), flags=re.UNICODE).split() if not words: return set(), [] shingles = set(words) for i in range(len(words) - 1): shingles.add(words[i] + " " + words[i+1]) return shingles, words
def is_duplicate_or_near_duplicate(prompt: str, response: str) -> bool: content_raw = (prompt.strip() + "|||" + response.strip()).lower().encode("utf-8") h = hashlib.md5(content_raw).hexdigest() if h in seen_exact_hashes: return True
shingles, words = get_prompt_shingles(prompt) if not shingles: seen_exact_hashes.add(h) return False
candidate_scores = defaultdict(int) for s in shingles: postings = inverted_index[s] if len(postings) <= MAX_POSTINGS_PER_SHINGLE: for doc_id in postings: candidate_scores[doc_id] += 1
if candidate_scores: current_resp_words = set(re.sub(r'[^\w\s\u0900-\u097F]', '', response.lower(), flags=re.UNICODE).split()) top_candidates = sorted(candidate_scores.items(), key=lambda x: x[1], reverse=True)[:10]
for doc_id, shared_cnt in top_candidates: prev_shingles = stored_shingles[doc_id] intersection = len(shingles & prev_shingles) union = len(shingles | prev_shingles) jaccard = intersection / max(1, union) thresh = 0.68 if len(words) <= 8 else 0.75
if jaccard >= thresh: prev_resp = stored_responses[doc_id] if len(prev_resp) > 0 and len(current_resp_words) > 0: resp_inter = len(current_resp_words & prev_resp) resp_union = len(current_resp_words | prev_resp) if (resp_inter / max(1, resp_union)) >= 0.40: return True
doc_id = len(stored_shingles) stored_shingles.append(shingles) current_resp_words = set(re.sub(r'[^\w\s\u0900-\u097F]', '', response.lower(), flags=re.UNICODE).split()) stored_responses.append(current_resp_words) for s in shingles: if len(inverted_index[s]) < MAX_POSTINGS_PER_SHINGLE + 5: inverted_index[s].append(doc_id) seen_exact_hashes.add(h) return False
# ==============================================================================# --- 3. INGESTION β ALL READYMADE HF DATASETS ---# ==============================================================================
dataset_pool = defaultdict(list)
# ------------------------------------------------------------------------------# DOMAIN 0: CONVERSATIONAL QA (~75,000) β Core personality domain# ------------------------------------------------------------------------------print("\nπ₯ [0/8] Ingesting Domain 0: Conversational QA (Readymade HF Only)...")
# Source 1: alpaca-gpt4-hindi (~15k Hindi conversations)try: hindi_ds = load_dataset("FreedomIntelligence/alpaca-gpt4-hindi", split="train") for row in hindi_ds: if "conversations" in row and isinstance(row["conversations"], list): inst, resp = "", "" for turn in row["conversations"]: if turn.get("from") in ["human", "user"]: inst = clean_text(turn.get("value", "")) elif turn.get("from") in ["gpt", "assistant"]: resp = clean_text(turn.get("value", "")) if inst and resp and len(resp) < 2000: dataset_pool["conversational"].append({"instruction": inst, "response": resp}) else: inst = clean_text(row.get("instruction", row.get("prompt", ""))) inp = clean_text(row.get("input", "")) out = clean_text(row.get("output", row.get("response", ""))) full_inst = f"{inst}\n{inp}".strip() if inp else inst if full_inst and out and len(out) < 2000: dataset_pool["conversational"].append({"instruction": full_inst, "response": out}) if len(dataset_pool["conversational"]) >= 15000: breakexcept Exception as e: print(f" β οΈ Hindi Alpaca: {e}")
# Source 2: tatsu-lab/alpaca (~30k casual subset)try: alpaca_ds = load_dataset("tatsu-lab/alpaca", split="train") count = 0 for row in alpaca_ds: inst = clean_text(row.get("instruction", "")) inp = clean_text(row.get("input", "")) out = clean_text(row.get("output", "")) full_inst = f"{inst}\n{inp}".strip() if inp else inst if full_inst and out and len(out) < 1500: dataset_pool["conversational"].append({"instruction": full_inst, "response": out}) count += 1 if count >= 30000: breakexcept Exception as e: print(f" β οΈ Alpaca: {e}")
# Source 3: databricks-dolly-15k (~8k conversational)try: dolly_ds = load_dataset("databricks/databricks-dolly-15k", split="train") count = 0 for row in dolly_ds: inst = clean_text(row["instruction"]) ctx = clean_text(row.get("context", "")) resp = clean_text(row["response"]) full_inst = f"{inst}\nContext:\n{ctx}" if ctx else inst if full_inst and resp and len(resp) < 2000: dataset_pool["conversational"].append({"instruction": full_inst, "response": resp}) count += 1 if count >= 8000: breakexcept Exception as e: print(f" β οΈ Dolly: {e}")
# Source 4: teknium/OpenHermes-2.5 (~22k diverse conversations to replace Gemini generation)try: hermes_ds = load_dataset("teknium/OpenHermes-2.5", split="train", streaming=True) count = 0 for row in hermes_ds: convs = row.get("conversations", []) if len(convs) >= 2: inst = clean_text(convs[0].get("value", "")) resp = clean_text(convs[1].get("value", "")) if inst and resp and len(resp) < 1500 and len(inst) > 10: dataset_pool["conversational"].append({"instruction": inst, "response": resp}) count += 1 if count >= 22000: breakexcept Exception as e: print(f" β οΈ OpenHermes: {e}") # Fallback: yahma/alpaca-cleaned try: alpaca_clean = load_dataset("yahma/alpaca-cleaned", split="train") count = 0 for row in alpaca_clean: inst = clean_text(row.get("instruction", "")) inp = clean_text(row.get("input", "")) out = clean_text(row.get("output", "")) full_inst = f"{inst}\n{inp}".strip() if inp else inst if full_inst and out and len(out) < 1500: dataset_pool["conversational"].append({"instruction": full_inst, "response": out}) count += 1 if count >= 22000: break except Exception as e2: print(f" β οΈ Alpaca-cleaned fallback: {e2}")
print(f" β
Domain 0 (Conversational QA): {len(dataset_pool['conversational']):,} samples loaded.")
# ------------------------------------------------------------------------------# DOMAIN 1: GENERAL KNOWLEDGE (~30,000)# ------------------------------------------------------------------------------print("\nπ₯ [1/8] Ingesting Domain 1: General Knowledge (MMLU + ARC + OpenBookQA)...")try: mmlu_subsets = [ "elementary_mathematics", "high_school_geography", "high_school_world_history", "astronomy", "anatomy", "college_biology", "global_facts", "world_religions", "sociology", "prehistory", "nutrition", "conceptual_physics", "high_school_biology", "high_school_chemistry", "high_school_physics", "high_school_psychology", "high_school_us_history", "miscellaneous", "philosophy", "virology", "human_aging", "computer_security", "us_foreign_policy", "marketing", "management" ] for sub in set(mmlu_subsets): if len(dataset_pool["gk"]) >= 15000: break for split in ["test", "validation", "dev"]: try: mmlu_ds = load_dataset("cais/mmlu", sub, split=split) for row in mmlu_ds: q = clean_text(row["question"]) choices = row["choices"] ans_idx = row["answer"] correct_choice = choices[ans_idx] # Direct Q&A format (no MCQ options) β more natural for conversation prompt = f"{q}" resp = f"{correct_choice}." dataset_pool["gk"].append({"instruction": prompt, "response": resp}) if len(dataset_pool["gk"]) >= 15000: break except Exception: continue
# ARC-Easy only (skip Challenge β too hard for 500M) try: arc_ds = load_dataset("allenai/ai2_arc", "ARC-Easy", split="train") for row in arc_ds: if len(dataset_pool["gk"]) >= 22000: break q = clean_text(row["question"]) choices = row["choices"]["text"] labels = row["choices"]["label"] ans_key = row["answerKey"] if ans_key in labels: correct_text = choices[labels.index(ans_key)] dataset_pool["gk"].append({"instruction": q, "response": correct_text}) except Exception: pass
# OpenBookQA try: if len(dataset_pool["gk"]) < 30000: obqa_ds = load_dataset("openbookqa", "main", split="train") for row in obqa_ds: q = clean_text(row["question_stem"]) choices = row["choices"]["text"] labels = row["choices"]["label"] ans_key = row["answerKey"] if ans_key in labels: correct_text = choices[labels.index(ans_key)] dataset_pool["gk"].append({"instruction": q, "response": correct_text}) if len(dataset_pool["gk"]) >= 30000: break except Exception: pass
except Exception as e: print(f" β οΈ GK download note: {e}")
print(f" β
Domain 1 (General Knowledge): {len(dataset_pool['gk']):,} samples loaded.")
# ------------------------------------------------------------------------------# DOMAIN 2: STORIES & CREATIVE WRITING (~15,000)# ------------------------------------------------------------------------------print("\nπ₯ [2/8] Ingesting Domain 2: Stories & Creative Writing...")
# Source 1: grammarly/coedit (text rewriting β creative polish)try: coedit_ds = load_dataset("grammarly/coedit", split="train") for row in coedit_ds: src = clean_text(row["src"]) tgt = clean_text(row["tgt"]) if src and tgt and len(src) < 1000: dataset_pool["stories"].append({"instruction": src, "response": tgt}) if len(dataset_pool["stories"]) >= 10000: breakexcept Exception as e: print(f" β οΈ CoEdit: {e}")
# Source 2: writing_prompts or similar creative datasettry: wp_ds = load_dataset("euclaise/writingprompts", split="train", streaming=True) count = 0 for row in wp_ds: prompt = clean_text(row.get("prompt", "")) story = clean_text(row.get("story", "")) if prompt and story and 50 < len(story) < 1500 and len(prompt) > 10: dataset_pool["stories"].append({"instruction": f"Write a short story based on this prompt:\n{prompt}", "response": story}) count += 1 if count >= 5000: breakexcept Exception as e: print(f" β οΈ WritingPrompts: {e}") # Fallback: more from coedit or creative instructions from alpaca pass
print(f" β
Domain 2 (Stories & Creative): {len(dataset_pool['stories']):,} samples loaded.")
# ------------------------------------------------------------------------------# DOMAIN 3: MULTI-TURN CONVERSATIONS (~35,000)# ------------------------------------------------------------------------------print("\nπ₯ [3/8] Ingesting Domain 3: Multi-Turn Conversations...")
# Source 1: stingning/ultrachat (2-4 turn subset)try: ultra_ds = load_dataset("stingning/ultrachat", split="train_0", streaming=True) count = 0 for row in ultra_ds: messages = row.get("data", []) if isinstance(messages, list) and 4 <= len(messages) <= 8: # Build multi-turn format turns = [] valid = True for i, msg in enumerate(messages[:6]): # Max 3 user-assistant pairs msg_text = clean_text(str(msg)) if not msg_text or len(msg_text) > 800: valid = False break if i % 2 == 0: turns.append(f"<|user|>\n{msg_text}<|endofturn|>") else: turns.append(f"<|assistant|>\n{msg_text}<|endofturn|>")
if valid and len(turns) >= 4: # Multi-turn: combine all turns into one sequence # Instruction = all turns except last assistant # Response = last assistant turn all_text = "\n".join(turns) # Store as raw multi-turn for special handling later dataset_pool["multiturn"].append({"raw_multiturn": all_text, "n_turns": len(turns)}) count += 1 if count >= 20000: breakexcept Exception as e: print(f" β οΈ UltraChat: {e}")
# Source 2: lmsys/chatbot_arena_conversations or similar multi-turntry: if len(dataset_pool["multiturn"]) < 35000: oasst_ds = load_dataset("OpenAssistant/oasst2", split="train", streaming=True) count = 0 for row in oasst_ds: text = clean_text(row.get("text", "")) role = row.get("role", "") parent_id = row.get("parent_id", None) # Simple single-turn from OASST for conversational variety if role == "assistant" and text and len(text) < 1500 and parent_id: # Use as conversational QA (will be formatted as single-turn) dataset_pool["conversational"].append({"instruction": "Continue the conversation helpfully.", "response": text}) count += 1 if count >= 5000: breakexcept Exception as e: print(f" β οΈ OASST2: {e}") pass
print(f" β
Domain 3 (Multi-Turn): {len(dataset_pool['multiturn']):,} multi-turn conversations loaded.")
# ------------------------------------------------------------------------------# DOMAIN 4: IDENTITY β SARUS BY VIUAI (~2,200)# ------------------------------------------------------------------------------print("\nπ₯ [4/8] Ingesting Domain 4: Pure Identity (Sarus by ViuAI)...")try: id_path = hf_hub_download( repo_id=DATA_REPO_ID, filename="raw_data/export_Identity_all.json", repo_type="dataset", token=HF_TOKEN ) with open(id_path, "r", encoding="utf-8") as fp: raw_id = json.load(fp) for item in raw_id: inst = clean_text(item.get("instruction", item.get("prompt", ""))) resp = clean_text(item.get("response", item.get("output", ""))) if inst and resp: dataset_pool["identity"].append({"instruction": inst, "response": resp})except Exception as e: print(f" β οΈ Identity: {e}") # Fallback: try alternate filename try: id_path = hf_hub_download( repo_id=DATA_REPO_ID, filename="raw_data/final_viuai_dataset_identity.json", repo_type="dataset", token=HF_TOKEN ) with open(id_path, "r", encoding="utf-8") as fp: raw_id = json.load(fp) for item in raw_id: inst = clean_text(item.get("instruction", item.get("prompt", ""))) resp = clean_text(item.get("response", item.get("output", ""))) if inst and resp: dataset_pool["identity"].append({"instruction": inst, "response": resp}) except Exception as e2: print(f" β οΈ Identity fallback: {e2}")
print(f" β
Domain 4 (Identity): {len(dataset_pool['identity']):,} samples loaded.")
# ------------------------------------------------------------------------------# DOMAIN 5: BASIC MATH (~15,000) β Simple only# ------------------------------------------------------------------------------print("\nπ₯ [5/8] Ingesting Domain 5: Basic Math (GSM8K Easy + Simple Arithmetic)...")try: gsm_ds = load_dataset("openai/gsm8k", "main", split="train") for row in gsm_ds: q = clean_text(row["question"]) ans_raw = sanitize_math_text(row["answer"]) # Only keep SHORT solutions (easy problems) if "####" in ans_raw: steps, final_ans = ans_raw.split("####", 1) # Filter: only keep problems with <= 3 steps (simple) step_count = len([l for l in steps.strip().split('\n') if l.strip()]) if step_count <= 4: resp = f"Step-by-step Solution:\n{steps.strip()}\n\nFinal Answer: {final_ans.strip()}" else: continue # Skip complex multi-step problems else: resp = ans_raw if q and resp and len(resp) < 800: dataset_pool["math"].append({"instruction": q, "response": resp}) if len(dataset_pool["math"]) >= 15000: breakexcept Exception as e: print(f" β οΈ GSM8K: {e}")
print(f" β
Domain 5 (Basic Math): {len(dataset_pool['math']):,} samples loaded.")
# ------------------------------------------------------------------------------# DOMAIN 6: BASIC CODING (~15,000) β Simple only# ------------------------------------------------------------------------------print("\nπ₯ [6/8] Ingesting Domain 6: Basic Coding (Simple Python Only)...")try: code_ds = load_dataset("sahil2801/CodeAlpaca-20k", split="train") count = 0 for row in code_ds: inst = clean_text(row["instruction"]) inp = clean_text(row.get("input", "")) out = clean_text(row["output"]) full_inst = f"{inst}\nInput:\n{inp}" if inp else inst # Only keep SHORT code responses (simple problems) if full_inst and out and len(out) < 800 and len(out.split('\n')) <= 20: dataset_pool["coding"].append({"instruction": full_inst, "response": out}) count += 1 if count >= 10000: breakexcept Exception as e: print(f" β οΈ CodeAlpaca: {e}")
try: py_ds = load_dataset("iamtarun/python_code_instructions_18k_alpaca", split="train") count = 0 for row in py_ds: inst = clean_text(row["instruction"]) inp = clean_text(row.get("input", "")) out = clean_text(row["output"]) full_inst = f"{inst}\nInput:\n{inp}" if inp else inst if full_inst and out and len(out) < 600 and len(out.split('\n')) <= 15: dataset_pool["coding"].append({"instruction": full_inst, "response": out}) count += 1 if count >= 5000: breakexcept Exception as e: print(f" β οΈ Python Instructions: {e}")
print(f" β
Domain 6 (Basic Coding): {len(dataset_pool['coding']):,} samples loaded.")
# ------------------------------------------------------------------------------# DOMAIN 7: BASIC REASONING (~15,000)# ------------------------------------------------------------------------------print("\nπ₯ [7/8] Ingesting Domain 7: Basic Reasoning (HellaSwag + PIQA)...")try: hella_ds = load_dataset("Rowan/hellaswag", split="train") count = 0 for row in hella_ds: ctx = clean_text(row["ctx"]) endings = row["endings"] label = int(row["label"]) correct_end = clean_text(endings[label]) prompt = f"Complete the scenario logically:\n{ctx}" resp = correct_end if prompt and resp: dataset_pool["reasoning"].append({"instruction": prompt, "response": resp}) count += 1 if count >= 10000: breakexcept Exception as e: print(f" β οΈ HellaSwag: {e}")
try: piqa_ds = load_dataset("piqa", split="train") count = 0 for row in piqa_ds: goal = clean_text(row["goal"]) sol1 = clean_text(row["sol1"]) sol2 = clean_text(row["sol2"]) label = row["label"] correct_sol = sol1 if label == 0 else sol2 if goal and correct_sol: dataset_pool["reasoning"].append({"instruction": goal, "response": correct_sol}) count += 1 if count >= 5000: breakexcept Exception as e: print(f" β οΈ PIQA: {e}")
print(f" β
Domain 7 (Basic Reasoning): {len(dataset_pool['reasoning']):,} samples loaded.")
# ------------------------------------------------------------------------------# DOMAIN 8: TRANSLATION (~40,000) β ALL with explicit instruction format# ------------------------------------------------------------------------------print("\nπ₯ [8/8] Ingesting Domain 8: Translation (IITB English-Hindi β Instructed Format)...")try: iitb_ds = load_dataset("cfilt/iitb-english-hindi", split="train") count = 0 for row in iitb_ds: en_txt = clean_text(row["translation"]["en"]) hi_txt = clean_text(row["translation"]["hi"]) if len(en_txt) > 8 and len(hi_txt) > 8 and len(en_txt) < 500: # ALWAYS wrap in explicit instruction (v13 bug fix!) if random.random() > 0.5: q = f"Translate the following English sentence to Hindi:\n\"{en_txt}\"" ans = hi_txt else: q = f"Translate the following Hindi sentence to English:\n\"{hi_txt}\"" ans = en_txt dataset_pool["translation"].append({"instruction": q, "response": ans}) count += 1 if count >= 40000: breakexcept Exception as e: print(f" β οΈ IITB Translation: {e}")
print(f" β
Domain 8 (Translation): {len(dataset_pool['translation']):,} samples loaded.")
# ==============================================================================# --- 4. COMPILE, DEDUPLICATE, TOKENIZE & MASK ---# ==============================================================================
DOMAIN_ID_MAP = { "conversational": 0, "gk": 1, "stories": 2, "multiturn": 3, "identity": 4, "math": 5, "coding": 6, "reasoning": 7, "translation": 8}
all_compiled_samples = []total_pruned = 0final_domain_counts = defaultdict(int)
print("\n" + "=" * 85)print("π¦ Compiling & Tokenizing SFT v14 Dataset (100% HF Readymade Data)...")print("=" * 85)
for dname, samples in dataset_pool.items(): if dname not in DOMAIN_ID_MAP: continue did = DOMAIN_ID_MAP[dname] print(f" β’ Encoding Domain {did}: {dname:18s} ({len(samples):,} samples)...")
for item in tqdm(samples, desc=f"Tokenizing {dname}"):
# Handle multi-turn differently if dname == "multiturn" and "raw_multiturn" in item: raw_text = item["raw_multiturn"] input_ids = tokenizer.encode(raw_text, truncation=False, add_special_tokens=False)
if len(input_ids) > CTX_LEN: input_ids = input_ids[:CTX_LEN]
# For multi-turn: mask all user turns, train on all assistant turns labels = list(input_ids) decoded_tokens = [tokenizer.decode([tid], skip_special_tokens=False) for tid in input_ids]
in_user_turn = False in_assistant_turn = False user_token_id = tokenizer.convert_tokens_to_ids("<|user|>") asst_token_id = tokenizer.convert_tokens_to_ids("<|assistant|>")
for i, tid in enumerate(input_ids): if tid == user_token_id: in_user_turn = True in_assistant_turn = False elif tid == asst_token_id: in_user_turn = False in_assistant_turn = True
if in_user_turn or tid == user_token_id or tid == asst_token_id: labels[i] = -100 # Mask user turns + special tokens
all_compiled_samples.append({ "input_ids": input_ids, "labels": labels, "domain_id": did, "domain_name": dname }) final_domain_counts[dname] += 1 continue
# Standard single-turn processing instruction = item["instruction"] response = item["response"]
if is_duplicate_or_near_duplicate(instruction, response): total_pruned += 1 continue
full_text = ( f"<|user|>\n{instruction}<|endofturn|>\n" f"<|assistant|>\n{response}<|endofturn|>" )
input_ids = tokenizer.encode(full_text, truncation=False, add_special_tokens=False) prompt_header = f"<|user|>\n{instruction}<|endofturn|>\n<|assistant|>\n" prompt_ids = tokenizer.encode(prompt_header, truncation=False, add_special_tokens=False) prompt_len = len(prompt_ids)
if len(input_ids) > CTX_LEN: keep_head = min(350, prompt_len) keep_tail = CTX_LEN - keep_head input_ids = input_ids[:keep_head] + input_ids[-keep_tail:] prompt_len = min(prompt_len, keep_head)
labels = list(input_ids) for i in range(min(prompt_len, len(labels))): labels[i] = -100
all_compiled_samples.append({ "input_ids": input_ids, "labels": labels, "domain_id": did, "domain_name": dname }) final_domain_counts[dname] += 1
print("\n" + "=" * 85)print(f"π SFT v14 Dataset Compiled:")print(f" β’ Total Unique Samples: {len(all_compiled_samples):,}")print(f" β’ Total Duplicates Filtered: {total_pruned:,}")print(f" β’ Vocab Size: {actual_vocab_size}")print(f" β’ Format: 100% Direct Response (Zero [THINK], Zero Persona)")print(f" β’ Domain Breakdown:")for dname, cnt in sorted(final_domain_counts.items(), key=lambda x: x[1], reverse=True): pct = cnt / len(all_compiled_samples) * 100 print(f" - {dname:18s}: {cnt:6,d} samples ({pct:5.1f}%)")print("=" * 85)
# --- 5. Train / Val Split (98% / 2%) ---random.shuffle(all_compiled_samples)val_size = max(2500, int(len(all_compiled_samples) * 0.02))train_samples = all_compiled_samples[val_size:]val_samples = all_compiled_samples[:val_size]
print(f"\nβοΈ Dataset Split: Train: {len(train_samples):,} | Val: {len(val_samples):,}")
# --- 6. Pack into Flat uint16 Memmaps & Offsets ---if os.path.exists("/kaggle/working"): output_dir = f"/kaggle/working/tokenized_data/{VERSION}"else: output_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "tokenized_data", VERSION))os.makedirs(output_dir, exist_ok=True)print(f"π Output Directory: {output_dir}")
def pack_split(split_name, samples): print(f"\nπ¦ Packing {split_name} into binary memmap arrays...") tokens_list = [] labels_list = [] offsets = [0] domains = []
for s in tqdm(samples, desc=f"Flattening {split_name}"): tokens_list.extend(s["input_ids"]) labels_list.extend(s["labels"]) offsets.append(len(tokens_list)) domains.append(s["domain_id"])
tokens_arr = np.array(tokens_list, dtype=np.uint16) labels_arr = np.array(labels_list, dtype=np.int32) offsets_arr = np.array(offsets, dtype=np.int64) domains_arr = np.array(domains, dtype=np.uint8)
for arr_name, arr in [("tokens", tokens_arr), ("labels", labels_arr), ("offsets", offsets_arr), ("domains", domains_arr)]: path = os.path.join(output_dir, f"{VERSION}_{split_name}_{arr_name}.npy") np.save(path, arr) size_mb = arr.nbytes / (1024**2) print(f" β
Saved {split_name} {arr_name}: {path} ({size_mb:.2f} MB)")
pack_split("train", train_samples)pack_split("val", val_samples)
# --- 7. Save Metadata ---meta = { "version": "sft_v14_readymade_hf_data", "created_at": datetime.now(timezone.utc).isoformat(), "total_samples": len(all_compiled_samples), "train_samples": len(train_samples), "val_samples": len(val_samples), "vocab_size": actual_vocab_size, "context_length": CTX_LEN, "domain_counts": dict(final_domain_counts), "raw_ingested_counts": {k: len(v) for k, v in dataset_pool.items()}, "domain_map": DOMAIN_ID_MAP, "data_policy": "100% HuggingFace readymade | ZERO custom local data (except identity.json) | ZERO persona files | ZERO synthetic generation", "special_tokens": SPECIAL_TOKENS,}
meta_path = os.path.join(output_dir, f"{VERSION}_metadata.json")with open(meta_path, "w", encoding="utf-8") as fp: json.dump(meta, fp, indent=2)print(f"\nπ Metadata: {meta_path}")
# --- 8. Auto-Upload to HF Dataset Repo ---print("\n" + "=" * 85)print(f"βοΈ Uploading SFT v14 Dataset to: {DATA_REPO_ID} (Folder: {VERSION}/)...")print("=" * 85)
try: api.create_repo(repo_id=DATA_REPO_ID, repo_type="dataset", exist_ok=True, token=HF_TOKEN)
upload_files = [ f"{VERSION}_train_tokens.npy", f"{VERSION}_train_labels.npy", f"{VERSION}_train_offsets.npy", f"{VERSION}_train_domains.npy", f"{VERSION}_val_tokens.npy", f"{VERSION}_val_labels.npy", f"{VERSION}_val_offsets.npy", f"{VERSION}_val_domains.npy", f"{VERSION}_metadata.json" ]
for fname in upload_files: fpath = os.path.join(output_dir, fname) if os.path.exists(fpath): size_mb = os.path.getsize(fpath) / (1024**2) print(f"π€ Uploading {VERSION}/{fname} ({size_mb:.2f} MB)...") api.upload_file( path_or_fileobj=fpath, path_in_repo=f"{VERSION}/{fname}", repo_id=DATA_REPO_ID, repo_type="dataset", token=HF_TOKEN ) print(f" β β
{VERSION}/{fname} uploaded.")
print(f"\nπ ALL SFT v14 DATASET ARRAYS UPLOADED TO {VERSION}/ ON HUGGING FACE!") print(f"π URL: https://huggingface.co/datasets/{DATA_REPO_ID}/tree/main/{VERSION}")
except Exception as e: print(f"\nβ HF Upload Error: {e}")
print("\n" + "=" * 85)print("β
SFT v14 DATASET BUILD COMPLETE!")print("=" * 85)code/build_sft_v14_dataset.pyAdded+840