Upload folder using huggingface_hub
Browse files2 unmodified lines3456789101112131414 unmodified lines293031323334357 unmodified lines4344454647484950515253545556575859606162636465666768697071727374131 unmodified lines20620720820921021121221321468 unmodified lines28328428528628728828929029129212 unmodified lines30530630730830931031131231331431531631731831932032113 unmodified lines3353363373383393404 unmodified lines3453463473483493503513523533543553563573583594 unmodified lines3643653663673682 unmodified linesπ ViuAI Sarus-500M β SFT v15 Master 50k Dataset Builder (2-Stage Curriculum)================================================================================Architecture:- Stage 1: 25,000 Pure English Foundation (Reasoning, Instructions, Math, Natural Chat)- Stage 2: 25,000 Hinglish Adaptation (80% Hinglish/Hindi + 20% English Anchor)- Thinking: 100% [THINK] ... [/THINK] Chain-of-Thought- Natural Warm Greetings: 500+ Human-like conversational greetings (Zero Robotic Tone)- Tokenizer: Vocab 64,003 Strict Alignment- Output: tokenized_data/sft_v15_stage1/ & tokenized_data/sft_v15_stage2/================================================================================"""14 unmodified linessys.stderr.reconfigure(encoding="utf-8")# ------------------------------------------------------------------------------# 1. Configuration & Paths# ------------------------------------------------------------------------------SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))PROJECT_ROOT = os.path.abspath(os.path.join(SCRIPT_DIR, ".."))7 unmodified linesTARGET_STAGE1_SAMPLES = 25000TARGET_STAGE2_SAMPLES = 25000VAL_SPLIT_RATIO = 0.02 # 2% val set (~500 samples per stage)MAX_SEQ_LEN = 1024SEED = 42random.seed(SEED)np.random.seed(SEED)print("=" * 80)print("π ViuAI Sarus-500M β SFT v15 Master 50k Dataset Builder")print("=" * 80)HF_TOKEN = os.environ.get("HF_TOKEN")# ------------------------------------------------------------------------------# 2. Load Tokenizer# ------------------------------------------------------------------------------print("\nπ Loading Tokenizer...")if not os.path.exists(TOKENIZER_PATH):# Check cached snapshots firstcache_base = r"C:\Users\IQC-SURBHI\.cache\huggingface\hub\models--ViuAI--ViuAI-500M\snapshots"if os.path.exists(cache_base):snaps = os.listdir(cache_base)if snaps:c_tok = os.path.join(cache_base, snaps[0], "tokenizer", "tokenizer.json")if os.path.exists(c_tok):TOKENIZER_PATH = c_tokif not os.path.exists(TOKENIZER_PATH):from huggingface_hub import hf_hub_downloadTOKENIZER_PATH = hf_hub_download(repo_id="ViuAI/ViuAI-500M", filename="tokenizer/tokenizer.json", token=HF_TOKEN)131 unmodified linesis_greeting = bool(greeting_whitelist.search(inst)) or len(inst.split()) <= 3if not is_greeting and len(inst) < 8:continueif len(resp) < 15 or len(resp) > 2200:continueif len(th) < 10 or len(th) > 1000:continueinst_hash = hash(inst.lower()[:80])68 unmodified linesprint(f" β’ English Anchor: {len(stage2_anchor):,} (20%)")# ------------------------------------------------------------------------------# 7. Tokenization & Packing Engine# ------------------------------------------------------------------------------def tokenize_and_pack_dataset(data_list, output_dir, stage_name):print(f"\nβοΈ Tokenizing & Packing {stage_name} into {output_dir}...")os.makedirs(output_dir, exist_ok=True)num_val = max(200, int(len(data_list) * VAL_SPLIT_RATIO))12 unmodified lines"clarification & uncertainty": 6}for item in tqdm(dataset, desc=f"Processing {split_name} ({len(dataset):,})"):inst = item["instruction"]th = item["thinking"]resp = item["response"]dom = item.get("domain", "chit-chat").lower()d_id = domain_map.get(dom, 0)prompt_str = f"<|user|>\n{inst}<|endofturn|>\n<|assistant|>\n"thought_str = f"[THINK]\n{th}\n[/THINK]\n"response_str = f"{resp}<|endofturn|>"prompt_ids = tokenizer.encode(prompt_str, add_special_tokens=False)target_ids = tokenizer.encode(thought_str + response_str, add_special_tokens=False)13 unmodified linesoffsets.append(len(token_list))domain_ids.append(d_id)tok_arr = np.array(token_list, dtype=np.uint32)lbl_arr = np.array(label_list, dtype=np.int32)off_arr = np.array(offsets, dtype=np.int64)4 unmodified linesnp.save(os.path.join(output_dir, f"{split_name}_offsets.npy"), off_arr)np.save(os.path.join(output_dir, f"{split_name}_domains.npy"), dom_arr)print(f" β {split_name.upper()}: {len(dataset):,} samples | {len(tok_arr):,} total tokens | Saved.")metadata = {"stage": stage_name,"total_samples": len(data_list),"train_samples": len(train_data),"val_samples": len(val_data),"vocab_size": vocab_size,"format": "User + [THINK] + Response","has_natural_greetings": True}with open(os.path.join(output_dir, "metadata.json"), "w", encoding="utf-8") as f:4 unmodified linestokenize_and_pack_dataset(stage2_data, STAGE2_OUT_DIR, "Stage 2 (Hinglish Adaptation)")print("\n" + "=" * 80)print("π ALL SFT v15 DATASETS BUILT & TOKENIZED SUCCESSFULLY!")print("=" * 80)2 unmodified lines3456789101112131415161714 unmodified lines323334353637387 unmodified lines46474849505152535455565758596061626364656667131 unmodified lines19920020120220320420520620768 unmodified lines27627727827928028128228328428512 unmodified lines29829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433513 unmodified lines3493503513523533543553563573583593603614 unmodified lines3663673683693703713723733743753763773783793803813824 unmodified lines3873883893903912 unmodified linesπ ViuAI Sarus-500M β SFT v15 Master 50k Dataset Builder (2-Stage Curriculum)================================================================================Architecture:- Stage 1: 25,000 Pure English Foundation (Reasoning, Code, Math, Instructions, Natural Chat)- Stage 2: 25,000 Hinglish Adaptation (80% Hinglish/Hindi + 20% English Anchor)- Thinking: 100% [THINK] ... [/THINK] Chain-of-Thought- Natural Warm Greetings: 500+ Human-like conversational greetings (Zero Robotic Tone)- Sequence Length: MAX_SEQ_LEN = 2048 (Zero Truncation)- Dual Output Formats:1. .jsonl format (Standard Hugging Face / TRL SFTTrainer / LLaMA-Factory)2. .npy packed format (Zero-overhead mmap arrays for ViuAI custom PyTorch engine)- Cross-Platform: 100% Linux & Windows compatible (Zero hardcoded OS paths)================================================================================"""14 unmodified linessys.stderr.reconfigure(encoding="utf-8")# ------------------------------------------------------------------------------# 1. Configuration & Paths (100% Cross-Platform)# ------------------------------------------------------------------------------SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))PROJECT_ROOT = os.path.abspath(os.path.join(SCRIPT_DIR, ".."))7 unmodified linesTARGET_STAGE1_SAMPLES = 25000TARGET_STAGE2_SAMPLES = 25000VAL_SPLIT_RATIO = 0.02 # 2% val set (~500 samples per stage)MAX_SEQ_LEN = 2048 # 2048 Context Length (100% Native Architecture Alignment)SEED = 42random.seed(SEED)np.random.seed(SEED)print("=" * 80)print("π ViuAI Sarus-500M β SFT v15 Master 50k Dataset Builder (MAX_SEQ_LEN=2048)")print("=" * 80)HF_TOKEN = os.environ.get("HF_TOKEN")# ------------------------------------------------------------------------------# 2. Load Tokenizer (Cross-Platform & Hugging Face Hub Fallback)# ------------------------------------------------------------------------------print("\nπ Loading Tokenizer...")if not os.path.exists(TOKENIZER_PATH):from huggingface_hub import hf_hub_downloadTOKENIZER_PATH = hf_hub_download(repo_id="ViuAI/ViuAI-500M", filename="tokenizer/tokenizer.json", token=HF_TOKEN)131 unmodified linesis_greeting = bool(greeting_whitelist.search(inst)) or len(inst.split()) <= 3if not is_greeting and len(inst) < 8:continueif len(resp) < 15 or len(resp) > 3500:continueif len(th) < 10 or len(th) > 2000:continueinst_hash = hash(inst.lower()[:80])68 unmodified linesprint(f" β’ English Anchor: {len(stage2_anchor):,} (20%)")# ------------------------------------------------------------------------------# 7. Tokenization & Packing Engine (Exports both .jsonl and .npy)# ------------------------------------------------------------------------------def tokenize_and_pack_dataset(data_list, output_dir, stage_name):print(f"\nβοΈ Processing & Tokenizing {stage_name} into {output_dir}...")os.makedirs(output_dir, exist_ok=True)num_val = max(200, int(len(data_list) * VAL_SPLIT_RATIO))12 unmodified lines"clarification & uncertainty": 6}jsonl_path = os.path.join(output_dir, f"{split_name}.jsonl")jsonl_entries = []for item in tqdm(dataset, desc=f"Processing {split_name} ({len(dataset):,})"):inst = item["instruction"]th = item["thinking"]resp = item["response"]dom = item.get("domain", "chit-chat").lower()lang = item.get("language", "english")d_id = domain_map.get(dom, 0)prompt_str = f"<|user|>\n{inst}<|endofturn|>\n<|assistant|>\n"thought_str = f"[THINK]\n{th}\n[/THINK]\n"response_str = f"{resp}<|endofturn|>"full_text = f"{prompt_str}{thought_str}{response_str}"# JSONL Entry for TRL SFTTrainer / Hugging Face / LLaMA-Factoryjsonl_entries.append({"instruction": inst,"thinking": th,"response": resp,"language": lang,"domain": dom,"text": full_text,"messages": [{"role": "user", "content": inst},{"role": "assistant", "content": f"[THINK]\n{th}\n[/THINK]\n{resp}"}]})# Binary Tokenizationprompt_ids = tokenizer.encode(prompt_str, add_special_tokens=False)target_ids = tokenizer.encode(thought_str + response_str, add_special_tokens=False)13 unmodified linesoffsets.append(len(token_list))domain_ids.append(d_id)# Save JSONLwith open(jsonl_path, "w", encoding="utf-8") as f:for entry in jsonl_entries:f.write(json.dumps(entry, ensure_ascii=False) + "\n")print(f" π Saved {split_name.upper()} JSONL: {jsonl_path} ({len(jsonl_entries):,} rows)")# Save NumPy binary arraystok_arr = np.array(token_list, dtype=np.uint32)lbl_arr = np.array(label_list, dtype=np.int32)off_arr = np.array(offsets, dtype=np.int64)4 unmodified linesnp.save(os.path.join(output_dir, f"{split_name}_offsets.npy"), off_arr)np.save(os.path.join(output_dir, f"{split_name}_domains.npy"), dom_arr)print(f" β Saved {split_name.upper()} NPY: {len(dataset):,} samples | {len(tok_arr):,} total tokens.")metadata = {"stage": stage_name,"total_samples": len(data_list),"train_samples": len(train_data),"val_samples": len(val_data),"max_seq_len": MAX_SEQ_LEN,"vocab_size": vocab_size,"formats_available": ["jsonl", "npy"],"chat_template": "User + [THINK] + Response","has_natural_greetings": True}with open(os.path.join(output_dir, "metadata.json"), "w", encoding="utf-8") as f:4 unmodified linestokenize_and_pack_dataset(stage2_data, STAGE2_OUT_DIR, "Stage 2 (Hinglish Adaptation)")print("\n" + "=" * 80)print("π ALL SFT v15 DUAL FORMAT DATASETS (JSONL + NPY) BUILT SUCCESSFULLY!")print("=" * 80)
code/build_sft_v15_dataset.py+47-24