Upload code/build_sft_data_v6.py with huggingface_hub
Browse files1234567891011121314151619 unmodified lines36373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081822 unmodified lines85868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313425 unmodified lines1601611621631641651661679 unmodified lines1771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082093 unmodified lines21321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733810 unmodified lines349350351352353354355356357358359360361362"""Sarus 500M (by ViuAI) — SFT Dataset Builder V6============================================================Fixes:1. Replaces trivia RAG with dynamic open-ended queries (news, prices).2. Generates realistic, messy DDG search results (Title, URL, Snippet).3. Completely fixes identity overfitting by generating 2000+ unique variations (Eng, Hin, Hinglish).4. Limits companion repetition to avoid overfitting."""import osimport randomimport numpy as npfrom datasets import load_datasetfrom tqdm import tqdmfrom transformers import PreTrainedTokenizerFast19 unmodified linestokenizer.add_tokens(["<|user|>", "<|assistant|>", "<|endofturn|>", "[THINK]", "[/THINK]", "<search>", "</search>", "<search_result>", "</search_result>"], special_tokens=True)print(f"Vocab size: {len(tokenizer)}")# =========================================================================# MASKING HELPERS# =========================================================================def build_simple_example(user_text, assistant_text):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)if len(ids) > 2048: return None, Nonelabels = [-100] * n_prefix + ids[n_prefix:]return np.array(ids, dtype=np.int32), np.array(labels, dtype=np.int32)def build_search_example(user_text, search_query, search_result_text, final_answer):part1 = f"<|user|>\n{user_text}<|endofturn|>\n<|assistant|>\n<search>{search_query}</search>"part2 = f"\n<search_result>\n{search_result_text}\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)user_prompt = f"<|user|>\n{user_text}<|endofturn|>\n<|assistant|>\n"n_user = len(tokenizer.encode(user_prompt, add_special_tokens=False))all_ids = ids1 + ids2 + ids3if len(all_ids) > 2048: return None, Nonelabels1 = [-100] * n_user + ids1[n_user:]labels2 = [-100] * len(ids2)labels3 = ids3.copy()all_labels = labels1 + labels2 + labels3return np.array(all_ids, dtype=np.int32), np.array(all_labels, dtype=np.int32)# =========================================================================# 1. RAG SEARCH DATA (Dynamic Queries & Messy DDG Template)# =========================================================================def build_rag():print("\n[1/5] Building RAG Data (5,000 examples)...")examples = []queries = [2 unmodified lines"spacex latest launch", "pm modi latest speech", "current stock price of reliance","new phone releases 2026", "what is happening in the world", "today india news"]# Use SQuAD / TriviaQA but format them like open-ended DDG resultstry:ds = load_dataset("squad_v2", split="train", trust_remote_code=True)for row in tqdm(ds.select(range(5000)), desc="RAG DDG"):context = row["context"].strip()ans = row["answers"]["text"][0] if len(row["answers"]["text"]) > 0 else "Based on the results, I couldn't find a definitive answer."user_query = row["question"].strip()search_q = user_query# Build Messy DDG Result format (Bug #2 Fix)domain = random.choice(["news.com", "timesofindia.com", "techcrunch.com", "wikipedia.org"])ddg_result = (f"1. {user_query.title()} - Latest Updates\n"f"https://www.{domain}/article/{random.randint(1000,9999)}\n"f"{context[:300]}...\n\n"f"2. More info on {user_query}\n"f"https://www.{domain}/more-info\n"f"{context[300:500]}...")# Inject [THINK] block to teach reasoning over search resultsfinal_answer = (f"[THINK]\nI need to analyze the search results for '{search_q}'. "f"The results mention relevant context. I will synthesize this into a helpful response.\n[/THINK]\n"f"{ans}")ids, labels = build_search_example(user_query, search_q, ddg_result, final_answer)if ids is not None: examples.append((ids, labels))random.shuffle(examples)return examples[:4500], examples[4500:5000]except Exception as e:print(f" WARNING: {e}")return [], []# =========================================================================# 2. SARUS IDENTITY INJECTION (Dynamic Template Generation)# =========================================================================def build_identity():print("\n[2/5] Building Identity (2,000 unique examples)...")examples = []eng_q = ["Who are you?", "What is your name?", "Who created you?", "Tell me about yourself.", "Are you a human?", "Who built you?", "Identify yourself.", "What should I call you?", "Your name?", "May I know your name?", "Who am I speaking with?", "Are you a bot?", "What are you?", "Introduce yourself.", "Who is your maker?", "Who developed you?", "Which company made you?", "Are you ChatGPT?", "Are you from OpenAI?", "Who programmed you?"]25 unmodified lines"Aap mera naam Sarus jaan sakte hain, mujhe ViuAI ne code kiya hai."]# Generate 2000 UNIQUE variations (Bug #3 Fix)for _ in range(2100):lang = random.choice(["eng", "hin", "hing"])if lang == "eng":q = random.choice(eng_q)9 unmodified lines"The user wants to know who I am. I am Sarus, developed by the ViuAI team.","I should politely clarify that I am an AI named Sarus, created by ViuAI.","Let me confirm my identity: Sarus, a smart companion by ViuAI.","This query is about my origins. I will state I am Sarus from ViuAI.","I need to tell the user my name is Sarus and my developer is ViuAI.","The prompt asks for my name. I am Sarus, built by ViuAI.","Identity inquiry detected. My response should confirm I am Sarus by ViuAI.","I must clarify that I am an AI assistant named Sarus, created by ViuAI.","The user is curious about my background. I'm Sarus, developed by ViuAI.","Let me introduce myself properly as Sarus, an AI from ViuAI."]think_str = f"[THINK]\n{random.choice(id_thinks)}\n[/THINK]\n"# 50% chance to include a thought process for identityif random.random() > 0.5:a = think_str + aids, labels = build_simple_example(q, a)if ids is not None: examples.append((ids, labels))random.shuffle(examples)return examples[:1900], examples[1900:2100]# =========================================================================# 3. EMPATHETIC DIALOGUES & HINGLISH COMPANION (Balanced)# =========================================================================def build_empathetic():print("\n[3/5] Empathetic Dialogues (15,000 examples)...")examples = []# 1. Custom Hinglish (Unique without 2000x loops) (Bug #4 Fix)hinglish_pairs = [("Bhai kaisa hai?", "Main ekdum badhiya! Aap batao, kya chal raha hai aaj?"),("Kuch samajh nahi aa raha yaar", "Koi baat nahi, mujhe batao kya dikkat hai, hum milkar solve karenge."),3 unmodified lines("Thanks yaar", "Arre isme kya! Main hamesha yahin hoon aapki madad ke liye."),("Aur batao", "Bas sab badhiya! Main toh naye naye facts seekh raha hoon. Aapne aaj kya kiya?")]# Add them a FEW times only (e.g. 50 times each max = 350 total), not 2000!for _ in range(50):for q, a in hinglish_pairs:ids, labels = build_simple_example(q, a)if ids is not None: examples.append((ids, labels))# 2. English Empathetictry:ds = load_dataset("empathetic_dialogues", split="train", trust_remote_code=True)for row in tqdm(ds.select(range(14500)), desc="Empathetic"):q, a = row["prompt"].strip(), row["utterance"].strip()ids, labels = build_simple_example(q, a)if ids is not None: examples.append((ids, labels))except Exception as e: print(f" WARNING: {e}")random.shuffle(examples)return examples[:14000], examples[14000:15000]# =========================================================================# 4. GENERAL CHAT (15,000)# =========================================================================def build_general():print("\n[4/5] General Chat (15,000 examples)...")examples = []try:ds = load_dataset("databricks/databricks-dolly-15k", split="train", trust_remote_code=True)for row in tqdm(ds.select(range(15750)), desc="Dolly"):q = row["instruction"].strip()if row.get("input", "").strip(): q += "\n" + row["input"].strip()a = row["response"].strip()ids, labels = build_simple_example(q, a)if ids is not None: examples.append((ids, labels))except Exception as e: print(f" WARNING: {e}")train, val = examples[:15000], examples[15000:15750]return train, val# =========================================================================# 5. INTENT-THINKING (Diverse Alpaca) (10,000)# =========================================================================def build_thinking():print("\n[5/5] Diverse Thinking Dataset (10,000 examples)...")examples = []try:ds = load_dataset("yahma/alpaca-cleaned", split="train", trust_remote_code=True)for row in tqdm(ds.select(range(10500)), desc="Alpaca-Think"):q = row["instruction"].strip()if row.get("input", "").strip(): q += "\n" + row["input"].strip()ans = row["output"].strip()# Programmatically inject a thought based on the question (Bug #3 Fix)# This teaches the model to think before ANY complex question, not just identity!think_str = random.choice(["I need to answer the user's prompt carefully and provide an accurate response.","The user is asking a question. Let me retrieve the best possible information.","I should analyze the request and provide a clear, concise answer.","Let me think about how to best address this instruction.","I will formulate a response that directly answers the user's query.","To answer this correctly, I need to consider the context.","I should break down the user's prompt and provide a detailed explanation.","This requires a thoughtful reply. Let me compose my thoughts.","I will provide a direct and helpful answer to this.","Let me ensure my answer is factual and easy to understand.","I must focus on delivering exactly what the user is asking for.","Let me structure my response so it is logical and informative.","I should review the prompt and construct a comprehensive answer.","The best approach here is to be direct and concise.","Let me gather my knowledge on this topic and respond appropriately.","I need to provide a high-quality response to this query.","Let's tackle this step-by-step for clarity.","I will ensure my tone is helpful and my facts are correct.","This prompt requires a detailed response. Let me plan my answer.","I should formulate a clear and accurate reply.","My goal is to be as helpful as possible here.","Let me evaluate the question and synthesize an answer.","I will respond with precision and clarity.","To provide a good answer, I need to be thorough.","Let me craft a response that directly addresses the user's intent.","I should make sure I am fully answering the prompt.","Let me quickly process this and generate a useful reply.","I need to be informative and polite in my answer.","Let me organize the facts before presenting them.","I will deliver a straight-to-the-point answer.","I should explain this concept clearly.","Let me structure the information for easy reading.","I will provide the necessary details without overcomplicating it.","Let me make sure I don't miss any part of the user's question.","I should respond comprehensively.","Let me outline the key points before answering.","I will give a factual and precise explanation.","To respond effectively, I need to be focused.","Let me deliver exactly what was requested.","I should write a well-thought-out response.","Let me present this information clearly.","I will address the prompt directly.","Let me compose a thorough and helpful answer.","I need to be accurate and concise.","Let me ensure my explanation is clear.","I will answer this to the best of my ability.","Let me think through the logical flow of this answer.","I should be clear and helpful.","Let me prepare a precise response.","I will construct an informative answer.","This is an interesting query, I will address it step-by-step.","Let me analyze the prompt before generating the output."])asst_text = f"[THINK]\n{think_str}\n[/THINK]\n{ans}"ids, labels = build_simple_example(q, asst_text)if ids is not None: examples.append((ids, labels))except Exception as e: print(f" WARNING: {e}")train, val = examples[:10000], examples[10000:10500]return train, val# =========================================================================# COMPILE AND SAVE# =========================================================================def main():print("🚀 Starting V6 SFT Data Build (Zero-Duplication, OOD Fixes)")t1, v1 = build_rag()t2, v2 = build_identity()t3, v3 = build_empathetic()10 unmodified linesdef pack_and_save(examples, prefix, split):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)all_labels = np.concatenate(labels_list)np.save(f"{OUT_DIR}/{prefix}_{split}_ids.npy", all_ids)np.save(f"{OUT_DIR}/{prefix}_{split}_labels.npy", all_labels)np.save(f"{OUT_DIR}/{prefix}_{split}_offsets.npy", offsets)pack_and_save(train_all, "sft_v6", "train")pack_and_save(val_all, "sft_v6", "val")123456789101112131415161718192019 unmodified lines4041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191202 unmodified lines12312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323425 unmodified lines2602612622632642652669 unmodified lines2762772782792802812822832842852862872882892902912922932942952962972982993003 unmodified lines30430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139210 unmodified lines403404405406407408409410411412413414415416417418419420421422"""Sarus 500M (by ViuAI) — SFT Dataset Builder V6.1============================================================Fixes:1. Replaces trivia RAG with dynamic open-ended queries (news, prices) & 3-result DDG format.2. Long Thinking (80-120 words) & Detailed Synthesis (150+ words) for RAG.3. RAG Fallbacks for empty searches.4. Tokenizer parity check.5. Exact 60k balancing & Stratified Validation.6. Saves category tags for loss weighting.7. System prompt format variations (20%)."""import osimport randomimport numpy as npfrom datetime import datetimefrom datasets import load_datasetfrom tqdm import tqdmfrom transformers import PreTrainedTokenizerFast19 unmodified linestokenizer.add_tokens(["<|user|>", "<|assistant|>", "<|endofturn|>", "[THINK]", "[/THINK]", "<search>", "</search>", "<search_result>", "</search_result>"], special_tokens=True)print(f"Vocab size: {len(tokenizer)}")# Tokenizer sanity checktry:chk_path = "../tokenizer/tokenizer.json"if os.path.exists(chk_path):tok_chk = PreTrainedTokenizerFast(tokenizer_file=chk_path)tok_chk.add_tokens(["<|user|>", "<|assistant|>", "<|endofturn|>", "[THINK]", "[/THINK]", "<search>", "</search>", "<search_result>", "</search_result>"], special_tokens=True)assert len(tokenizer) == len(tok_chk), "Tokenizer vocab size mismatch!"test_str = "hello [THINK] </search>"assert tokenizer.encode(test_str) == tok_chk.encode(test_str), "Tokenizer encode mismatch!"print("✅ Tokenizer parity check passed.")except Exception as e:print(f"⚠️ Tokenizer check skipped or failed: {e}")# =========================================================================# MASKING HELPERS# =========================================================================def get_prompt_format(user_text, style_idx):if style_idx == 0:return f"<|user|>\n{user_text}<|endofturn|>\n<|assistant|>\n"elif style_idx == 1:return f"System: You are helpful assistant.\nUser: {user_text}\nAssistant:\n"else:return f"User: {user_text}\nAssistant:\n"def build_simple_example(user_text, assistant_text, category):style_rand = random.random()if style_rand < 0.1: style_idx = 1elif style_rand < 0.2: style_idx = 2else: style_idx = 0prefix = get_prompt_format(user_text, style_idx)full = prefix + assistant_text + ("<|endofturn|>\n" if style_idx == 0 else "\n")ids = tokenizer.encode(full, add_special_tokens=False)prefix_ids = tokenizer.encode(prefix, add_special_tokens=False)n_prefix = len(prefix_ids)if len(ids) > 2048: return Nonelabels = [-100] * n_prefix + ids[n_prefix:]return (np.array(ids, dtype=np.int32), np.array(labels, dtype=np.int32), category)def build_search_example(user_text, search_query, search_result_text, final_answer, category):style_rand = random.random()if style_rand < 0.1: style_idx = 1elif style_rand < 0.2: style_idx = 2else: style_idx = 0prefix = get_prompt_format(user_text, style_idx)part1 = f"{prefix}<search>{search_query}</search>"part2 = f"\n<search_result>\n{search_result_text}\n</search_result>\n"part3 = f"{final_answer}" + ("<|endofturn|>\n" if style_idx == 0 else "\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)n_user = len(tokenizer.encode(prefix, add_special_tokens=False))all_ids = ids1 + ids2 + ids3if len(all_ids) > 2048: return Nonelabels1 = [-100] * n_user + ids1[n_user:]labels2 = [-100] * len(ids2)labels3 = ids3.copy()all_labels = labels1 + labels2 + labels3return (np.array(all_ids, dtype=np.int32), np.array(all_labels, dtype=np.int32), category)# =========================================================================# 1. RAG SEARCH DATA (Dynamic Queries & Messy DDG Template)# =========================================================================def build_rag():print("\n[1/5] Building RAG Data (8,000 examples)...")examples = []queries = [2 unmodified lines"spacex latest launch", "pm modi latest speech", "current stock price of reliance","new phone releases 2026", "what is happening in the world", "today india news"]hi_queries = ["aaj ki khabar", "news batao", "cricket score aaj ka", "bharat ki taja khabar", "aaj mausam kaisa hai"]try:ds = load_dataset("squad_v2", split="train", trust_remote_code=True)# We need 8000 examples. 500 will be empty fallbacks.# We will use 7500 real ones.for idx, row in enumerate(tqdm(ds.select(range(7500)), desc="RAG DDG")):context = row["context"].strip()# 50% use synthetic news queries, 50% use factual squad queriesis_news = random.random() < 0.5is_hindi = Falseif is_news:if random.random() < 0.3:user_query = random.choice(hi_queries)is_hindi = Trueelse:user_query = random.choice(queries)else:user_query = row["question"].strip()search_q = user_querytitle1 = f"Latest on {search_q[:20]}"title2 = f"More info for {search_q[:20]}"title3 = f"Updates: {search_q[:20]}"today = datetime.now().strftime("%d %B %Y")# Format explicitly 3 resultsddg_result = (f"[Today: {today}] Results:\n"f"1. {title1}: {context[:150]}\n"f"2. {title2}: {context[150:300]}\n"f"3. {title3}: {context[300:450]}")lang_detect = "Hindi/Hinglish" if is_hindi else "English"think_str = (f"[THINK]\nUser query: '{search_q}'. Analyzing 3 search results:\n"f"- R1: {title1} - {context[:50]}...\n"f"- R2: {title2} - {context[150:200]}...\n"f"- R3: {title3} - {context[300:350]}...\n"f"Language detection: Query is {lang_detect} so answer should be in {lang_detect}.\n"f"Plan: Combine results, remove duplicates, avoid hallucination beyond results, add [Today: {today}], structure into 2-3 paragraphs, give full details with citations.\n[/THINK]\n")# Detailed synthesisif is_hindi:ans_body = (f"Aaj ke search results [Today: {today}] ke mutabiq, yahan kuch mukhy baatein hain:\n"f"1. Result 1 ke anusaar, {context[:100]}...\n"f"2. Result 2 ke mutabiq aur bhi details hain jaise ki {context[150:250]}...\n"f"3. Result 3 batata hai ki {context[300:400]}...\n\n"f"Summary: In sabhi sources ko dekh kar, hum keh sakte hain ki {search_q} ke baare mein taza jankari yahi bata rahi hai ki situation aage badh rahi hai aur nayi updates aati rahengi. Mujhe ummeed hai ye aapke liye helpful hoga!")else:ans_body = (f"Based on today's results [Today: {today}], here are the detailed findings:\n"f"1. According to Result 1, {context[:100]}...\n"f"2. From Result 2, we can see additional details such as {context[150:250]}...\n"f"3. Result 3 highlights that {context[300:400]}...\n\n"f"Summary: Synthesizing these three sources, it is evident that the situation regarding '{search_q}' involves multiple facets. The sources agree on the general premise but provide different granular details. I hope this detailed breakdown helps answer your query comprehensively!")final_answer = think_str + ans_bodyex = build_search_example(user_query, search_q, ddg_result, final_answer, "rag")if ex: examples.append(ex)# Empty Fallbacks (500)for _ in range(500):user_query = random.choice(queries + hi_queries)is_hindi = user_query in hi_queriestoday = datetime.now().strftime("%d %B %Y")ddg_result = f"[Today: {today}] Results:\nNo relevant results found."lang_detect = "Hindi/Hinglish" if is_hindi else "English"think_str = (f"[THINK]\nUser query: '{user_query}'. Analyzing search results:\n"f"Results returned empty. No relevant information found via DuckDuckGo.\n"f"Language detection: Query is {lang_detect} so answer should be in {lang_detect}.\n"f"Plan: I must gracefully inform the user that the search failed and I cannot find exact live info, to avoid hallucination.\n[/THINK]\n")if is_hindi:ans_body = "Main search results mein iski exact jankari nahi dhoondh paya, par meri knowledge ke anusaar yeh ek complex topic ho sakta hai. Agar aap thodi aur detail de sakein toh shayad main behtar search kar saku."else:ans_body = "I couldn't find exact information for this in the live search results. Based on my general knowledge, there might not be any breaking updates on this right now. Could you provide a bit more context so I can try another search?"final_answer = think_str + ans_bodyex = build_search_example(user_query, user_query, ddg_result, final_answer, "rag")if ex: examples.append(ex)random.shuffle(examples)return examples[:7600], examples[7600:8000] # 400 valexcept Exception as e:print(f" WARNING RAG: {e}")return [], []# =========================================================================# 2. SARUS IDENTITY INJECTION# =========================================================================def build_identity():print("\n[2/5] Building Identity (1,000 examples)...")examples = []eng_q = ["Who are you?", "What is your name?", "Who created you?", "Tell me about yourself.", "Are you a human?", "Who built you?", "Identify yourself.", "What should I call you?", "Your name?", "May I know your name?", "Who am I speaking with?", "Are you a bot?", "What are you?", "Introduce yourself.", "Who is your maker?", "Who developed you?", "Which company made you?", "Are you ChatGPT?", "Are you from OpenAI?", "Who programmed you?"]25 unmodified lines"Aap mera naam Sarus jaan sakte hain, mujhe ViuAI ne code kiya hai."]for _ in range(1100):lang = random.choice(["eng", "hin", "hing"])if lang == "eng":q = random.choice(eng_q)9 unmodified lines"The user wants to know who I am. I am Sarus, developed by the ViuAI team.","I should politely clarify that I am an AI named Sarus, created by ViuAI.","Let me confirm my identity: Sarus, a smart companion by ViuAI.","This query is about my origins. I will state I am Sarus from ViuAI."]think_str = f"[THINK]\n{random.choice(id_thinks)}\n[/THINK]\n"if random.random() > 0.5:a = think_str + aex = build_simple_example(q, a, "identity")if ex: examples.append(ex)random.shuffle(examples)return examples[:950], examples[950:1000] # 50 val# =========================================================================# 3. EMPATHETIC DIALOGUES# =========================================================================def build_empathetic():print("\n[3/5] Empathetic Dialogues (18,000 examples)...")examples = []hinglish_pairs = [("Bhai kaisa hai?", "Main ekdum badhiya! Aap batao, kya chal raha hai aaj?"),("Kuch samajh nahi aa raha yaar", "Koi baat nahi, mujhe batao kya dikkat hai, hum milkar solve karenge."),3 unmodified lines("Thanks yaar", "Arre isme kya! Main hamesha yahin hoon aapki madad ke liye."),("Aur batao", "Bas sab badhiya! Main toh naye naye facts seekh raha hoon. Aapne aaj kya kiya?")]for _ in range(100):for q, a in hinglish_pairs:ex = build_simple_example(q, a, "empathetic")if ex: examples.append(ex)try:ds = load_dataset("empathetic_dialogues", split="train", trust_remote_code=True)for row in tqdm(ds.select(range(18000)), desc="Empathetic"):q, a = row["prompt"].strip(), row["utterance"].strip()ex = build_simple_example(q, a, "empathetic")if ex: examples.append(ex)except Exception as e: print(f" WARNING: {e}")random.shuffle(examples)return examples[:17100], examples[17100:18000] # 900 val# =========================================================================# 4. GENERAL CHAT (18,000)# =========================================================================def build_general():print("\n[4/5] General Chat (18,000 examples)...")examples = []try:ds = load_dataset("databricks/databricks-dolly-15k", split="train", trust_remote_code=True)# Duplicate to reach 18kpool = list(ds)pool = pool + pool[:4000]for row in tqdm(pool[:19000], desc="Dolly"):q = row["instruction"].strip()if row.get("input", "").strip(): q += "\n" + row["input"].strip()a = row["response"].strip()ex = build_simple_example(q, a, "general")if ex: examples.append(ex)except Exception as e: print(f" WARNING: {e}")random.shuffle(examples)return examples[:17100], examples[17100:18000] # 900 val# =========================================================================# 5. INTENT-THINKING (Diverse Alpaca) (15,000)# =========================================================================def build_thinking():print("\n[5/5] Diverse Thinking Dataset (15,000 examples)...")examples = []try:ds = load_dataset("yahma/alpaca-cleaned", split="train", trust_remote_code=True)for row in tqdm(ds.select(range(16000)), desc="Alpaca-Think"):q = row["instruction"].strip()if row.get("input", "").strip(): q += "\n" + row["input"].strip()ans = row["output"].strip()# Long Thinking for general prompts (60-80 words)think_parts = ["I need to carefully evaluate this request.",f"The user is asking to process: '{q[:30]}...'.","First, I should break down the core instruction.","Let me consider the constraints and necessary steps.","Step 1: Identify the key entities and the required format.","Step 2: Retrieve any relevant internal knowledge.","Step 3: Draft a response that is logically structured.","I must ensure that my tone is helpful, polite, and directly addresses the prompt.","This seems straightforward, but I will double check my logic.","Let's finalize the answer structure before generating the final output."]random.shuffle(think_parts)think_str = f"[THINK]\n{' '.join(think_parts[:7])}\n[/THINK]\n"asst_text = think_str + ansex = build_simple_example(q, asst_text, "thinking")if ex: examples.append(ex)except Exception as e: print(f" WARNING: {e}")random.shuffle(examples)return examples[:14250], examples[14250:15000] # 750 val# =========================================================================# COMPILE AND SAVE# =========================================================================def main():print("🚀 Starting V6.1 SFT Data Build")t1, v1 = build_rag()t2, v2 = build_identity()t3, v3 = build_empathetic()10 unmodified linesdef pack_and_save(examples, prefix, split):ids_list = [e[0] for e in examples]labels_list = [e[1] for e in examples]cat_list = [e[2] 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)all_labels = np.concatenate(labels_list)all_cats = np.array(cat_list, dtype=str)np.save(f"{OUT_DIR}/{prefix}_{split}_ids.npy", all_ids)np.save(f"{OUT_DIR}/{prefix}_{split}_labels.npy", all_labels)np.save(f"{OUT_DIR}/{prefix}_{split}_offsets.npy", offsets)np.save(f"{OUT_DIR}/{prefix}_{split}_categories.npy", all_cats)pack_and_save(train_all, "sft_v6", "train")pack_and_save(val_all, "sft_v6", "val")
code/build_sft_data_v6.py+198-138