Upload code/build_sft_data_v9.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297# ==============================================================================# ViuAI 500M โ SFT v9 Domain-Aware Cognitive Dataset Builder# ==============================================================================# - Ingests 8 Cleaned Files (60,836 samples) from 'Final Clean STF Data'# - Saves Domain-ID Tags (sft_v9_train_domains.npy / sft_v9_val_domains.npy)# - Produces flat uint16 memmapped arrays + offsets + metadata for train_sft.py# ==============================================================================
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 globimport jsonimport timeimport shutilimport hashlibimport randomimport unicodedatafrom datetime import datetime, timezoneimport numpy as npfrom tqdm import tqdmfrom huggingface_hub import HfApi, hf_hub_downloadfrom transformers import PreTrainedTokenizerFast
# Set deterministic random seedrandom.seed(42)np.random.seed(42)
# --- 1. Configuration & Domain Mappings ---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 = 2048EXPECTED_VOCAB_SIZE = 64009
DOMAIN_MAP = { "final_viuai_dataset_math_domain.json": {"id": 0, "name": "math", "weight": 2.0}, "final_viuai_dataset_reasoning_domain.json": {"id": 1, "name": "reasoning", "weight": 2.0}, "final_viuai_dataset_translation.json": {"id": 2, "name": "translation", "weight": 1.5}, "final_viuai_dataset_identity.json": {"id": 3, "name": "identity", "weight": 2.5}, "final_viuai_dataset_chit_chat.json": {"id": 4, "name": "chit_chat", "weight": 1.0}, "final_viuai_dataset_friends_persona.json": {"id": 5, "name": "friends_persona", "weight": 1.0}, "final_viuai_dataset_boyfriend_persona.json": {"id": 6, "name": "boyfriend_persona", "weight": 1.0}, "final_viuai_dataset_girlfriend_persona.json": {"id": 7, "name": "girlfriend_persona", "weight": 1.0},}
SPECIAL_TOKENS = [ "<|user|>", "<|assistant|>", "<|endofturn|>", "[THINK]", "[/THINK]", "<search>", "</search>", "<search_result>", "</search_result>"]
api = HfApi(token=HF_TOKEN)
print("=" * 80)print(f"๐ ViuAI SFT v9 Domain-Aware Dataset Builder")print(f" Model Repo: {REPO_ID} | Dataset Repo: {DATA_REPO_ID}")print(f" Context Length: {CTX_LEN} | Target Vocab: {EXPECTED_VOCAB_SIZE}")print("=" * 80)
# --- 2. Load & Validate Tokenizer ---try: tok_path = hf_hub_download(repo_id=REPO_ID, filename="tokenizer/tokenizer.json", repo_type="model", token=HF_TOKEN)except Exception: tok_path = "tokenizer/tokenizer.json"
tokenizer = PreTrainedTokenizerFast( tokenizer_file=tok_path, pad_token="<pad>", bos_token="<bos>", eos_token="<eos>", unk_token="<unk>")tokenizer.add_tokens(SPECIAL_TOKENS, special_tokens=True)print(f"โ
Tokenizer loaded. Vocab size: {len(tokenizer)} | pad_token_id: {tokenizer.pad_token_id}")assert len(tokenizer) == EXPECTED_VOCAB_SIZE, f"Tokenizer vocab size mismatch: {len(tokenizer)} != {EXPECTED_VOCAB_SIZE}"
# --- 3. Text Cleaners & Formatting Helpers ---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 strip_calculator_junk(text: str) -> str: if not text: return "" text = re.sub(r'<<[^\n>]+>>', '', text) text = re.sub(r'####\s*', 'The answer is: ', text) return text.strip()
# --- 4. Deduplication Registry ---seen_hashes = set()
def is_duplicate(prompt: str, response: str) -> bool: content = (prompt.strip() + "|||" + response.strip()).lower().encode("utf-8") h = hashlib.md5(content).hexdigest() if h in seen_hashes: return True seen_hashes.add(h) return False
# --- 5. Locate Source Clean JSON Data ---source_dir = r"C:\Users\IQC-SURBHI\Documents\S-Work\ViuAI\STF Data\Final Clean STF Data"if not os.path.exists(source_dir): source_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "STF Data", "Final Clean STF Data"))if not os.path.exists(source_dir): source_dir = "Final Clean STF Data"
source_json_files = sorted(glob.glob(os.path.join(source_dir, "*.json")))print(f"๐ Found {len(source_json_files)} clean JSON dataset files in '{source_dir}'.")assert len(source_json_files) > 0, f"No JSON files found in {source_dir}!"
# --- 6. Parse, Format and Tokenize with Domain IDs ---all_samples = []domain_counts = {}
for fpath in source_json_files: fname = os.path.basename(fpath) domain_info = DOMAIN_MAP.get(fname, {"id": 4, "name": "chit_chat", "weight": 1.0}) domain_id = domain_info["id"] domain_name = domain_info["name"] with open(fpath, "r", encoding="utf-8", errors="replace") as fp: raw_data = json.load(fp) print(f"\nโ๏ธ Processing {fname} (Domain {domain_id}: {domain_name} | {len(raw_data):,} items)...") file_samples = 0 file_skipped = 0 for item in tqdm(raw_data, desc=f"Encoding {domain_name}"): instruction = clean_text(item.get("instruction", item.get("input", item.get("prompt", "")))) thinking = strip_calculator_junk(clean_text(item.get("thinking", item.get("thought", "")))) response = strip_calculator_junk(clean_text(item.get("response", item.get("output", "")))) if not instruction or not response: file_skipped += 1 continue if is_duplicate(instruction, response): file_skipped += 1 continue if not thinking: thinking = f"Understand the user's request and formulate a precise, helpful, and direct answer as Sarus by ViuAI." # PURE COGNITIVE REASONING FORMAT full_text = ( f"<|user|>\n{instruction}<|endofturn|>\n" f"<|assistant|>\n[THINK]\n{thinking}\n[/THINK]\n{response}<|endofturn|>" ) # Tokenize sequence input_ids = tokenizer.encode(full_text, truncation=False, add_special_tokens=False) # Prompt masking 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) # Enforce Context Length 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_samples.append({ "input_ids": input_ids, "labels": labels, "domain_id": domain_id, "domain_name": domain_name, "file": fname }) file_samples += 1 domain_counts[domain_name] = file_samples print(f" โ Kept: {file_samples:,} | Skipped/Dupe: {file_skipped:,}")
print("\n" + "=" * 80)print(f"๐ Total Unique Samples Compiled: {len(all_samples):,}")for dname, cnt in domain_counts.items(): print(f" โข {dname:20s}: {cnt:6,} ({cnt/len(all_samples)*100:5.1f}%)")print("=" * 80)
# --- 7. Stratified Train / Val Split (95% Train, 5% Val) ---print("\n๐ Performing Stratified Domain Train/Val Split...")train_samples = []val_samples = []
# Group by domain for stratified splitby_domain = {}for s in all_samples: d = s["domain_id"] if d not in by_domain: by_domain[d] = [] by_domain[d].append(s)
for d, s_list in by_domain.items(): random.shuffle(s_list) n_val_domain = max(50, int(len(s_list) * 0.05)) val_samples.extend(s_list[:n_val_domain]) train_samples.extend(s_list[n_val_domain:])
random.shuffle(train_samples)random.shuffle(val_samples)
print(f"โ
Split Complete:")print(f" Train Samples: {len(train_samples):,}")print(f" Val Samples: {len(val_samples):,}")
# --- 8. Pack and Save Memmapped .npy Files + Domain Array ---out_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "data", "sft_v9"))os.makedirs(out_dir, exist_ok=True)
def pack_and_save(samples, split_name): print(f"\n๐ฆ Packing {split_name} set ({len(samples):,} items)...") offsets = [0] all_input_ids = [] all_labels = [] all_domains = [] for s in tqdm(samples, desc=f"Flattening {split_name}"): ids = s["input_ids"] lbls = s["labels"] dom = s["domain_id"] all_input_ids.extend(ids) all_labels.extend(lbls) all_domains.append(dom) offsets.append(offsets[-1] + len(ids)) ids_arr = np.array(all_input_ids, dtype=np.uint16) labels_arr = np.array(all_labels, dtype=np.int32) offsets_arr = np.array(offsets, dtype=np.uint64) domains_arr = np.array(all_domains, dtype=np.uint8) ids_path = os.path.join(out_dir, f"sft_v9_{split_name}_ids.npy") labels_path = os.path.join(out_dir, f"sft_v9_{split_name}_labels.npy") offsets_path = os.path.join(out_dir, f"sft_v9_{split_name}_offsets.npy") domains_path = os.path.join(out_dir, f"sft_v9_{split_name}_domains.npy") np.save(ids_path, ids_arr) np.save(labels_path, labels_arr) np.save(offsets_path, offsets_arr) np.save(domains_path, domains_arr) print(f" ๐พ Saved {os.path.basename(ids_path)} ({ids_arr.nbytes / (1024*1024):.2f} MB | {len(ids_arr):,} tokens)") print(f" ๐พ Saved {os.path.basename(labels_path)} ({labels_arr.nbytes / (1024*1024):.2f} MB)") print(f" ๐พ Saved {os.path.basename(offsets_path)} ({offsets_arr.nbytes / (1024*1024):.2f} MB)") print(f" ๐พ Saved {os.path.basename(domains_path)} ({domains_arr.nbytes / (1024*1024):.2f} MB | {len(domains_arr):,} domain tags)") return len(ids_arr), len(samples)
train_toks, train_items = pack_and_save(train_samples, "train")val_toks, val_items = pack_and_save(val_samples, "val")
# --- 9. Save Metadata ---metadata = { "version": "sft_v9", "created_at": datetime.now(timezone.utc).isoformat(), "vocab_size": EXPECTED_VOCAB_SIZE, "context_length": CTX_LEN, "total_samples": len(all_samples), "train_samples": train_items, "val_samples": val_items, "train_tokens": train_toks, "val_tokens": val_toks, "domains": DOMAIN_MAP, "domain_counts": domain_counts}
meta_path = os.path.join(out_dir, "metadata_sft_v9.json")with open(meta_path, "w", encoding="utf-8") as f: json.dump(metadata, f, indent=2)
print("\n" + "=" * 80)print(f"๐ SFT v9 DATASET BUILD COMPLETE!")print(f" Output Directory: {out_dir}")print(f" Total Samples: {len(all_samples):,} | Total Tokens: {train_toks + val_toks:,}")print("=" * 80)code/build_sft_data_v9.pyAdded+297