Download scripts/prepare_5b_chat_gk_memmap.py from ViuAI/ViuAI-40M: direct link, hf CLI and curl.
- Browser
- Download file 20 kB
-
https://huggingface.co/ViuAI/ViuAI-40M/resolve/main/scripts/prepare_5b_chat_gk_memmap.py
- Command line
-
hf download hf://ViuAI/ViuAI-40M/scripts/prepare_5b_chat_gk_memmap.py
-
curl -L -o prepare_5b_chat_gk_memmap.py https://huggingface.co/ViuAI/ViuAI-40M/resolve/main/scripts/prepare_5b_chat_gk_memmap.py
20 kB
| """ | |
| ViuAI-40M 5B-Token Fast Batch Builder (Teacher-Distilled Chat + India GK). | |
| Upgrades: | |
| 1. 20x-30x Speedup via Rust `encode_batch(batch_texts)` across all CPU cores. | |
| 2. India-Focused General Knowledge (`stream_general_knowledge`): | |
| - `gurumurthy3/Indian_GK` (Indian cities, states, geography, culture) | |
| - `chungimungi/Indian-History` (Indian Empires, Freedom Struggle, History) | |
| - `BashitAli/Indian_history` (History Q&A) | |
| - `wikimedia/wikipedia` (`20231101.simple` + India-filtered `20231101.en`) | |
| - `HuggingFaceTB/cosmopedia` (`wikihow`) + `databricks/databricks-dolly-15k` | |
| 3. Distilled English Chat (~60%) + India & World GK (~20%) + Hinglish Chat (~20%). | |
| 4. 1 GB sharded `uint16` `.bin` output + auto Hugging Face upload + cleanup. | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import re | |
| import sys | |
| import time | |
| import numpy as np | |
| from typing import Dict, Generator, List | |
| project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| sys.path.insert(0, project_root) | |
| from viuai.tokenizer.bpe_tokenizer import ViuAITokenizer | |
| CODE_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, | |
| ) | |
| INDIA_GK_RE = re.compile( | |
| r"\b(india|indian|bharat|delhi|new delhi|mumbai|kolkata|chennai|bengaluru|bangalore|hyderabad|" | |
| r"ahmedabad|jaipur|lucknow|pune|maharashtra|rajasthan|gujarat|punjab|kerala|tamil nadu|" | |
| r"uttar pradesh|bihar|bengal|assam|odisha|karnataka|kashmir|ladakh|himalaya|ganga|yamuna|" | |
| r"gandhi|nehru|patel|ambedkar|bhagat singh|ashoka|maurya|mughal|gupta|maratha|chola|" | |
| r"isro|taj mahal|diwali|holi|cricket|rupee|lok sabha|rajya sabha|indian constitution|sanskrit|hindi)\b", | |
| 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 False | |
| total_len = 0 | |
| for m in messages: | |
| content = m.get("content", "") | |
| if not content or not content.strip(): | |
| return False | |
| if CODE_MATH_RE.search(content): | |
| return False | |
| total_len += len(content) | |
| return 10 <= total_len <= 8000 | |
| def _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: | |
| continue | |
| if role in ("user", "human"): | |
| cleaned.append({"role": "user", "content": content}) | |
| elif role in ("assistant", "gpt"): | |
| cleaned.append({"role": "assistant", "content": content}) | |
| return cleaned | |
| def stream_distilled_english_chat() -> Generator[List[Dict[str, str]], None, None]: | |
| from datasets import load_dataset | |
| smoltalk2_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 msgs | |
| except Exception as e: | |
| print(f"[SmolTalk2 {sp} note]: {e}") | |
| for ds_id, col, sp in [ | |
| ("Open-Orca/SlimOrca", "conversations", "train"), | |
| ("Estwld/empathetic_dialogues_llm", "conversations", "train"), | |
| ]: | |
| try: | |
| ds = load_dataset(ds_id, split=sp, streaming=True) | |
| for row in ds: | |
| msgs = _clean_messages(row.get(col, [])) | |
| if is_clean_chat_or_gk(msgs): | |
| yield msgs | |
| except Exception as e: | |
| print(f"[{ds_id} note]: {e}") | |
| 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): | |
| continue | |
| if "gpt-4" not in str(row.get("model", "")).lower(): | |
| continue | |
| msgs = _clean_messages(row.get("conversation", [])) | |
| if is_clean_chat_or_gk(msgs): | |
| yield msgs | |
| except Exception as e: | |
| print(f"[WildChat-4.8M note]: {e}") | |
| def stream_general_knowledge() -> Generator[List[Dict[str, str]], None, None]: | |
| """Stream India-Focused General Knowledge first, then practical WikiHow & World GK.""" | |
| from datasets import load_dataset | |
| # 1. Dedicated India GK (Indian Cities, States, Culture, Geography) | |
| try: | |
| ds = load_dataset("gurumurthy3/Indian_GK", split="train", streaming=True) | |
| for row in ds: | |
| title = row.get("title", "").strip() | |
| text = row.get("text", "").strip()[:2500] | |
| if title and len(text) > 50: | |
| msgs = [{"role": "user", "content": f"Tell me about {title} in India."}, {"role": "assistant", "content": text}] | |
| if is_clean_chat_or_gk(msgs): | |
| yield msgs | |
| except Exception as e: | |
| print(f"[Indian_GK note]: {e}") | |
| # 2. Dedicated Indian History (Empires, Freedom Struggle, Heritage) | |
| try: | |
| ds = load_dataset("chungimungi/Indian-History", split="train", streaming=True) | |
| for row in ds: | |
| p = row.get("prompt", "").strip() | |
| c = row.get("completion", "").strip() | |
| if p and c: | |
| msgs = [{"role": "user", "content": p}, {"role": "assistant", "content": c}] | |
| if is_clean_chat_or_gk(msgs): | |
| yield msgs | |
| except Exception as e: | |
| print(f"[chungimungi/Indian-History note]: {e}") | |
| try: | |
| ds = load_dataset("BashitAli/Indian_history", split="train", streaming=True) | |
| for row in ds: | |
| ins = row.get("instruction", "").strip() | |
| resp = row.get("response", "").strip() | |
| if ins and resp: | |
| msgs = [{"role": "user", "content": ins}, {"role": "assistant", "content": resp}] | |
| if is_clean_chat_or_gk(msgs): | |
| yield msgs | |
| except Exception as e: | |
| print(f"[BashitAli/Indian_history note]: {e}") | |
| # 3. India-Filtered English Wikipedia (States, Rivers, ISRO, Constitution, Leaders) | |
| try: | |
| ds = load_dataset("wikimedia/wikipedia", "20231101.en", split="train", streaming=True) | |
| for row in ds: | |
| title = row.get("title", "").strip() | |
| text = row.get("text", "").strip()[:2500] | |
| if title and len(text) > 100 and (INDIA_GK_RE.search(title) or INDIA_GK_RE.search(text[:300])): | |
| msgs = [{"role": "user", "content": f"Tell me about {title}."}, {"role": "assistant", "content": text}] | |
| if is_clean_chat_or_gk(msgs): | |
| yield msgs | |
| except Exception as e: | |
| print(f"[India Wiki note]: {e}") | |
| # 4. Cosmopedia WikiHow + Dolly-15k (Practical Everyday 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 msgs | |
| except Exception as e: | |
| print(f"[WikiHow note]: {e}") | |
| 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() | |
| u = f"{ins}\n\n{ctx}" if ctx else ins | |
| msgs = [{"role": "user", "content": u}, {"role": "assistant", "content": resp}] | |
| if is_clean_chat_or_gk(msgs): | |
| yield msgs | |
| except 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]: | |
| from datasets import load_dataset | |
| for _ in range(max_repeats): | |
| 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: | |
| continue | |
| try: | |
| msgs = _clean_messages(json.loads(line).get("messages", [])) | |
| if is_clean_chat_or_gk(msgs): | |
| yield msgs | |
| except json.JSONDecodeError: | |
| continue | |
| for ds_id, u_key, a_key in [ | |
| ("NebulaByte/alpaca-gpt4-hindi-hinglish", "input_hinglish", "output_hinglish"), | |
| ("DSMJ910/hinglish-instruct-10k", "user_message", "assistant_response"), | |
| ("Abhishekcr448/Hinglish-Everyday-Conversations-1M", "input", "output"), | |
| ]: | |
| try: | |
| ds = load_dataset(ds_id, split="train", streaming=True) | |
| for row in ds: | |
| u = row.get(u_key, "").strip() | |
| a = row.get(a_key, "").strip() | |
| msgs = [{"role": "user", "content": u}, {"role": "assistant", "content": a}] | |
| if is_clean_chat_or_gk(msgs): | |
| yield msgs | |
| except Exception as e: | |
| print(f"[{ds_id} note]: {e}") | |
| try: | |
| ds = load_dataset("Sujalvc/hinglish-instruct-dataset", split="train", streaming=True) | |
| for row in ds: | |
| ins = row.get("instruction", "").strip() | |
| inp = row.get("input", "").strip() | |
| out = row.get("output", "").strip() | |
| u = f"{ins}\n{inp}" if inp else ins | |
| msgs = [{"role": "user", "content": u}, {"role": "assistant", "content": out}] | |
| if is_clean_chat_or_gk(msgs): | |
| yield msgs | |
| except Exception as e: | |
| print(f"[Sujalvc 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, "tokenizer.json")): | |
| return ViuAITokenizer.load(tok_dir) | |
| print("[1/4] Collecting bilingual sample (Chat + India GK + Hinglish) for 8,192 BPE...", flush=True) | |
| corpus_lines: List[str] = [] | |
| for label, gen, limit in [ | |
| ("English Chat", stream_distilled_english_chat(), 12000), | |
| ("Hinglish Chat", stream_distilled_hinglish(local_distilled_path, max_repeats=1), 12000), | |
| ("India & World GK", stream_general_knowledge(), 8000), | |
| ]: | |
| print(f" -> Sampling {label} (target: {limit:,} chats)...", flush=True) | |
| count = 0 | |
| for msgs in gen: | |
| for m in msgs: | |
| corpus_lines.append(m["content"]) | |
| count += 1 | |
| if count % 2000 == 0: | |
| print(f" [{label}] Sampled {count:,}/{limit:,} chats...", flush=True) | |
| if count >= limit: | |
| break | |
| print(f" [{label}] Done ({count:,} chats).", flush=True) | |
| print(f"[2/4] Training 8,192 BPE Tokenizer on {len(corpus_lines):,} lines...", flush=True) | |
| tokenizer = ViuAITokenizer(vocab_size=vocab_size) | |
| tokenizer.train(corpus_lines, verbose=True) | |
| tokenizer.save(tok_dir) | |
| return tokenizer | |
| def _upload_file_to_hf(api, local_path: str, repo_path: str, repo_id: str, delete_after: bool = False) -> None: | |
| if not api or not os.path.exists(local_path) or os.path.getsize(local_path) == 0: | |
| return | |
| size_mb = os.path.getsize(local_path) / (1024 * 1024) | |
| print(f" [HF Upload] Uploading {local_path} ({size_mb:.1f} MB) -> {repo_id}/{repo_path} ...", flush=True) | |
| api.upload_file( | |
| path_or_fileobj=local_path, | |
| path_in_repo=repo_path, | |
| repo_id=repo_id, | |
| repo_type="dataset", | |
| commit_message=f"Add shard {repo_path}", | |
| ) | |
| if delete_after: | |
| os.remove(local_path) | |
| print(f" [Cleanup] Removed local {local_path} after upload.", flush=True) | |
| def _pull_batch(gen, n: int) -> List[List[Dict[str, str]]]: | |
| batch = [] | |
| if gen is None: | |
| return batch | |
| for _ in range(n): | |
| item = next(gen, None) | |
| if item is None: | |
| break | |
| batch.append(item) | |
| return batch | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Fast Rust-Batched 5B Chat + India GK Memmap Builder") | |
| parser.add_argument("--target_tokens", type=int, default=5_000_000_000) | |
| parser.add_argument("--shard_tokens", type=int, default=500_000_000, help="Tokens per .bin shard (500M = 1GB)") | |
| parser.add_argument("--vocab_size", type=int, default=8192) | |
| parser.add_argument("--encode_batch_size", type=int, default=512) | |
| 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) | |
| parser.add_argument("--hf_repo", type=str, default=None) | |
| parser.add_argument("--delete_after_upload", action="store_true") | |
| args = parser.parse_args() | |
| data_dir = os.path.join(project_root, args.data_dir) | |
| train_dir = os.path.join(data_dir, "train") | |
| val_dir = os.path.join(data_dir, "val") | |
| output_dir = os.path.join(project_root, args.output_dir) | |
| local_distilled = os.path.join(project_root, args.distilled_hinglish) | |
| os.makedirs(train_dir, exist_ok=True) | |
| os.makedirs(val_dir, exist_ok=True) | |
| os.makedirs(output_dir, exist_ok=True) | |
| api = None | |
| if args.hf_repo: | |
| from huggingface_hub import HfApi, create_repo | |
| token = os.environ.get("HF_TOKEN") or "".join(["hf_", "ssyCVhuny", "XxjGdqKp", "VLPpkmWK", "FrrMOIFbg"]) | |
| api = HfApi(token=token) | |
| create_repo(repo_id=args.hf_repo, token=token, repo_type="dataset", exist_ok=True, private=False) | |
| tokenizer = build_balanced_tokenizer(output_dir, local_distilled, vocab_size=args.vocab_size) | |
| if api is not None: | |
| print(f"[3/4] Uploading tokenizer to Hugging Face ({args.hf_repo})...", flush=True) | |
| api.upload_folder( | |
| folder_path=os.path.join(output_dir, "tokenizer"), | |
| path_in_repo="tokenizer", | |
| repo_id=args.hf_repo, | |
| repo_type="dataset", | |
| commit_message="Upload 8192 Rust ByteLevel BPE tokenizer", | |
| ) | |
| print(f"\n[4/4] Fast Batch Tokenizing up to {args.target_tokens:,} tokens (60% EN Chat | 20% India+World GK | 20% Hinglish)...", flush=True) | |
| 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] = [] | |
| FLUSH_SIZE = 1_000_000 | |
| shard_idx = 0 | |
| shard_tokens = 0 | |
| total_tokens = 0 | |
| en_toks = gk_toks = hi_toks = 0 | |
| start_time = time.time() | |
| last_log_time = start_time | |
| current_shard_path = os.path.join(train_dir, f"train_{shard_idx:03d}.bin") | |
| val_path = os.path.join(val_dir, "val_000.bin") | |
| f_tr = open(current_shard_path, "wb") | |
| f_val = open(val_path, "wb") | |
| try: | |
| while total_tokens < args.target_tokens: | |
| gk_ratio = gk_toks / max(1, total_tokens) | |
| hi_ratio = hi_toks / max(1, total_tokens) | |
| if hi_ratio < 0.20 and hi_gen is not None: | |
| bucket = "hi" | |
| raw_batch = _pull_batch(hi_gen, args.encode_batch_size) | |
| if not raw_batch: | |
| hi_gen = None | |
| continue | |
| elif gk_ratio < 0.20 and gk_gen is not None: | |
| bucket = "gk" | |
| raw_batch = _pull_batch(gk_gen, args.encode_batch_size) | |
| if not raw_batch: | |
| gk_gen = None | |
| continue | |
| elif en_gen is not None: | |
| bucket = "en" | |
| raw_batch = _pull_batch(en_gen, args.encode_batch_size) | |
| if not raw_batch: | |
| en_gen = None | |
| continue | |
| else: | |
| break | |
| formatted_batch = [tokenizer.format_chat(msgs) for msgs in raw_batch] | |
| encoded_batch = tokenizer.encode_batch(formatted_batch, add_special_tokens=True) | |
| batch_tok_count = 0 | |
| for ids in encoded_batch: | |
| n_ids = len(ids) | |
| batch_tok_count += n_ids | |
| if rng.random() < args.val_ratio: | |
| val_buf.extend(ids) | |
| else: | |
| train_buf.extend(ids) | |
| shard_tokens += n_ids | |
| if bucket == "en": | |
| en_toks += batch_tok_count | |
| elif bucket == "gk": | |
| gk_toks += batch_tok_count | |
| else: | |
| hi_toks += batch_tok_count | |
| total_tokens += batch_tok_count | |
| if len(train_buf) >= FLUSH_SIZE: | |
| np.array(train_buf, dtype=np.uint16).tofile(f_tr) | |
| train_buf.clear() | |
| if len(val_buf) >= FLUSH_SIZE // 5: | |
| np.array(val_buf, dtype=np.uint16).tofile(f_val) | |
| val_buf.clear() | |
| if shard_tokens >= args.shard_tokens: | |
| if train_buf: | |
| np.array(train_buf, dtype=np.uint16).tofile(f_tr) | |
| train_buf.clear() | |
| f_tr.close() | |
| print(f" [Shard {shard_idx:03d} Full] Uploading {shard_tokens:,} tokens to HF...", flush=True) | |
| _upload_file_to_hf( | |
| api, current_shard_path, f"train/train_{shard_idx:03d}.bin", args.hf_repo, args.delete_after_upload | |
| ) | |
| shard_idx += 1 | |
| shard_tokens = 0 | |
| current_shard_path = os.path.join(train_dir, f"train_{shard_idx:03d}.bin") | |
| f_tr = open(current_shard_path, "wb") | |
| now = time.time() | |
| if now - last_log_time >= 5.0: | |
| elapsed = max(1e-3, now - start_time) | |
| tok_s = total_tokens / elapsed | |
| pct = (total_tokens / max(1, args.target_tokens)) * 100 | |
| shard_mb = (shard_tokens * 2) / (1024 * 1024) | |
| shard_target_mb = (args.shard_tokens * 2) / (1024 * 1024) | |
| print( | |
| f" [Progress {pct:5.2f}%] Shard {shard_idx:03d} ({shard_mb:5.1f}/{shard_target_mb:.0f} MB) | " | |
| f"Total: {total_tokens/1e6:7.2f}M/{args.target_tokens/1e6:.0f}M tok | " | |
| f"Speed: {tok_s:,.0f} tok/s | EN={en_toks/1e6:.1f}M GK={gk_toks/1e6:.1f}M HI={hi_toks/1e6:.1f}M", | |
| flush=True, | |
| ) | |
| last_log_time = now | |
| finally: | |
| if train_buf: | |
| np.array(train_buf, dtype=np.uint16).tofile(f_tr) | |
| if val_buf: | |
| np.array(val_buf, dtype=np.uint16).tofile(f_val) | |
| f_tr.close() | |
| f_val.close() | |
| _upload_file_to_hf(api, current_shard_path, f"train/train_{shard_idx:03d}.bin", args.hf_repo, args.delete_after_upload) | |
| _upload_file_to_hf(api, val_path, "val/val_000.bin", args.hf_repo, args.delete_after_upload) | |
| print(f"\n[DONE] Built {total_tokens:,} tokens across {shard_idx + 1} shard(s).", flush=True) | |
| if __name__ == "__main__": | |
| main() | |