Upload code/build_sft_data_v8.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324# ==============================================================================# ViuAI 500M β SFT v8 Pure Cognitive Dataset Builder (NO RAG / Deep Monologue)# ==============================================================================# 11 Modules Ingested from Raw SFT Data (210k+ Samples)# Produces exact 6-file flat memmapped format (.npy) + metadata for train_sft.py# Optimized to run on Kaggle / Colab / Rental GPU / Local# ==============================================================================
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_download, list_repo_files, delete_filefrom transformers import PreTrainedTokenizerFast
# Set deterministic random seedrandom.seed(42)np.random.seed(42)
# --- 1. Configuration & Tokens ---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
SPECIAL_TOKENS = [ "<|user|>", "<|assistant|>", "<|endofturn|>", "[THINK]", "[/THINK]", "<search>", "</search>", "<search_result>", "</search_result>"]
api = HfApi(token=HF_TOKEN)
print("=" * 70)print(f"π ViuAI SFT v8 Dataset Builder β Pure Cognitive Reasoning (NO RAG)")print(f" Model Repo: {REPO_ID} | Dataset Repo: {DATA_REPO_ID}")print(f" Context Length: {CTX_LEN} | Target Vocab: {EXPECTED_VOCAB_SIZE}")print("=" * 70)
# --- 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: """Cleans raw text while strictly preserving code indentation.""" 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: """Removes leftover calculator tokens <<4+4=8>> and GSM8K headers.""" 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. Download Raw JSON Data from Hugging Face if not local ---work_dir = "/kaggle/working" if os.path.exists("/kaggle/working") else os.getcwd()raw_local_dir = os.path.join(work_dir, "raw_sft_data")os.makedirs(raw_local_dir, exist_ok=True)
# First check if local STF Data existsif os.path.exists("STF Data") and len(glob.glob("STF Data/*.json")) > 0: source_json_files = sorted(glob.glob("STF Data/*.json")) print(f"π Found {len(source_json_files)} local JSON files in 'STF Data/'.")else: print(f"π₯ Downloading raw SFT dataset files from HF: {DATA_REPO_ID} (raw_data/)...") try: repo_files = list_repo_files(repo_id=DATA_REPO_ID, repo_type="dataset", token=HF_TOKEN) raw_repo_files = [f for f in repo_files if f.startswith("raw_data/") and f.endswith(".json")] print(f" Found {len(raw_repo_files)} JSON files in Hugging Face repo.") source_json_files = [] for rf in raw_repo_files: local_target = hf_hub_download( repo_id=DATA_REPO_ID, filename=rf, repo_type="dataset", local_dir=raw_local_dir, token=HF_TOKEN ) source_json_files.append(local_target) except Exception as e: print(f"β οΈ Error downloading from HF: {e}") source_json_files = sorted(glob.glob(os.path.join(raw_local_dir, "**", "*.json"), recursive=True))
print(f"β
Ready to process {len(source_json_files)} dataset files.")
# --- 6. Parse, Format (NO RAG) and Tokenize ---all_samples = []category_stats = {}
for fpath in source_json_files: fname = os.path.basename(fpath) file_samples = 0 file_skipped = 0 with open(fpath, "r", encoding="utf-8") as fp: raw_data = json.load(fp) print(f"\nβοΈ Processing {fname} ({len(raw_data):,} items)...") for item in tqdm(raw_data, desc=f"Encoding {fname[:25]}"): instruction = clean_text(item.get("instruction", "")) thinking = strip_calculator_junk(clean_text(item.get("thinking", ""))) response = strip_calculator_junk(clean_text(item.get("response", ""))) if not instruction or not response: file_skipped += 1 continue if is_duplicate(instruction, response): file_skipped += 1 continue if not thinking: thinking = "Understand user query and formulate a clear, direct, and helpful response as Sarus by ViuAI." # PURE COGNITIVE FORMAT (NO RAG) 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) # Calculate prompt header length for 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 (2048) 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": item.get("domain", fname), "file": fname }) file_samples += 1 category_stats[fname] = { "total_raw": len(raw_data), "valid_kept": file_samples, "skipped_or_dupe": file_skipped } print(f" β Kept: {file_samples:,} | Skipped/Dupe: {file_skipped:,}")
print("\n" + "=" * 70)print(f"π Total Unique Samples Compiled: {len(all_samples):,}")print("=" * 70)
# --- 7. Shuffle & Split (95% Train, 5% Val) ---print("\nπ Shuffling and creating 95% Train / 5% Val split...")random.shuffle(all_samples)
n_total = len(all_samples)n_val = max(1000, int(n_total * 0.05))n_train = n_total - n_val
train_samples = all_samples[:n_train]val_samples = all_samples[n_train:]
print(f" β Train Examples: {len(train_samples):,}")print(f" β Val Examples: {len(val_samples):,}")
# --- 8. Pack into flat NumPy arrays (.npy) ---output_dir = os.path.join(work_dir, "sft_v8_dataset")os.makedirs(output_dir, exist_ok=True)
def pack_and_save(samples, split_name, prefix="sft_v8_"): print(f"\nπ¦ Packing {split_name} ({len(samples):,} samples) into flat memmap format...") offsets = [0] total_tokens = sum(len(s["input_ids"]) for s in samples) ids_arr = np.empty(total_tokens, dtype=np.int64) labels_arr = np.empty(total_tokens, dtype=np.int64) curr_ptr = 0 for s in tqdm(samples, desc=f"Packing {split_name}"): ids = s["input_ids"] labels = s["labels"] length = len(ids) ids_arr[curr_ptr:curr_ptr + length] = ids labels_arr[curr_ptr:curr_ptr + length] = labels curr_ptr += length offsets.append(curr_ptr) offsets_arr = np.array(offsets, dtype=np.int64) ids_path = os.path.join(output_dir, f"{prefix}{split_name}_ids.npy") labels_path = os.path.join(output_dir, f"{prefix}{split_name}_labels.npy") offsets_path = os.path.join(output_dir, f"{prefix}{split_name}_offsets.npy") np.save(ids_path, ids_arr) np.save(labels_path, labels_arr) np.save(offsets_path, offsets_arr) print(f" β
Saved {os.path.basename(ids_path)} ({os.path.getsize(ids_path)/1e6:.1f} MB)") print(f" β
Saved {os.path.basename(labels_path)} ({os.path.getsize(labels_path)/1e6:.1f} MB)") print(f" β
Saved {os.path.basename(offsets_path)} ({os.path.getsize(offsets_path)/1e6:.1f} MB)") print(f" β Total tokens: {total_tokens:,}") return total_tokens
train_tokens = pack_and_save(train_samples, "train", prefix="sft_v8_")val_tokens = pack_and_save(val_samples, "val", prefix="sft_v8_")
# Create fallback generic sft_ prefix copies as wellfor split in ["train", "val"]: for kind in ["ids", "labels", "offsets"]: src = os.path.join(output_dir, f"sft_v8_{split}_{kind}.npy") dst = os.path.join(output_dir, f"sft_{split}_{kind}.npy") shutil.copyfile(src, dst)
# Save metadata JSONmeta = { "version": "v8_no_rag", "timestamp": datetime.now(timezone.utc).isoformat(), "architecture": "Pure Monologue Cognitive Reasoning (No RAG)", "context_len": CTX_LEN, "vocab_size": EXPECTED_VOCAB_SIZE, "total_unique_examples": n_total, "train_examples": n_train, "val_examples": n_val, "train_tokens": train_tokens, "val_tokens": val_tokens, "total_tokens": train_tokens + val_tokens, "files_breakdown": category_stats}meta_path = os.path.join(output_dir, "dataset_meta_v8.json")with open(meta_path, "w", encoding="utf-8") as fp: json.dump(meta, fp, indent=2, ensure_ascii=False)
# Also save generic dataset_meta.jsonshutil.copyfile(meta_path, os.path.join(output_dir, "dataset_meta.json"))
print("\n" + "=" * 70)print(f"π SFT v8 Generation Complete! ({n_total:,} examples, {train_tokens+val_tokens:,} tokens)")print("=" * 70)
# --- 9. Clean Old Files & Upload to Hugging Face ---print(f"\nβοΈ Uploading new SFT v8 tokenized dataset to Hugging Face ({DATA_REPO_ID})...")try: # Delete old v7 files if present old_files_to_remove = [ "dataset_meta_v7.json", "sft_v7_train_ids.npy", "sft_v7_train_labels.npy", "sft_v7_train_offsets.npy", "sft_v7_val_ids.npy", "sft_v7_val_labels.npy", "sft_v7_val_offsets.npy" ] for old_f in old_files_to_remove: try: delete_file(path_in_repo=old_f, repo_id=DATA_REPO_ID, repo_type="dataset", token=HF_TOKEN) print(f" ποΈ Removed old file: {old_f}") except Exception: pass
# Upload all new generated files api.upload_folder( folder_path=output_dir, repo_id=DATA_REPO_ID, repo_type="dataset" ) print(f"π Successfully uploaded new SFT v8 tokenized dataset to Hugging Face!") print(f"π Dataset: https://huggingface.co/datasets/{DATA_REPO_ID}")except Exception as e: print(f"β οΈ Upload error: {e}")code/build_sft_data_v8.pyAdded+324