Feature: Smart Near-Duplicate Deduplication + Indian Colloquial & Slang Grounding
Browse files85 unmodified lines86878889909114 unmodified lines10610710810911011111254 unmodified lines1671681691701711728 unmodified lines18118218318418518618718830 unmodified lines21922022122222322422510 unmodified lines23623723823924024124224324424524618 unmodified lines26526626726826927027110 unmodified lines28228328428528628728826 unmodified lines31531631731831932032110 unmodified lines3323333343353363373387 unmodified lines34634734834935035135214 unmodified lines36736836937037137237312 unmodified lines38638738838939039139267 unmodified lines46046146246346446546646746846947085 unmodified linesreturn text.strip()def format_qa(instruction: str, response: str, thinking: str = ""):inst = clean_text(instruction)resp = clean_text(response)14 unmodified lineselse:resp_str = f"{resp}{EOT_TOKEN}"return prompt_str, resp_strdef main():54 unmodified linestotal_train_tokens_count = 0total_val_tokens_count = 0collected = 0def flush_buffers():nonlocal buf_tr_tok, buf_tr_lab, buf_val_tok, buf_val_lab8 unmodified linesbuf_val_tok.clear()buf_val_lab.clear()def add_pair(prompt_str, resp_str, domain_id):nonlocal collected, total_train_tokens_count, total_val_tokens_countp_ids = tokenizer.encode(prompt_str).idsr_ids = tokenizer.encode(resp_str).ids30 unmodified linesflush_buffers()if collected % 100_000 == 0:print(f" ⚡ Disk-Streamed: {collected:,} clean samples | Train Tokens: {total_train_tokens_count:,} (RAM Safe: <300MB)")sys.stdout.flush()return True10 unmodified lineswith open(fp, "r", encoding="utf-8") as f:for it in json.load(f):pair = format_qa(it.get("instruction", ""), it.get("response", ""))if pair and add_pair(pair[0], pair[1], did):p1 += 1print(f" ✅ Pillar 1 Ready: {p1:,} samples.")sys.stdout.flush()# --------------------------------------------------------------------------# Pillar 2: STEM, Math & Physics Reasoning (<thought> inner monologue)# --------------------------------------------------------------------------18 unmodified linesresp = a_partpair = format_qa(u_part, resp, thought)if pair and add_pair(pair[0], pair[1], 2):p2 += 1except Exception as e:print(f" ⚠️ STEM streaming: {e}")10 unmodified linesds_chat = load_dataset("Abhishekcr448/Hinglish-Everyday-Conversations-1M", split="train", streaming=True, token=HF_TOKEN)for it in ds_chat:pair = format_qa(it.get("input", ""), it.get("output", ""))if pair and add_pair(pair[0], pair[1], 3):p3 += 1except Exception as e:print(f" ⚠️ Hinglish chat streaming: {e}")26 unmodified linesinst, resp = random.choice(trans_templates[2:]).format(hi=hi), enpair = format_qa(inst, resp)if pair and add_pair(pair[0], pair[1], 4):p4 += 1except Exception as e:print(f" ⚠️ Translation streaming: {e}")10 unmodified linesds_dsm = load_dataset("DSMJ910/hinglish-instruct-10k", split="train", streaming=True, token=HF_TOKEN)for it in ds_dsm:pair = format_qa(it.get("user_message", ""), it.get("assistant_response", ""))if pair and add_pair(pair[0], pair[1], 5):p5 += 1except Exception as e:print(f" ⚠️ DSMJ910: {e}")7 unmodified linesconvs = ast.literal_eval(convs_raw) if isinstance(convs_raw, str) else convs_rawif len(convs) >= 2:pair = format_qa(convs[0].get("value", ""), convs[1].get("value", ""))if pair and add_pair(pair[0], pair[1], 5):p5 += 1except Exception:continue14 unmodified linesmessages = it.get("messages", [])if len(messages) >= 2:pair = format_qa(messages[0].get("content", ""), messages[1].get("content", ""))if pair and add_pair(pair[0], pair[1], 6):p6 += 1except Exception as e:print(f" ⚠️ UltraChat: {e}")12 unmodified linesmessages = it.get("messages", [])if len(messages) >= 2:pair = format_qa(messages[0].get("content", ""), messages[1].get("content", ""))if pair and add_pair(pair[0], pair[1], 7):p7 += 1except Exception as e:print(f" ⚠️ SmolTalk: {e}")67 unmodified linesmetadata = {"dataset_name": f"Sarus_SFT_v2_Master_Uncapped_{collected//1000}k","total_samples": collected,"train_samples": total_train,"val_samples": total_val,"train_tokens": total_train_tokens_count,"val_tokens": total_val_tokens_count,"max_seq_len": MAX_SEQ_LEN,"thinking_mode": "Adaptive (Short 30-60 token thinking on STEM/Math, Direct on Chat/Mails)","refusal_policy": "Strict Zero Refusals (Canned AI preachiness dropped)","language_gate": "100% Roman Alphabet (Zero Devanagari)"85 unmodified lines868788899091929394959697989910010110210310414 unmodified lines11912012112212312412554 unmodified lines1801811821831841851861878 unmodified lines19619719819920020120220320420520620720820921021121221321421521621730 unmodified lines24824925025125225325410 unmodified lines26526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533618 unmodified lines35535635735835936036110 unmodified lines37237337437537637737826 unmodified lines40540640740840941041110 unmodified lines4224234244254264274287 unmodified lines43643743843944044144214 unmodified lines45745845946046146246312 unmodified lines47647747847948048148267 unmodified lines55055155255355455555655755855956056156256385 unmodified linesreturn text.strip()def normalize_for_dedup(text: str) -> str:"""Normalize text for smart near-duplicate detection.Strips punctuation, collapses extra whitespace, and converts to lowercase.Preserves colloquial word variations while eliminating redundant copies."""if not text:return ""t = text.lower()t = re.sub(r"[^\w\s]", "", t)t = re.sub(r"\s+", " ", t).strip()return tdef format_qa(instruction: str, response: str, thinking: str = ""):inst = clean_text(instruction)resp = clean_text(response)14 unmodified lineselse:resp_str = f"{resp}{EOT_TOKEN}"return prompt_str, resp_str, instdef main():54 unmodified linestotal_train_tokens_count = 0total_val_tokens_count = 0collected = 0seen_prompt_hashes = set()dedup_dropped = 0def flush_buffers():nonlocal buf_tr_tok, buf_tr_lab, buf_val_tok, buf_val_lab8 unmodified linesbuf_val_tok.clear()buf_val_lab.clear()def add_pair(prompt_str, resp_str, domain_id, raw_instruction=""):nonlocal collected, total_train_tokens_count, total_val_tokens_count, dedup_dropped# Smart Near-Duplicate Deduplication Filter:# Normalized 64-bit hash strips punctuation, excess spaces & lowercase.# Drops redundant duplicates (e.g. 5,000 identical greetings) while# preserving colloquial slang vs formal grammatical variations!if raw_instruction:norm_inst = normalize_for_dedup(raw_instruction)if norm_inst:h = hash(norm_inst)if h in seen_prompt_hashes:dedup_dropped += 1return Falseseen_prompt_hashes.add(h)p_ids = tokenizer.encode(prompt_str).idsr_ids = tokenizer.encode(resp_str).ids30 unmodified linesflush_buffers()if collected % 100_000 == 0:print(f" ⚡ Disk-Streamed: {collected:,} clean samples | Skipped Near-Duplicates: {dedup_dropped:,} | Train Tokens: {total_train_tokens_count:,} (RAM Safe: <350MB)")sys.stdout.flush()return True10 unmodified lineswith open(fp, "r", encoding="utf-8") as f:for it in json.load(f):pair = format_qa(it.get("instruction", ""), it.get("response", ""))if pair and add_pair(pair[0], pair[1], did, pair[2]):p1 += 1print(f" ✅ Pillar 1 Ready: {p1:,} samples.")sys.stdout.flush()# --------------------------------------------------------------------------# Pillar 1.5: Indian Spoken Colloquial, Slang & Intent Equivalence Anchors# --------------------------------------------------------------------------# Bridges the gap between textbook grammar and everyday spoken colloquial Hinglish.# Teaches the model slangs ("code fat gya", "jugaad", "scene kya h", "error fek rha h"),# shorthands ("smjh", "ni", "nhi", "yr", "btado", "plz"), and intent alignment!print("\n🔹 [1.5/7] Packing Indian Spoken Colloquial & Slang Anchors...")sys.stdout.flush()colloquial_anchors = [# Coding & Debugging in everyday spoken Hinglish("bhai code fat gya dekh na syntax error fek rha h","Arre tension mat lo bhai! Code snippet aur terminal ka exact error message share karo, hum milke abhi debug karte hain ki syntax me kahan gadbad hai."),("api hit ni ho rhi 500 error aa rha h kya kru yr","500 Internal Server Error ka matlab backend server crash ho gaya hai. Backend terminal ya console logs check karo ki kis line par exception throw hua hai. Routing aur environment variables bhi verify karo bhai."),("python me list comprehension ka easy jugaad btao","Bilkul bhai! Python me list comprehension bohot simple aur fast hota hai: `squares = [x**2 for x in range(10) if x % 2 == 0]`. Isse lambe for-loop ki zaroorat nahi padti aur code ek line me clean dikhta hai!"),("bhai loop fas gya infinite chal rha h kaise roke","Pehle terminal me Ctrl + C dabakar process kill karo. Fir code me check karo ki loop variable increment (i += 1) ho raha hai ya nahi aur termination condition reach ho rahi hai ya nahi."),("django vs fastapi me kya pick kru yr confuse hu","Bhai agar heavy admin panel, user auth aur built-in ORM chahiye to Django best hai. Lekin agar microservice, fast REST APIs aur async speed chahiye to FastAPI pick karo!"),("git merge conflict aa gya kaise fix kru","Bhai chill karo! Pehle git status chalao, conflicted file open karo jahan `<<<<<<< HEAD` markers lage hain. Apna final code finalize karke markers delete karo, fir `git add .` aur `git commit` kar do. Sorted!"),("sql query me fas gya hu join kaise lgana h","Table structure batao bhai! Matching rows ke liye `INNER JOIN` use karo, aur agar left table ka saara data chahiye chahe match ho ya na ho to `LEFT JOIN` lgao."),("docker container baar baar restart ho rha h kya scene h","Bhai `docker logs <container_id>` run karo. Usually container turant exit tab hota hai jab entrypoint script fail ho jati hai ya koi foreground process nahi hoti."),# Casual & Daily Indian Slangs & Shorthands("aaj ka kya scene h bro","Bas sab badhiya bhai! Aap batao, aaj kis project ya topic par kaam karna hai? Main poori tarah ready hoon!"),("kuch smjh ni aara yr padhai start kaise kru","Overthinking mat karo bhai! Sabse pehle ek chota aur easy topic select karo, phone ko DND par daalo aur 25 minutes ka timer laga kar focus mode me padho. Choti shuruat se momentum banta hai."),("yr ek leave application draft kr do boss k liye tabiyat theek ni h","Ye lijiye bhai, ek clean aur professional sick leave application:\n\nSubject: Sick Leave Application - [Your Name]\n\nDear [Manager's Name],\n\nI am writing to inform you that I am unwell today and will not be able to attend work. I will keep you updated on my recovery and ensure urgent tasks are addressed. Thank you for understanding.\n\nWarm regards,\n[Your Name]"),("bhai ye model phone me offline chalega kya","Haan bhai! ViuAI Sarus-500M ko 4-bit GGUF quantize karke llama.cpp ya MLC LLM ke through Android phone par bina internet ke 100% offline super fast run kar sakte ho!"),("kuch jugaad btao na yr","Bhai exact problem batao, har technical problem ka smart aur solid jugaad nikalte hain!"),("bta na yr kaise kru","Bhai step-by-step batata hoon, batao kahan se start karna hai!"),("mujhe machine learning sikhna h roadmap do bro","Bhai solid 4-step roadmap ye raha: 1. Python & NumPy/Pandas, 2. Math (Linear Algebra & Calculus basics), 3. Scikit-Learn (Linear Regression, Decision Trees), 4. Deep Learning (PyTorch & Transformers). Har step par chote projects banao!"),# Formal vs Colloquial Intent Bridges("Kripya mujhe binary search ka siddhant samjhayein.","Binary Search ek efficient algorithm hai jo sorted list me kisi element ko dhoondhne ke liye har step par search space ko aada (half) kar deta hai. Iski time complexity O(log n) hoti hai."),("bhai binary search ka logic simple bhasha me bta de","Bhai simple example: Jaise dictionary me word dhoondhte waqt aap direct beech ka page kholte ho. Agar word aage hai to pehla aada hissa chhod dete ho. Har step me list aadhi hoti jati hai! Isi ko Binary Search bolte hain O(log n)."),("line pe solder bridging ka issue aa rha h stencil check kre kya","Haan bhai! Solder bridging ke liye pehle stencil aperture size, squeegee pressure aur PCB support pins check karo. Sath hi solder paste ki viscosity aur reflow soak zone profile inspect karo."),("bhai audit h iatf 16949 me kya check hoga","IATF 16949 audit me Control Plans, PFMEA, 8D Root Cause Analysis reports, Gage R&R, Calibration logs, aur Non-Conformance action plans sabse pehle verify kiye jate hain."),("bro fast reply kr direct answer chahiye","Samajh gaya bhai! Seedha point-to-point, crisp aur 100% accurate jawab bina kisi faltu gyan ke."),]p15 = 0for inst, resp in colloquial_anchors:pair = format_qa(inst, resp)if pair and add_pair(pair[0], pair[1], 1, pair[2]):p15 += 1print(f" ✅ Pillar 1.5 Ready: {p15:,} Indian Spoken Slang Anchors packed.")sys.stdout.flush()# --------------------------------------------------------------------------# Pillar 2: STEM, Math & Physics Reasoning (<thought> inner monologue)# --------------------------------------------------------------------------18 unmodified linesresp = a_partpair = format_qa(u_part, resp, thought)if pair and add_pair(pair[0], pair[1], 2, pair[2]):p2 += 1except Exception as e:print(f" ⚠️ STEM streaming: {e}")10 unmodified linesds_chat = load_dataset("Abhishekcr448/Hinglish-Everyday-Conversations-1M", split="train", streaming=True, token=HF_TOKEN)for it in ds_chat:pair = format_qa(it.get("input", ""), it.get("output", ""))if pair and add_pair(pair[0], pair[1], 3, pair[2]):p3 += 1except Exception as e:print(f" ⚠️ Hinglish chat streaming: {e}")26 unmodified linesinst, resp = random.choice(trans_templates[2:]).format(hi=hi), enpair = format_qa(inst, resp)if pair and add_pair(pair[0], pair[1], 4, pair[2]):p4 += 1except Exception as e:print(f" ⚠️ Translation streaming: {e}")10 unmodified linesds_dsm = load_dataset("DSMJ910/hinglish-instruct-10k", split="train", streaming=True, token=HF_TOKEN)for it in ds_dsm:pair = format_qa(it.get("user_message", ""), it.get("assistant_response", ""))if pair and add_pair(pair[0], pair[1], 5, pair[2]):p5 += 1except Exception as e:print(f" ⚠️ DSMJ910: {e}")7 unmodified linesconvs = ast.literal_eval(convs_raw) if isinstance(convs_raw, str) else convs_rawif len(convs) >= 2:pair = format_qa(convs[0].get("value", ""), convs[1].get("value", ""))if pair and add_pair(pair[0], pair[1], 5, pair[2]):p5 += 1except Exception:continue14 unmodified linesmessages = it.get("messages", [])if len(messages) >= 2:pair = format_qa(messages[0].get("content", ""), messages[1].get("content", ""))if pair and add_pair(pair[0], pair[1], 6, pair[2]):p6 += 1except Exception as e:print(f" ⚠️ UltraChat: {e}")12 unmodified linesmessages = it.get("messages", [])if len(messages) >= 2:pair = format_qa(messages[0].get("content", ""), messages[1].get("content", ""))if pair and add_pair(pair[0], pair[1], 7, pair[2]):p7 += 1except Exception as e:print(f" ⚠️ SmolTalk: {e}")67 unmodified linesmetadata = {"dataset_name": f"Sarus_SFT_v2_Master_Uncapped_{collected//1000}k","total_samples": collected,"dedup_duplicates_skipped": dedup_dropped,"train_samples": total_train,"val_samples": total_val,"train_tokens": total_train_tokens_count,"val_tokens": total_val_tokens_count,"max_seq_len": MAX_SEQ_LEN,"dedup_policy": "Normalized 64-bit Canonical Hash (Drops redundant duplicate questions while preserving colloquial slang & formal variations)","colloquial_grounding": "Active (Everyday Indian Tech/Life Slang & Shorthand Intent Equivalence)","thinking_mode": "Adaptive (Short 30-60 token thinking on STEM/Math, Direct on Chat/Mails)","refusal_policy": "Strict Zero Refusals (Canned AI preachiness dropped)","language_gate": "100% Roman Alphabet (Zero Devanagari)"
code/build_sft_v2_kaggle.py+105-12