Upload code/build_sft_data_v4.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496"""Sarus 500M (by ViuAI) โ SFT Dataset Builder V4=================================================KEY IMPROVEMENT over V3: Tool Response Masking for Internet Search
V3 mein search hallucination tha kyunki model search result khud likhnaseekhta tha. V4 mein hum 3-part masking use karenge:
PART 1 (Loss=ACTIVE): User query + <search>query</search> <- Model seekhega SEARCH kab karna hai PART 2 (Loss=-100): <search_result>...</search_result> <- Model is data ko PADHEGA lekin likhna NAHI seekhega PART 3 (Loss=ACTIVE): Final answer <|endofturn|> <- Model seekhega result ke baad ANSWER kaise dena
Data Mix (33,000 total): - TriviaQA (Search) : 8,000 -- Agent search examples with tool masking - GSM8K (Math + Think) : 7,000 -- Math reasoning with [THINK] - General Chat : 10,500 -- Coding, writing, reasoning - Identity + Hindi : 3,000 -- Sarus ki identity, Hindi baat-cheet - DailyDialog (Friendly): 4,500 -- Casual/friendly conversations
RUN THIS ON KAGGLE!"""import osimport reimport randomimport numpy as npfrom datasets import load_datasetfrom tqdm import tqdmfrom transformers import PreTrainedTokenizerFastfrom huggingface_hub import HfApi, hf_hub_download
# =========================================================================# CONFIGURATION# =========================================================================random.seed(42)np.random.seed(42)
HF_TOKEN = os.environ.get("HF_TOKEN")if not HF_TOKEN: raise ValueError("Please set HF_TOKEN environment variable!")
DATA_REPO = "ViuAI/viuai-500m-sft-tokenized"MODEL_REPO = "ViuAI/ViuAI-500M"OUT_DIR = "sft_data_v4"os.makedirs(OUT_DIR, exist_ok=True)
# TargetsTRIVIA_TARGET = 8000; VAL_TRIVIA = 400MATH_TARGET = 7000; VAL_MATH = 350GENERAL_TARGET = 10500; VAL_GENERAL = 525IDENTITY_TARGET = 3000; VAL_IDENTITY = 150FRIENDLY_TARGET = 4500; VAL_FRIENDLY = 225
# =========================================================================# TOKENIZER# =========================================================================print("Loading tokenizer from HuggingFace...")tok_path = hf_hub_download(MODEL_REPO, "tokenizer/tokenizer.json", token=HF_TOKEN)tokenizer = PreTrainedTokenizerFast(tokenizer_file=tok_path)print(f"Vocab size: {tokenizer.vocab_size}")
# All special token IDsUSER_ID = tokenizer.convert_tokens_to_ids("<|user|>")ASST_ID = tokenizer.convert_tokens_to_ids("<|assistant|>")EOT_ID = tokenizer.convert_tokens_to_ids("<|endofturn|>")
# Search/Think tokens are already in vocab as IDs 64003-64008# But since V3 tokenizer only has user/asst/eot (64000-64002),# we use text-based tags for <search> and <search_result># and check if they are single tokens or multi-token
def check_special_ids(): """Check which search tags are available in tokenizer.""" tags = { "think_open": "[THINK]", "think_close": "[/THINK]", "search_open": "<search>", "search_close": "</search>", "result_open": "<search_result>", "result_close": "</search_result>", } for name, tag in tags.items(): ids = tokenizer.encode(tag, add_special_tokens=False) print(f" {tag!r:25s} -> token IDs: {ids}")
print("\nSpecial tag token IDs:")check_special_ids()
# =========================================================================# CORE MASKING HELPER# =========================================================================def tokenize_with_mask(ids_list, labels_list): """Convert Python lists to numpy arrays with dtype int32.""" return np.array(ids_list, dtype=np.int32), np.array(labels_list, dtype=np.int32)
def build_search_example(user_text: str, search_query: str, search_result: str, final_answer: str): """ Build a 3-part Tool Response Masking example.
Format: [PART 1 - Active] <|user|>\n{user_text}<|endofturn|>\n<|assistant|>\n<search>{search_query}</search> [PART 2 - Masked] \n<search_result>\n{search_result}\n</search_result>\n [PART 3 - Active] {final_answer}<|endofturn|>\n
Labels: PART 1: same as token ids (model learns to generate search) PART 2: -100 (model reads but doesn't learn to generate results) PART 3: same as token ids (model learns to use results for answer) """ part1 = f"<|user|>\n{user_text}<|endofturn|>\n<|assistant|>\n<search>{search_query}</search>" part2 = f"\n<search_result>\n{search_result}\n</search_result>\n" part3 = f"{final_answer}<|endofturn|>\n"
ids1 = tokenizer.encode(part1, add_special_tokens=False) ids2 = tokenizer.encode(part2, add_special_tokens=False) ids3 = tokenizer.encode(part3, add_special_tokens=False)
# Labels # PART 1: user is masked (only assistant output is trained on) # We want to mask the user prompt part, keep assistant part active user_prompt = f"<|user|>\n{user_text}<|endofturn|>\n<|assistant|>\n" user_prompt_ids = tokenizer.encode(user_prompt, add_special_tokens=False) n_user = len(user_prompt_ids)
labels1 = [-100] * n_user + ids1[n_user:] # Mask user part, keep search query + tags labels2 = [-100] * len(ids2) # FULLY MASKED - search result labels3 = ids3.copy() # FULLY ACTIVE - final answer
all_ids = ids1 + ids2 + ids3 all_labels = labels1 + labels2 + labels3
if len(all_ids) > 2048: return None, None
return (np.array(all_ids, dtype=np.int32), np.array(all_labels, dtype=np.int32))
def build_simple_example(user_text: str, assistant_text: str): """Standard single-turn example with user turn masked.""" full = f"<|user|>\n{user_text}<|endofturn|>\n<|assistant|>\n{assistant_text}<|endofturn|>\n" prefix = f"<|user|>\n{user_text}<|endofturn|>\n<|assistant|>\n"
ids = tokenizer.encode(full, add_special_tokens=False) prefix_ids = tokenizer.encode(prefix, add_special_tokens=False) n_prefix = len(prefix_ids)
labels = [-100] * n_prefix + ids[n_prefix:]
if len(ids) > 2048: return None, None
return (np.array(ids, dtype=np.int32), np.array(labels, dtype=np.int32))
# =========================================================================# SECTION 1 โ TRIVIA (with Tool Response Masking)# =========================================================================def build_trivia_search(): print("\n[1/5] TriviaQA โ Tool Response Masking examples...") try: ds = load_dataset("trivia_qa", "rc.nocontext", split="train", trust_remote_code=True) except Exception as e: print(f" WARNING: Could not load TriviaQA: {e}") return [], []
examples = [] for row in tqdm(ds, desc="TriviaQA"): question = row["question"].strip() answer = row["answer"]["value"].strip() if not question or not answer: continue
# Search query is just the question search_query = question # Simulated search result (realistic-looking factual context) search_result = ( f"According to multiple sources, the answer to '{question}' is '{answer}'. " f"This is a well-established fact found in encyclopedias and reference databases." ) final_answer = answer
ids, labels = build_search_example(question, search_query, search_result, final_answer) if ids is not None: examples.append((ids, labels)) if len(examples) >= TRIVIA_TARGET + VAL_TRIVIA: break
random.shuffle(examples) train = examples[:TRIVIA_TARGET] val = examples[TRIVIA_TARGET:TRIVIA_TARGET + VAL_TRIVIA] print(f" Built: {len(train)} train + {len(val)} val") return train, val
# =========================================================================# SECTION 2 โ GSM8K (Math with [THINK] reasoning)# =========================================================================MATH_FORMAT_TEMPLATES = [ lambda q, steps, ans: f"[THINK]\n{steps}\n[/THINK]\n{ans}", lambda q, steps, ans: f"Let me work through this step by step:\n\n{steps}\n\nAnswer: {ans}", lambda q, steps, ans: f"[THINK]\nIs math problem ko carefully solve karta hoon.\n{steps}\n[/THINK]\n**Answer: {ans}**", lambda q, steps, ans: f"{steps}\n\nThe answer is **{ans}**.", lambda q, steps, ans: f"[THINK]\nStep-by-step solution:\n{steps}\n[/THINK]\nFinal answer: {ans}",]
def build_math(): print("\n[2/5] GSM8K โ Math reasoning examples...") try: ds = load_dataset("gsm8k", "main", split="train", trust_remote_code=True) except Exception as e: print(f" WARNING: Could not load GSM8K: {e}") return [], []
examples = [] for row in tqdm(ds, desc="GSM8K"): question = row["question"].strip() answer = row["answer"].strip() # Split answer: steps (before ####) and final number (after ####) if "####" in answer: steps, final = answer.split("####", 1) steps = steps.strip() final = final.strip() else: steps = answer final = answer.split()[-1]
fmt = random.choice(MATH_FORMAT_TEMPLATES) assistant_text = fmt(question, steps, final)
ids, labels = build_simple_example(question, assistant_text) if ids is not None: examples.append((ids, labels)) if len(examples) >= MATH_TARGET + VAL_MATH: break
random.shuffle(examples) train = examples[:MATH_TARGET] val = examples[MATH_TARGET:MATH_TARGET + VAL_MATH] print(f" Built: {len(train)} train + {len(val)} val") return train, val
# =========================================================================# SECTION 3 โ GENERAL CHAT (Dolly + OpenAssistant)# =========================================================================def build_general(): print("\n[3/5] General Chat โ Dolly + OpenAssistant...") examples = []
# Dolly try: ds = load_dataset("databricks/databricks-dolly-15k", split="train", trust_remote_code=True) for row in tqdm(ds, desc="Dolly"): instruction = row.get("instruction", "").strip() context = row.get("context", "").strip() response = row.get("response", "").strip() if not instruction or not response: continue if context: user_text = f"{instruction}\n\nContext: {context}" else: user_text = instruction ids, labels = build_simple_example(user_text, response) if ids is not None: examples.append((ids, labels)) if len(examples) >= GENERAL_TARGET + VAL_GENERAL: break except Exception as e: print(f" WARNING: Could not load Dolly: {e}")
# OpenAssistant (oasst1) fallback if Dolly not enough if len(examples) < GENERAL_TARGET + VAL_GENERAL: try: ds = load_dataset("OpenAssistant/oasst1", split="train", trust_remote_code=True) rows = [r for r in ds if r.get("role") == "prompter" and r.get("lang") == "en"] for row in tqdm(rows, desc="OASST"): user_text = row.get("text", "").strip() if not user_text: continue ids, labels = build_simple_example(user_text, "I'd be happy to help with that!") if ids is not None: examples.append((ids, labels)) if len(examples) >= GENERAL_TARGET + VAL_GENERAL: break except Exception as e: print(f" WARNING: Could not load OASST: {e}")
random.shuffle(examples) train = examples[:GENERAL_TARGET] val = examples[GENERAL_TARGET:GENERAL_TARGET + VAL_GENERAL] print(f" Built: {len(train)} train + {len(val)} val") return train, val
# =========================================================================# SECTION 4 โ IDENTITY + HINDI CHAT# =========================================================================IDENTITY_QA = [ # English identity ("What is your name?", "My name is Sarus! I'm an AI assistant created by ViuAI."), ("Who created you?", "I was created by ViuAI. I'm Sarus, their AI assistant!"), ("What AI are you?", "I'm Sarus, a 500M parameter language model developed by ViuAI."), ("Are you ChatGPT?", "No, I'm not ChatGPT. I'm Sarus, an AI assistant made by ViuAI!"), ("Are you made by OpenAI?", "No! I'm Sarus, created by ViuAI โ not OpenAI."), ("What can you do?", "I'm Sarus by ViuAI! I can answer questions, help with coding, write essays, solve math, and even search the internet when needed."), ("Who are you?", "I am Sarus, an AI assistant built by ViuAI to help you with a wide variety of tasks."), ("Introduce yourself.", "Hi! I'm Sarus, an AI language model created by ViuAI. I'm here to assist you with questions, coding, math, writing, and more!"), ("What model are you?", "I'm Sarus โ a 500M parameter language model built by ViuAI."), ("Are you a robot?", "I'm an AI assistant named Sarus, created by ViuAI. Not a robot, but I can think and respond to help you!"), # Hindi identity ("Aap kaun hain?", "Main Sarus hoon! ViuAI ne mujhe banaya hai. Main aapki kaise madad kar sakta hoon?"), ("Tumhara naam kya hai?", "Mera naam Sarus hai! Mujhe ViuAI ne create kiya hai."), ("Kya aap ChatGPT ho?", "Nahi, main ChatGPT nahi hoon. Main Sarus hoon, ViuAI ka AI assistant!"), ("Aapko kisne banaya?", "Mujhe ViuAI ne banaya hai. Main Sarus hoon, unka AI assistant!"), ("Kya aap AI ho?", "Haan, main Sarus hoon โ ViuAI dwara banaya gaya ek AI assistant!"), ("Apna parichay do.", "Namaste! Main Sarus hoon, ViuAI ka ek AI assistant. Aapki kisi bhi cheez mein madad karne ke liye taiyar hoon!"), ("Aap kya kar sakte ho?", "Main Sarus hoon! Main sawalon ke jawab de sakta hoon, coding mein madad kar sakta hoon, math solve kar sakta hoon, aur internet par search bhi kar sakta hoon."), ("Kaun si company ne banaya?", "ViuAI ne mujhe banaya hai. Mera naam Sarus hai!"), ("Kya aap insaan ho?", "Nahi, main ek AI hoon! Mera naam Sarus hai aur mujhe ViuAI ne banaya hai."), ("Aap kahan se ho?", "Main ViuAI ka product hoon. Mera naam Sarus hai aur main aapki madad ke liye hamesha taiyar hoon!"), # General Hindi chat ("Aap kaise hain?", "Main bilkul theek hoon, shukriya! Aap kaise hain? Kya main aapki koi madad kar sakta hoon?"), ("Namaste!", "Namaste! Main Sarus hoon. Aapka swagat hai! Aaj main aapki kya madad kar sakta hoon?"), ("Hello!", "Hello! I'm Sarus, your AI assistant by ViuAI. How can I help you today?"), ("Hi there!", "Hi! I'm Sarus by ViuAI. Nice to meet you! What can I help you with?"), ("Dhanyavaad!", "Aapka swagat hai! Agar aur koi sawaal ho toh zaroor poochhein."), ("Shukriya!", "Koi baat nahi! Agar aur koi madad chahiye toh batayein."), ("Theek hai.", "Accha! Agar aur kuch chahiye toh main hamesha yahan hoon."), ("Good morning!", "Good morning! Hope you're having a great day. How can Sarus help you today?"), ("Good night!", "Good night! Feel free to come back anytime you need help. Take care!"), ("Kuch sikh sakta hoon?", "Bilkul! Main Sarus hoon aur aapko seekhne mein madad karna mujhe bahut accha lagta hai. Kya seekhna chahate hain?"),]
def build_identity(): print("\n[4/5] Identity + Hindi Chat examples...") examples = [] while len(examples) < IDENTITY_TARGET + VAL_IDENTITY: for q, a in IDENTITY_QA: ids, labels = build_simple_example(q, a) if ids is not None: examples.append((ids, labels)) if len(examples) >= IDENTITY_TARGET + VAL_IDENTITY: break
random.shuffle(examples) train = examples[:IDENTITY_TARGET] val = examples[IDENTITY_TARGET:IDENTITY_TARGET + VAL_IDENTITY] print(f" Built: {len(train)} train + {len(val)} val") return train, val
# =========================================================================# SECTION 5 โ DAILY DIALOG (Friendly Chat)# =========================================================================def build_friendly(): print("\n[5/5] DailyDialog โ Friendly Chat examples...") examples = []
try: ds = load_dataset("daily_dialog", split="train", trust_remote_code=True) for conv in tqdm(ds, desc="DailyDialog"): dialog = conv["dialog"] if len(dialog) < 2: continue # Build consecutive pairs from the conversation for i in range(0, len(dialog) - 1, 2): user_text = dialog[i].strip() asst_text = dialog[i + 1].strip() if len(user_text) < 5 or len(asst_text) < 5: continue ids, labels = build_simple_example(user_text, asst_text) if ids is not None: examples.append((ids, labels)) if len(examples) >= FRIENDLY_TARGET + VAL_FRIENDLY: break if len(examples) >= FRIENDLY_TARGET + VAL_FRIENDLY: break except Exception as e: print(f" WARNING: DailyDialog failed: {e}") print(" Using fallback friendly examples...") FALLBACK_FRIENDLY = [ ("How are you doing today?", "I'm doing great, thanks for asking! How about you?"), ("What's your favorite color?", "I don't have personal preferences, but I love helping people! What's yours?"), ("Tell me something interesting.", "Did you know honey never spoils? Archaeologists found 3000-year-old honey in Egyptian tombs that was still edible!"), ("What do you think about AI?", "AI is fascinating! It's rapidly changing how we interact with technology and solve problems."), ("Can we be friends?", "Of course! I'd love to be your AI friend. I'm Sarus, always here for a chat!"), ("Make me laugh!", "Why don't scientists trust atoms? Because they make up everything! ๐"), ("What time is it?", "I don't have access to real-time data, but I'd be happy to help with anything else!"), ("I'm bored.", "Let me help with that! We could play a word game, I can tell you a fun fact, or we can explore any topic you're curious about!"), ("I feel sad today.", "I'm sorry to hear that. Remember, tough times don't last, but tough people do. I'm here if you want to talk!"), ("You're awesome!", "Thank you so much! That really means a lot. You're pretty awesome yourself! ๐"), ] while len(examples) < FRIENDLY_TARGET + VAL_FRIENDLY: for q, a in FALLBACK_FRIENDLY: ids, labels = build_simple_example(q, a) if ids is not None: examples.append((ids, labels)) if len(examples) >= FRIENDLY_TARGET + VAL_FRIENDLY: break
random.shuffle(examples) train = examples[:FRIENDLY_TARGET] val = examples[FRIENDLY_TARGET:FRIENDLY_TARGET + VAL_FRIENDLY] print(f" Built: {len(train)} train + {len(val)} val") return train, val
# =========================================================================# MAIN: BUILD ALL + SAVE + UPLOAD# =========================================================================def pack_and_save(examples, prefix, split): if not examples: print(f" WARNING: No examples for {prefix}_{split}!") return None, None, None
ids_list = [e[0] for e in examples] labels_list = [e[1] for e in examples]
offsets = np.zeros(len(ids_list) + 1, dtype=np.int64) for i, ids in enumerate(ids_list): offsets[i + 1] = offsets[i] + len(ids)
all_ids = np.concatenate(ids_list).astype(np.int32) all_labels = np.concatenate(labels_list).astype(np.int32)
ids_path = os.path.join(OUT_DIR, f"sft_v4_{split}_ids.npy") labels_path = os.path.join(OUT_DIR, f"sft_v4_{split}_labels.npy") offsets_path= os.path.join(OUT_DIR, f"sft_v4_{split}_offsets.npy")
np.save(ids_path, all_ids) np.save(labels_path, all_labels) np.save(offsets_path, offsets)
print(f" Saved {split}: {len(examples)} examples, {len(all_ids):,} tokens") return ids_path, labels_path, offsets_path
def main(): print("=" * 70) print("Sarus 500M (by ViuAI) โ V4 SFT Dataset Builder") print("=" * 70)
# Build all sections trivia_train, trivia_val = build_trivia_search() math_train, math_val = build_math() general_train, general_val = build_general() identity_train, identity_val = build_identity() friendly_train, friendly_val = build_friendly()
# Combine all_train = trivia_train + math_train + general_train + identity_train + friendly_train all_val = trivia_val + math_val + general_val + identity_val + friendly_val
random.shuffle(all_train) random.shuffle(all_val)
print(f"\nTotal: {len(all_train):,} train, {len(all_val):,} val")
# Save print("\nSaving .npy files...") train_ids_path, train_labels_path, train_offsets_path = pack_and_save(all_train, "sft_v4", "train") val_ids_path, val_labels_path, val_offsets_path = pack_and_save(all_val, "sft_v4", "val")
# Upload to HuggingFace print("\nUploading to HuggingFace...") api = HfApi(token=HF_TOKEN) for path, repo_filename in [ (train_ids_path, "sft_v4_train_ids.npy"), (train_labels_path, "sft_v4_train_labels.npy"), (train_offsets_path,"sft_v4_train_offsets.npy"), (val_ids_path, "sft_v4_val_ids.npy"), (val_labels_path, "sft_v4_val_labels.npy"), (val_offsets_path, "sft_v4_val_offsets.npy"), ]: if path is None: continue api.upload_file( path_or_fileobj=path, path_in_repo=repo_filename, repo_id=DATA_REPO, repo_type="dataset", ) print(f" Uploaded: {repo_filename}")
print("\n" + "=" * 70) print("V4 Dataset Build Complete!") print(f" Train: {len(all_train):,} examples") print(f" Val: {len(all_val):,} examples") print(f" Total: {len(all_train) + len(all_val):,} examples") print("=" * 70)
if __name__ == "__main__": main()code/build_sft_data_v4.pyAdded+496