Release ViuAI-40M: 32L UltraDeep (39.29M Total / 18.06M Active / 8192 Vocab)
Browse filesFiles changed (4)
3 unmodified lines456789101112133 unmodified lines"cell_type": "markdown","metadata": {},"source": ["# \ud83d\ude80 ViuAI-40M: Pure Chat + General Knowledge GPU Pipeline\n","### 32-Layer UltraDeep (39.29M Total / 18.06M Active) \u2022 65% English Chat + 15% General Knowledge + 20% Hinglish Chat\n","\n","**Note:** Hard coding and heavy math are automatically filtered out (`is_clean_chat_or_gk`), focusing 100% on friendly bilingual chat & everyday general knowledge.\n","\n","Pipeline Steps:\n","1. **GPU Setup** (Kaggle T4, RTX 3090, or RTX 4090)\n",3 unmodified lines456789101112133 unmodified lines"cell_type": "markdown","metadata": {},"source": ["# \ud83d\ude80 ViuAI-40M: Teacher-Distilled Chat + General Knowledge GPU Pipeline\n","### 32-Layer UltraDeep (39.29M Total / 18.06M Active) \u2022 Distilled EN Chat (65%) + GK (15%) + Hinglish Chat (20%)\n","\n","**Teacher-Distilled Data:** Uses GPT-4 / Qwen3 / Mixtral distilled `no_think` dialogues (SmolTalk2, SlimOrca, WildChat GPT-4, Cosmopedia WikiHow, Simple Wikipedia, NebulaByte Hinglish) + optional live Teacher Distiller (`scripts/distill_teacher_hinglish.py`).\n","\n","Pipeline Steps:\n","1. **GPU Setup** (Kaggle T4, RTX 3090, or RTX 4090)\n",
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132"""ViuAI-40M Live Teacher Distillation Generator (Hinglish Chat + General Knowledge).
Generates high-quality synthetic bilingual Hinglish + GK conversations using a strongTeacher LLM running locally on RTX 3090/4090 (e.g. Qwen/Qwen2.5-7B-Instruct).
Why Sequence-Level Distillation? Teacher models like Qwen2.5 (151k vocab) and ViuAI-40M (8,192 vocab) have different tokenizers, so sequence-level distillation (Teacher generates ultra-clean natural Hinglish multi-turn chats & GK answers -> ViuAI-40M trains on them) transfers frontier fluency directly into our compact 40M student model.
Usage (on RTX 3090/4090): python scripts/distill_teacher_hinglish.py --teacher Qwen/Qwen2.5-7B-Instruct --num_samples 25000"""
import argparseimport jsonimport osimport randomimport sysfrom typing import List, Dict
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.path.insert(0, project_root)
HINGLISH_TOPICS = [ "Daily life and morning routine advice in friendly Hinglish", "Simple Indian history or geography general knowledge explained casually in Hinglish", "Friendly motivation when feeling stressed about exams or work in Hinglish", "Simple science facts like how rain happens or why the sky is blue in Hinglish", "Casual conversation between two friends about movies, food, and weekend plans in Hinglish", "Everyday health, sleep, and fitness tips in simple Roman Hinglish", "Explaining famous monuments of India and world capitals in friendly Hinglish", "Polite and helpful customer-style or everyday assistant Q&A in Hinglish",]
DISTILL_SYSTEM_PROMPT = ( "You are a synthetic data generator creating natural, friendly, polite Hinglish " "(Hindi written in Roman English script mixed with simple English) multi-turn conversations. " "Do NOT write computer code or complex math. Output strictly valid JSON with a 'messages' list " "containing alternating 'user' and 'assistant' turns (2 to 4 turns total).")
def parse_json_conversation(text: str) -> Dict: """Extract clean {'messages': [...]} JSON from teacher output.""" start = text.find("{") end = text.rfind("}") if start == -1 or end == -1 or end <= start: return {} try: obj = json.loads(text[start : end + 1]) msgs = obj.get("messages", []) cleaned = [ {"role": m["role"], "content": m["content"].strip()} for m in msgs if m.get("role") in ("user", "assistant") and m.get("content", "").strip() ] if len(cleaned) >= 2: return {"messages": cleaned} except Exception: pass return {}
def main(): parser = argparse.ArgumentParser(description="Distill Hinglish Chat + GK from Teacher LLM") parser.add_argument("--teacher", type=str, default="Qwen/Qwen2.5-7B-Instruct") parser.add_argument("--num_samples", type=int, default=10000) parser.add_argument("--batch_size", type=int, default=8) parser.add_argument("--output", type=str, default="data/distilled_hinglish.jsonl") args = parser.parse_args()
import torch from transformers import AutoModelForCausalLM, AutoTokenizer
out_path = os.path.join(project_root, args.output) os.makedirs(os.path.dirname(out_path), exist_ok=True)
print(f"[*] Loading Teacher LLM: {args.teacher} ...") tok = AutoTokenizer.from_pretrained(args.teacher) if tok.pad_token_id is None: tok.pad_token_id = tok.eos_token_id tok.padding_side = "left"
model = AutoModelForCausalLM.from_pretrained( args.teacher, torch_dtype=torch.bfloat16 if torch.cuda.is_available() and torch.cuda.is_bf16_supported() else torch.float16, device_map="auto", ) model.eval()
generated_count = 0 with open(out_path, "a", encoding="utf-8") as f_out: while generated_count < args.num_samples: prompts = [] for _ in range(args.batch_size): topic = random.choice(HINGLISH_TOPICS) msgs = [ {"role": "system", "content": DISTILL_SYSTEM_PROMPT}, {"role": "user", "content": f"Generate one natural Hinglish chat conversation about: {topic}"}, ] prompts.append(tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True))
inputs = tok(prompts, return_tensors="pt", padding=True).to(model.device) with torch.no_grad(): outputs = model.generate( **inputs, max_new_tokens=320, temperature=0.85, top_p=0.92, do_sample=True, )
prompt_len = inputs["input_ids"].shape[1] for seq in outputs: reply = tok.decode(seq[prompt_len:], skip_special_tokens=True) conv = parse_json_conversation(reply) if conv: f_out.write(json.dumps(conv, ensure_ascii=False) + "\n") generated_count += 1
f_out.flush() if generated_count % 100 == 0: print(f" Distilled {generated_count:,}/{args.num_samples:,} Hinglish conversations...")
print(f"[DONE] Saved {generated_count:,} teacher-distilled Hinglish chats to {out_path}")
if __name__ == "__main__": main()12 unmodified lines1314151617181920212212 unmodified lines"cell_type": "markdown","metadata": {},"source": ["# 🚀 ViuAI-40M: Pure Chat + General Knowledge GPU Pipeline\n","### 32-Layer UltraDeep (39.29M Total / 18.06M Active) • 65% English Chat + 15% General Knowledge + 20% Hinglish Chat\n","\n","**Note:** Hard coding and heavy math are automatically filtered out (`is_clean_chat_or_gk`), focusing 100% on friendly bilingual chat & everyday general knowledge.\n","\n","Pipeline Steps:\n","1. **GPU Setup** (Kaggle T4, RTX 3090, or RTX 4090)\n",12 unmodified lines1314151617181920212212 unmodified lines"cell_type": "markdown","metadata": {},"source": ["# 🚀 ViuAI-40M: Teacher-Distilled Chat + General Knowledge GPU Pipeline\n","### 32-Layer UltraDeep (39.29M Total / 18.06M Active) • Distilled EN Chat (65%) + GK (15%) + Hinglish Chat (20%)\n","\n","**Teacher-Distilled Data:** Uses GPT-4 / Qwen3 / Mixtral distilled `no_think` dialogues (SmolTalk2, SlimOrca, WildChat GPT-4, Cosmopedia WikiHow, Simple Wikipedia, NebulaByte Hinglish) + optional live Teacher Distiller (`scripts/distill_teacher_hinglish.py`).\n","\n","Pipeline Steps:\n","1. **GPU Setup** (Kaggle T4, RTX 3090, or RTX 4090)\n",
123456789101112131415161718192021222324255 unmodified lines3132333435363738394041424344457 unmodified lines53545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081093 unmodified lines1131141151161171181191201211221231241251261271281291301312 unmodified lines1341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701715 unmodified lines1771781791801811821837 unmodified lines1911921931941951961971981992002012022032042052062072082096 unmodified lines21621721821922022122222322422522622722822923023123223311 unmodified lines2452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742754 unmodified lines28028128228328428528628753 unmodified lines341342343344345346347"""ViuAI-40M 5B-Token Pure Chat + General Knowledge Memmap Builder.Combines 3 verified pillars (with hard-coding & math filtered out):1. Pure English Chat (~65%): WildChat-4.8M (non-code), SmolTalk everyday-conversations,EmpatheticDialogues, UltraChat (non-code)2. General Knowledge (~15%): Simple English Wikipedia (20231101.simple),Cosmopedia WikiHow (practical everyday life how-to), Databricks Dolly-15k3. Pure Hinglish Chat (~20%, replay-capped): Abhishekcr448/Hinglish-Everyday-Conversations-1M,DSMJ910/hinglish-instruct-10k, Sujalvc/hinglish-instruct-dataset, NebulaByte HinglishOutputs zero-RAM `uint16` memory-mapped `.bin` files:data/train.bindata/val.binoutput/tokenizer/ (8,192 lossless case-preserving BPE)Usage:python scripts/prepare_5b_chat_gk_memmap.py --target_tokens 5000000000python scripts/prepare_5b_chat_gk_memmap.py --target_tokens 1000000000 # 1B quick run"""import argparseimport osimport reimport sys5 unmodified linesfrom viuai.tokenizer.bpe_tokenizer import ViuAITokenizer# Filter out heavy coding, SQL, HTML, and LaTeX mathCODE_MATH_RE = re.compile(r"(```|\bdef\s+\w+\(|\bclass\s+\w+[:\(]|\bimport\s+\w+|#include\s*<|SELECT\s+.+\s+FROM|\\frac\{|\\sum_|<html>|function\s*\()",re.IGNORECASE,)def is_clean_chat_or_gk(messages: List[Dict[str, str]]) -> bool:"""Reject empty turns or heavy coding/math blocks so model focuses on chat + GK."""if not messages or len(messages) < 2:return Falsetotal_len = 07 unmodified linesreturn 10 <= total_len <= 8000def stream_english_pure_chat() -> Generator[List[Dict[str, str]], None, None]:from datasets import load_dataset# 1. SmolTalk everyday-conversationstry:ds = load_dataset("HuggingFaceTB/smoltalk", "everyday-conversations", split="train", streaming=True)for row in ds:msgs = [{"role": m["role"], "content": m["content"].strip()} for m in row.get("messages", []) if m.get("role") in ("user", "assistant")]if is_clean_chat_or_gk(msgs):yield msgsexcept Exception as e:print(f"[SmolTalk everyday note]: {e}")# 2. Empathetic Dialoguestry:ds = load_dataset("Estwld/empathetic_dialogues_llm", split="train", streaming=True)for row in ds:convs = row.get("conversations", [])msgs = []for turn in convs:role = "user" if turn.get("role") in ("user", "human") else "assistant"content = turn.get("content", "").strip()if content:msgs.append({"role": role, "content": content})if is_clean_chat_or_gk(msgs):yield msgsexcept Exception as e:print(f"[EmpatheticDialogues note]: {e}")# 3. UltraChat 200k (filtered)try:ds = load_dataset("HuggingFaceH4/ultrachat_200k", split="train_sft", streaming=True)for row in ds:msgs = [{"role": m["role"], "content": m["content"].strip()} for m in row.get("messages", []) if m.get("role") in ("user", "assistant")]if is_clean_chat_or_gk(msgs):yield msgsexcept Exception as e:print(f"[UltraChat note]: {e}")# 4. WildChat-4.8M (English only, non-toxic, no code)try:ds = load_dataset("allenai/WildChat-4.8M", split="train", streaming=True)for row in ds:if row.get("language") != "English" or row.get("toxic", False):continuemsgs = []for turn in row.get("conversation", []):role = "user" if turn.get("role") == "user" else "assistant"content = turn.get("content", "").strip()if content:msgs.append({"role": role, "content": content})if is_clean_chat_or_gk(msgs):yield msgsexcept Exception as e:3 unmodified linesdef stream_general_knowledge() -> Generator[List[Dict[str, str]], None, None]:from datasets import load_dataset# 1. Dolly-15k (GK + QA)try:ds = load_dataset("databricks/databricks-dolly-15k", split="train", streaming=True)for row in ds:ins = row.get("instruction", "").strip()ctx = row.get("context", "").strip()resp = row.get("response", "").strip()user_text = f"{ins}\n\n{ctx}" if ctx else insmsgs = [{"role": "user", "content": user_text}, {"role": "assistant", "content": resp}]if is_clean_chat_or_gk(msgs):yield msgsexcept Exception as e:print(f"[Dolly note]: {e}")# 2. Simple English Wikipedia (World Facts, History, Science, Geography)try:2 unmodified linestitle = row.get("title", "").strip()text = row.get("text", "").strip()[:2500]if title and len(text) > 80:msgs = [{"role": "user", "content": f"Tell me about {title}."},{"role": "assistant", "content": text},]if is_clean_chat_or_gk(msgs):yield msgsexcept Exception as e:print(f"[SimpleWiki note]: {e}")# 3. Cosmopedia WikiHow (Practical Everyday Knowledge)try:ds = load_dataset("HuggingFaceTB/cosmopedia", "wikihow", split="train", streaming=True)for row in ds:prompt = row.get("prompt", "").strip()text = row.get("text", "").strip()[:2500]if prompt and len(text) > 80:msgs = [{"role": "user", "content": prompt},{"role": "assistant", "content": text},]if is_clean_chat_or_gk(msgs):yield msgsexcept Exception as e:print(f"[WikiHow note]: {e}")def stream_hinglish_chat(max_repeats: int = 8) -> Generator[List[Dict[str, str]], None, None]:"""Stream Hinglish chat with safe epoch cap to avoid verbatim overfitting."""from datasets import load_datasetfor epoch in range(max_repeats):# 1. DSMJ910 Friendly Hinglish Persona Chatstry:ds = load_dataset("DSMJ910/hinglish-instruct-10k", split="train", streaming=True)for row in ds:5 unmodified linesexcept Exception as e:print(f"[DSMJ910 note]: {e}")# 2. Sujalvc Hinglish Instructtry:ds = load_dataset("Sujalvc/hinglish-instruct-dataset", split="train", streaming=True)for row in ds:7 unmodified linesexcept Exception as e:print(f"[Sujalvc note]: {e}")# 3. NebulaByte Alpaca Hinglishtry:ds = load_dataset("NebulaByte/alpaca-gpt4-hindi-hinglish", split="train", streaming=True)for row in ds:u = row.get("input_hinglish", "").strip()a = row.get("output_hinglish", "").strip()msgs = [{"role": "user", "content": u}, {"role": "assistant", "content": a}]if is_clean_chat_or_gk(msgs):yield msgsexcept Exception as e:print(f"[NebulaByte note]: {e}")# 4. Abhishekcr448 Hinglish Everyday Conversations 1Mtry:ds = load_dataset("Abhishekcr448/Hinglish-Everyday-Conversations-1M", split="train", streaming=True)for row in ds:6 unmodified linesprint(f"[Hinglish-1M note]: {e}")def build_balanced_tokenizer(output_dir: str, vocab_size: int = 8192) -> ViuAITokenizer:"""Train a bilingual 8,192 BPE tokenizer on a balanced sample of Chat + GK + Hinglish."""tok_dir = os.path.join(output_dir, "tokenizer")if os.path.exists(os.path.join(tok_dir, "vocab.json")):return ViuAITokenizer.load(tok_dir)print("[1/2] Collecting balanced sample for 8,192 BPE tokenizer training...")corpus_lines: List[str] = []for gen, limit in [(stream_english_pure_chat(), 15000),(stream_hinglish_chat(max_repeats=1), 15000),(stream_general_knowledge(), 8000),]:count = 011 unmodified linesdef main():parser = argparse.ArgumentParser(description="Build 5B Chat + GK Memmap Dataset for ViuAI-40M")parser.add_argument("--target_tokens", type=int, default=5_000_000_000,help="Total tokens to write (default: 5,000,000,000)")parser.add_argument("--vocab_size", type=int, default=8192)parser.add_argument("--data_dir", type=str, default="data")parser.add_argument("--output_dir", type=str, default="output")parser.add_argument("--val_ratio", type=float, default=0.01)args = parser.parse_args()data_dir = os.path.join(project_root, args.data_dir)output_dir = os.path.join(project_root, args.output_dir)os.makedirs(data_dir, exist_ok=True)os.makedirs(output_dir, exist_ok=True)tokenizer = build_balanced_tokenizer(output_dir, vocab_size=args.vocab_size)train_bin = os.path.join(data_dir, "train.bin")val_bin = os.path.join(data_dir, "val.bin")print(f"\n[2/2] Streaming up to {args.target_tokens:,} tokens (65% EN Chat | 15% GK | 20% Hinglish Chat)...")en_gen = stream_english_pure_chat()gk_gen = stream_general_knowledge()hi_gen = stream_hinglish_chat(max_repeats=8)# Token-level mixture budgetsrng = np.random.default_rng(42)train_buf: List[int] = []val_buf: List[int] = []4 unmodified lineswith open(train_bin, "wb") as f_tr, open(val_bin, "wb") as f_val:while total_tokens < args.target_tokens:# Token-budget weighted sampling: pick whichever stream is most behind its target shareen_ratio = en_toks / max(1, total_tokens)gk_ratio = gk_toks / max(1, total_tokens)hi_ratio = hi_toks / max(1, total_tokens)53 unmodified linesif val_buf:np.array(val_buf, dtype=np.uint16).tofile(f_val)print(f"\n[DONE] Built {total_tokens:,} tokens -> {train_bin} & {val_bin}")if __name__ == "__main__":12345678910111213141516171819202122232425262728293031325 unmodified lines3839404142434445464748495051527 unmodified lines606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311323 unmodified lines1361371381391401411421431441451461471481491501511521532 unmodified lines1561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162175 unmodified lines2232242252262272282297 unmodified lines2372382392402412422436 unmodified lines25025125225325425525625725825926026126226326426526626726826927011 unmodified lines2822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113124 unmodified lines31731831932032132253 unmodified lines376377378379380381382"""ViuAI-40M 5B-Token Teacher-Distilled Chat + General Knowledge Memmap Builder.Uses frontier teacher-distilled datasets (zero `<think>` bloat, hard coding & math filtered out):1. Distilled English Chat (~65%):- HuggingFaceTB/smoltalk2 (SFT `no_think` splits: everyday_conversations, smol_magpie_ultra,systemchats_30k, smol_rewrite, smol_summarize)- Open-Orca/SlimOrca (518k GPT-4 curated chats)- allenai/WildChat-4.8M (GPT-4 / GPT-4o non-toxic English chats)- Estwld/empathetic_dialogues_llm (emotional & friendly chat)2. Distilled General Knowledge (~15%):- HuggingFaceTB/cosmopedia (wikihow — Mixtral-8x7B distilled everyday knowledge)- wikimedia/wikipedia (20231101.simple — Simple English Wikipedia GK)- databricks/databricks-dolly-15k3. Distilled Hinglish Chat + GK (~20%, replay-capped):- Local `data/distilled_hinglish.jsonl` (if generated via `distill_teacher_hinglish.py`)- NebulaByte/alpaca-gpt4-hindi-hinglish (GPT-4 distilled Hinglish)- DSMJ910/hinglish-instruct-10k (LLM distilled persona Hinglish)- Sujalvc/hinglish-instruct-dataset (LLM distilled Hinglish)- Abhishekcr448/Hinglish-Everyday-Conversations-1MOutputs zero-RAM `uint16` memory-mapped `.bin` files:data/train.bindata/val.binoutput/tokenizer/ (8,192 lossless case-preserving BPE)"""import argparseimport jsonimport osimport reimport sys5 unmodified linesfrom viuai.tokenizer.bpe_tokenizer import ViuAITokenizer# Reject heavy coding, SQL, HTML, LaTeX math, or <think> chainsCODE_MATH_RE = re.compile(r"(```|\bdef\s+\w+\(|\bclass\s+\w+[:\(]|\bimport\s+\w+|#include\s*<|SELECT\s+.+\s+FROM|\\frac\{|\\sum_|<html>|function\s*\(|<think>)",re.IGNORECASE,)def is_clean_chat_or_gk(messages: List[Dict[str, str]]) -> bool:"""Reject empty turns, <think> traces, or heavy coding/math blocks."""if not messages or len(messages) < 2:return Falsetotal_len = 07 unmodified linesreturn 10 <= total_len <= 8000def _clean_messages(raw_msgs: List[Dict[str, str]]) -> List[Dict[str, str]]:"""Normalize role names and keep clean user/assistant pairs."""cleaned = []for m in raw_msgs:role = m.get("role") or m.get("from", "")content = (m.get("content") or m.get("value") or "").strip()if not content:continueif role in ("user", "human"):cleaned.append({"role": "user", "content": content})elif role in ("assistant", "gpt"):cleaned.append({"role": "assistant", "content": content})return cleaneddef stream_distilled_english_chat() -> Generator[List[Dict[str, str]], None, None]:from datasets import load_dataset# 1. SmolTalk2 clean `no_think` teacher-distilled SFT splitssmoltalk2_splits = ["smoltalk_smollm3_everyday_conversations_no_think","smoltalk_smollm3_smol_magpie_ultra_no_think","smoltalk_smollm3_systemchats_30k_no_think","smoltalk_smollm3_smol_rewrite_no_think","smoltalk_smollm3_smol_summarize_no_think","OpenHermes_2.5_no_think",]for sp in smoltalk2_splits:try:ds = load_dataset("HuggingFaceTB/smoltalk2", "SFT", split=sp, streaming=True)for row in ds:msgs = _clean_messages(row.get("messages", []))if is_clean_chat_or_gk(msgs):yield msgsexcept Exception as e:print(f"[SmolTalk2 {sp} note]: {e}")# 2. Open-Orca/SlimOrca (GPT-4 distilled)try:ds = load_dataset("Open-Orca/SlimOrca", split="train", streaming=True)for row in ds:msgs = _clean_messages(row.get("conversations", []))if is_clean_chat_or_gk(msgs):yield msgsexcept Exception as e:print(f"[SlimOrca note]: {e}")# 3. Empathetic Dialoguestry:ds = load_dataset("Estwld/empathetic_dialogues_llm", split="train", streaming=True)for row in ds:msgs = _clean_messages(row.get("conversations", []))if is_clean_chat_or_gk(msgs):yield msgsexcept Exception as e:print(f"[EmpatheticDialogues note]: {e}")# 4. WildChat-4.8M (Prioritize GPT-4 teacher English conversations)try:ds = load_dataset("allenai/WildChat-4.8M", split="train", streaming=True)for row in ds:if row.get("language") != "English" or row.get("toxic", False):continuemodel_name = str(row.get("model", "")).lower()if "gpt-4" not in model_name:continuemsgs = _clean_messages(row.get("conversation", []))if is_clean_chat_or_gk(msgs):yield msgsexcept Exception as e:3 unmodified linesdef stream_general_knowledge() -> Generator[List[Dict[str, str]], None, None]:from datasets import load_dataset# 1. Cosmopedia WikiHow (Mixtral-8x7B distilled practical GK)try:ds = load_dataset("HuggingFaceTB/cosmopedia", "wikihow", split="train", streaming=True)for row in ds:prompt = row.get("prompt", "").strip()text = row.get("text", "").strip()[:2500]if prompt and len(text) > 80:msgs = [{"role": "user", "content": prompt}, {"role": "assistant", "content": text}]if is_clean_chat_or_gk(msgs):yield msgsexcept Exception as e:print(f"[Cosmopedia WikiHow note]: {e}")# 2. Simple English Wikipedia (World Facts, History, Science, Geography)try:2 unmodified linestitle = row.get("title", "").strip()text = row.get("text", "").strip()[:2500]if title and len(text) > 80:msgs = [{"role": "user", "content": f"Tell me about {title}."}, {"role": "assistant", "content": text}]if is_clean_chat_or_gk(msgs):yield msgsexcept Exception as e:print(f"[SimpleWiki note]: {e}")# 3. Dolly-15ktry:ds = load_dataset("databricks/databricks-dolly-15k", split="train", streaming=True)for row in ds:ins = row.get("instruction", "").strip()ctx = row.get("context", "").strip()resp = row.get("response", "").strip()u = f"{ins}\n\n{ctx}" if ctx else insmsgs = [{"role": "user", "content": u}, {"role": "assistant", "content": resp}]if is_clean_chat_or_gk(msgs):yield msgsexcept Exception as e:print(f"[Dolly note]: {e}")def stream_distilled_hinglish(local_distilled_path: str,max_repeats: int = 8,) -> Generator[List[Dict[str, str]], None, None]:"""Stream local teacher-distilled Hinglish JSONL + public Hinglish datasets."""from datasets import load_datasetfor _ in range(max_repeats):# 0. Locally generated high-quality Teacher-Distilled Hinglish + GK JSONL (if present)if os.path.exists(local_distilled_path):with open(local_distilled_path, "r", encoding="utf-8") as f:for line in f:line = line.strip()if not line:continuetry:msgs = _clean_messages(json.loads(line).get("messages", []))if is_clean_chat_or_gk(msgs):yield msgsexcept json.JSONDecodeError:continue# 1. GPT-4 Distilled Hinglish (NebulaByte)try:ds = load_dataset("NebulaByte/alpaca-gpt4-hindi-hinglish", split="train", streaming=True)for row in ds:u = row.get("input_hinglish", "").strip()a = row.get("output_hinglish", "").strip()msgs = [{"role": "user", "content": u}, {"role": "assistant", "content": a}]if is_clean_chat_or_gk(msgs):yield msgsexcept Exception as e:print(f"[NebulaByte note]: {e}")# 2. DSMJ910 Hinglish Persona Chatstry:ds = load_dataset("DSMJ910/hinglish-instruct-10k", split="train", streaming=True)for row in ds:5 unmodified linesexcept Exception as e:print(f"[DSMJ910 note]: {e}")# 3. Sujalvc Hinglish Instructtry:ds = load_dataset("Sujalvc/hinglish-instruct-dataset", split="train", streaming=True)for row in ds:7 unmodified linesexcept Exception as e:print(f"[Sujalvc note]: {e}")# 4. Everyday Hinglish 1Mtry:ds = load_dataset("Abhishekcr448/Hinglish-Everyday-Conversations-1M", split="train", streaming=True)for row in ds:6 unmodified linesprint(f"[Hinglish-1M note]: {e}")def build_balanced_tokenizer(output_dir: str,local_distilled_path: str,vocab_size: int = 8192,) -> ViuAITokenizer:tok_dir = os.path.join(output_dir, "tokenizer")if os.path.exists(os.path.join(tok_dir, "vocab.json")):return ViuAITokenizer.load(tok_dir)print("[1/2] Collecting teacher-distilled sample for 8,192 BPE tokenizer...")corpus_lines: List[str] = []for gen, limit in [(stream_distilled_english_chat(), 15000),(stream_distilled_hinglish(local_distilled_path, max_repeats=1), 15000),(stream_general_knowledge(), 8000),]:count = 011 unmodified linesdef main():parser = argparse.ArgumentParser(description="Build Teacher-Distilled 5B Chat+GK Memmap Dataset")parser.add_argument("--target_tokens", type=int, default=5_000_000_000)parser.add_argument("--vocab_size", type=int, default=8192)parser.add_argument("--data_dir", type=str, default="data")parser.add_argument("--output_dir", type=str, default="output")parser.add_argument("--distilled_hinglish", type=str, default="data/distilled_hinglish.jsonl")parser.add_argument("--val_ratio", type=float, default=0.01)args = parser.parse_args()data_dir = os.path.join(project_root, args.data_dir)output_dir = os.path.join(project_root, args.output_dir)local_distilled = os.path.join(project_root, args.distilled_hinglish)os.makedirs(data_dir, exist_ok=True)os.makedirs(output_dir, exist_ok=True)tokenizer = build_balanced_tokenizer(output_dir, local_distilled, vocab_size=args.vocab_size)train_bin = os.path.join(data_dir, "train.bin")val_bin = os.path.join(data_dir, "val.bin")print(f"\n[2/2] Streaming Teacher-Distilled tokens up to {args.target_tokens:,} (65% EN | 15% GK | 20% Hinglish)...")en_gen = stream_distilled_english_chat()gk_gen = stream_general_knowledge()hi_gen = stream_distilled_hinglish(local_distilled, max_repeats=8)rng = np.random.default_rng(42)train_buf: List[int] = []val_buf: List[int] = []4 unmodified lineswith open(train_bin, "wb") as f_tr, open(val_bin, "wb") as f_val:while total_tokens < args.target_tokens:gk_ratio = gk_toks / max(1, total_tokens)hi_ratio = hi_toks / max(1, total_tokens)53 unmodified linesif val_buf:np.array(val_buf, dtype=np.uint16).tofile(f_val)print(f"\n[DONE] Built {total_tokens:,} Teacher-Distilled tokens -> {train_bin} & {val_bin}")if __name__ == "__main__":
ViuAI_40M_Kaggle_Master_Pipeline.ipynb+3-3
scripts/distill_teacher_hinglish.pyAdded+132
scripts/generate_kaggle_notebook.py+3-3
scripts/prepare_5b_chat_gk_memmap.py+141-106