Upload folder using huggingface_hub
Browse files2 unmodified lines345667891011101112131415161714 unmodified lines32333432353637387 unmodified lines4647484649505152535455535657585960615962636462636465666768697071656667131 unmodified lines19920020120920220321120420520620768 unmodified lines27627727828627928028128928228328428512 unmodified lines29829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433513 unmodified lines3493503513523533543553563573583593603614 unmodified lines3663673683483693703713723733743753763773563783793803813824 unmodified lines3873883893673903912 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 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)
- Tokenizer: Vocab 64,003 Strict Alignment
- Output: tokenized_data/sft_v15_stage1/ & tokenized_data/sft_v15_stage2/
- 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 lines sys.stderr.reconfigure(encoding="utf-8")
# ------------------------------------------------------------------------------
# 1. Configuration & Paths
# 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 = 25000
TARGET_STAGE2_SAMPLES = 25000
VAL_SPLIT_RATIO = 0.02 # 2% val set (~500 samples per stage)
MAX_SEQ_LEN = 1024
MAX_SEQ_LEN = 2048 # 2048 Context Length (100% Native Architecture Alignment)
SEED = 42
random.seed(SEED)
np.random.seed(SEED)
print("=" * 80)
print("π ViuAI Sarus-500M β SFT v15 Master 50k Dataset Builder")
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
# 2. Load Tokenizer (Cross-Platform & Hugging Face Hub Fallback)
# ------------------------------------------------------------------------------
print("\nπ Loading Tokenizer...")
if not os.path.exists(TOKENIZER_PATH):
# Check cached snapshots first
cache_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_tok
if not os.path.exists(TOKENIZER_PATH):
from huggingface_hub import hf_hub_download
TOKENIZER_PATH = hf_hub_download(repo_id="ViuAI/ViuAI-500M", filename="tokenizer/tokenizer.json", token=HF_TOKEN)131 unmodified lines is_greeting = bool(greeting_whitelist.search(inst)) or len(inst.split()) <= 3
if not is_greeting and len(inst) < 8:
continue
if len(resp) < 15 or len(resp) > 2200:
if len(resp) < 15 or len(resp) > 3500:
continue
if len(th) < 10 or len(th) > 1000:
if len(th) < 10 or len(th) > 2000:
continue
inst_hash = hash(inst.lower()[:80])68 unmodified linesprint(f" β’ English Anchor: {len(stage2_anchor):,} (20%)")
# ------------------------------------------------------------------------------
# 7. Tokenization & Packing Engine
# 7. Tokenization & Packing Engine (Exports both .jsonl and .npy)
# ------------------------------------------------------------------------------
def tokenize_and_pack_dataset(data_list, output_dir, stage_name):
print(f"\nβοΈ Tokenizing & Packing {stage_name} into {output_dir}...")
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-Factory
jsonl_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 Tokenization
prompt_ids = tokenizer.encode(prompt_str, add_special_tokens=False)
target_ids = tokenizer.encode(thought_str + response_str, add_special_tokens=False)
13 unmodified lines offsets.append(len(token_list))
domain_ids.append(d_id)
# Save JSONL
with 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 arrays
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 lines np.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.")
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,
"format": "User + [THINK] + Response",
"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 DATASETS BUILT & TOKENIZED SUCCESSFULLY!")
print("π ALL SFT v15 DUAL FORMAT DATASETS (JSONL + NPY) BUILT SUCCESSFULLY!")
print("=" * 80)code/build_sft_v15_dataset.py+47-24