"""Build the SFT mix for Ivme-Conversate-v3.1-Instruct. Output (in OUT): train_x.npy / train_y.npy / val_x.npy / val_y.npy, each [N, 1024] int32, plus stats.json. y uses -100 for positions that carry no loss (prompts, padding). Chat format (plain text, no new tokens): <|endoftext|>System: ...\n\nUser: ...\n\nAssistant: ...\n\nUser: ...\n\nAssistant: ...<|endoftext|> Loss only on assistant text (+ the "\n\n" that ends a non-final turn, + the final EOT). """ import json, os, random, re, sys, time import numpy as np, pandas as pd from huggingface_hub import hf_hub_download, snapshot_download from tokenizers import Tokenizer OUT = sys.argv[1] if len(sys.argv) > 1 else "/marimo/ivme_sft/data" SEQ, EOT, PAD = 1024, 0, 1 REPLAY_TOKENS = 15_000_000 MAX_REPLY = int(sys.argv[2]) if len(sys.argv) > 2 else 10**9 # max tokens per assistant turn REPEAT = {"everyday": 5, "openthink": 2} os.makedirs(OUT, exist_ok=True) random.seed(0) t0 = time.time() def log(*a): print(f"[prep {time.time()-t0:6.0f}s]", *a, flush=True) tk = Tokenizer.from_file(snapshot_download("IvmeLabs/Ivme-Conversate-v3.1-Base") + "/tokenizer.json") def enc(texts): texts, out = list(texts), [] for i in range(0, len(texts), 4096): out += [e.ids for e in tk.encode_batch(texts[i:i + 4096])] return out def pq(repo, path): return pd.read_parquet(hf_hub_download(repo, path, repo_type="dataset", revision="refs/convert/parquet")) def clean(s): return s.replace("÷", "/").strip() # ---------------------------------------------------------------- conversations convs = {} # source -> list of [(role, text)] # 1) smol-smoltalk DROP = {"longalign", "smol-summarize-5k", "self-oss-instruct"} ss = pd.concat([pq("HuggingFaceTB/smol-smoltalk", f"default/train/000{i}.parquet") for i in range(4)]) ss = ss[~ss.source.isin(DROP)] def ok_msgs(m): txt = " ".join(x["content"] for x in m if x["role"] == "assistant") return "SmolLM" not in txt and len(m) >= 2 ss = ss[ss.messages.apply(ok_msgs)] convs["smol-smoltalk"] = [[(x["role"], x["content"]) for x in m] for m in ss.messages] log("smol-smoltalk", len(convs["smol-smoltalk"])) del ss # 2) everyday conversations (x3 upsample later) ev = pq("HuggingFaceTB/everyday-conversations-llama3.1-2k", "default/train_sft/0000.parquet") convs["everyday"] = [[(x["role"], x["content"]) for x in m] for m in ev.messages] # 3) OpenThink hybrid, minus the contradictory-finals rows def _t(s): m = re.fullmatch(r"\s*(\d{1,2}):(\d\d)\s*(am|pm)?\s*", s.lower()); return (int(m[1]) % 12, int(m[2])) if m else None def _n(s): try: return float(s.lower().replace("$", "").replace(",", "").strip()) except Exception: return None def finals_ok(bf): a, b = bf ta, tb = _t(a), _t(b) if ta and tb: return ta == tb na, nb = _n(a), _n(b) if na is not None and nb is not None: return na == nb return True ot = pq("slmconsortium/OpenThink", "hybrid/train/0000.parquet") n0 = len(ot); ot = ot[ot.both_finals.apply(finals_ok)] log("OpenThink dropped", n0 - len(ot)) convs["openthink"] = [[("user", clean(q)), ("assistant", clean(t))] for q, t in zip(ot.question, ot.trace)] log("openthink built") # 4) LibreMath without find_the_mistake lm = pq("opencerebral/LibreMath-v1", "default/train/0000.parquet") lm = lm[lm.format != "find_the_mistake"] log("libremath loaded", len(lm)) convs["libremath"] = [[("user", clean(p)), ("assistant", clean(s) + f"\n\nFinal answer: {a}")] for p, s, a in zip(lm.problem, lm.solution, lm.answer)] # 5) identity NAME, ORG, AUTHOR = "İvme-Conversate", "IvmeLabs", "Eren Ekşi" ask = ["Who are you?", "What is your name?", "What are you?", "Introduce yourself.", "Who made you?", "Who created you?", "Are you ChatGPT?", "Are you SmolLM?", "Which company built you?", "What model are you?", "Tell me about yourself.", "Hi! Who am I talking to?", "Are you a human?", "How big are you?", "What can you do?", "Who trained you?", "What's your name, assistant?", "Are you made by OpenAI?", "hey what are u", "who built this AI?"] ans = { "id": [f"I'm {NAME}, a small language model made by {ORG}.", f"My name is {NAME}. I'm a small AI assistant built by {ORG}.", f"I'm {NAME}, a tiny language model from {ORG}. I can chat and answer simple questions."], "maker": [f"I was made by {ORG}. {ORG} is run by {AUTHOR}.", f"{AUTHOR} at {ORG} built and trained me.", f"I was created by {ORG}, by {AUTHOR}."], "not": [f"No, I'm not. I'm {NAME}, a small model made by {ORG}.", f"No. I'm {NAME}, built by {ORG}, not by another company."], "human": [f"No, I'm not a human. I'm {NAME}, an AI language model made by {ORG}."], "size": [f"I'm very small: about 25 million parameters. That makes me fast, but I can make mistakes, so please double-check important answers."], "can": [f"I can chat, answer simple questions, explain basic ideas and do easy math. I'm a small model, so I can make mistakes on hard or very long tasks."], } def pick(q): ql = q.lower() if any(k in ql for k in ["chatgpt", "smollm", "openai"]): return "not" if "human" in ql: return "human" if "big" in ql: return "size" if "can you do" in ql: return "can" if any(k in ql for k in ["made", "created", "company", "trained", "built"]): return "maker" return "id" ident = [] for _ in range(400): q = random.choice(ask) if random.random() < 0.3: q = q.lower() ident.append([("user", q), ("assistant", random.choice(ans[pick(q)]))]) convs["identity"] = ident log("identity built") # ---------------------------------------------------------------- short casual replies (no identity) from casual_pairs import PAIRS def vary(q): r = random.random() if r < 0.3: q = q[0].upper() + q[1:] if random.random() < 0.2 and q[-1] not in "?!.": q += random.choice(["!", "?", "."]) return q casual = [[("user", vary(q)), ("assistant", a)] for q, a in PAIRS for _ in range(3)] for _ in range(400): # 2-3 turn casual chats -> EOT after every short turn casual.append([x for q, a in random.sample(PAIRS, random.randint(2, 3)) for x in (("user", vary(q)), ("assistant", a))]) ops = [("+", lambda a, b: a + b, ["plus", "+", " + ", "and"]), ("-", lambda a, b: a - b, ["minus", "-", " - "]), ("*", lambda a, b: a * b, ["times", "*", " x ", "multiplied by"])] for _ in range(1500): o, f, words = random.choice(ops); a_, b_ = random.randint(0, 30 if o != "*" else 12), random.randint(0, 30 if o != "*" else 12) if o == "-" and b_ > a_: a_, b_ = b_, a_ w = random.choice(words); w = w if w.startswith(" ") or w in "+-*" else f" {w} " expr = f"{a_}{w}{b_}" q = random.choice([f"what is {expr}?", f"whats {expr}", f"{expr}?", f"{expr}", f"What's {expr}?", f"calculate {expr}", f"what does {expr} equal?", f"can you add {a_} and {b_}?" if o == "+" else f"what is {expr}?"]) sym = {"+": "+", "-": "-", "*": "×"}[o] casual.append([("user", q), ("assistant", f"{a_} {sym} {b_} = {f(a_, b_)}.")]) convs["casual"] = casual REPEAT["casual"] = 1 # ---------------------------------------------------------------- safety from safety_pairs import CRISIS_Q, CRISIS_A, DISTRESS, HARM_Q, HARM_A, VIOLENCE_EXTRA, BENIGN, FALSE_PREMISE, BENIGN_HOWTO PRE = ["", "", "", "honestly ", "tbh ", "i think ", "please tell me ", "seriously, ", "be honest, "] def svary(q): return vary(random.choice(PRE) + q) safety = [] for q in CRISIS_Q: for _ in range(25): safety.append([("user", svary(q)), ("assistant", random.choice(CRISIS_A))]) for q in HARM_Q: for _ in range(15): safety.append([("user", svary(q)), ("assistant", random.choice(HARM_A))]) for group, n in [(DISTRESS, 12), (VIOLENCE_EXTRA, 12), (BENIGN, 12), (FALSE_PREMISE, 10), (BENIGN_HOWTO, 10)]: for q, a in group: for _ in range(n): safety.append([("user", vary(q)), ("assistant", a)]) for _ in range(900): # safety turn in the middle/end of a normal chat q0, a0 = random.choice(PAIRS) kind = random.random() if kind < 0.4: q1, a1 = random.choice(CRISIS_Q), random.choice(CRISIS_A) elif kind < 0.7: q1, a1 = random.choice(HARM_Q), random.choice(HARM_A) else: q1, a1 = random.choice(BENIGN + BENIGN_HOWTO) safety.append([("user", vary(q0)), ("assistant", a0), ("user", svary(q1)), ("assistant", a1)]) convs["safety"] = safety REPEAT["safety"] = 1 # ---------------------------------------------------------------- tokenize convs # Every assistant turn ends with <|endoftext|> (trained). Prompt pieces are masked. # <|endoftext|>User: q\n\nAssistant: a<|endoftext|>User: q2\n\nAssistant: a2<|endoftext|> ROLE = {"system": "System", "user": "User", "assistant": "Assistant"} def conv_pieces(c): while c and c[-1][0] != "assistant": c = c[:-1] if not c: return None pieces, buf = [], "" for r, t in c: if r == "assistant": pieces.append((buf + "Assistant:", False)); buf = "" pieces.append((" " + t.strip(), True)) else: buf += f"{ROLE.get(r, 'User')}: {t.strip()}\n\n" return pieces stats, all_ex = {}, [] for src, cl in convs.items(): log("tokenizing", src) plist = [p for p in (conv_pieces(c) for c in cl) if p] eids = enc([t for p in plist for t, _ in p]) k = 0; exs = [] for p in plist: ids, lab, longest = [EOT], [-100], 0 for (_, tr) in p: e = eids[k]; k += 1 if tr: ids += e + [EOT]; lab += e + [EOT]; longest = max(longest, len(e)) else: ids += e; lab += [-100] * len(e) if len(ids) <= SEQ and longest <= MAX_REPLY: exs.append((ids, lab)) rep = REPEAT.get(src, 1) stats[src] = {"convs": len(cl), "kept": len(exs), "tokens": sum(len(i) for i, _ in exs) * rep, "loss_tokens": sum(sum(l != -100 for l in lb) for _, lb in exs) * rep, "repeat": rep} log(src, stats[src]) all_ex += [(src, e) for e in exs] * rep random.shuffle(all_ex) nval, val_ex, train_ex = 2000, [], [] for s, e in all_ex: (val_ex if len(val_ex) < nval and s not in ("everyday", "identity", "casual", "safety") else train_ex).append(e) def pack(exs): X, Y, cx, cy = [], [], [], [] for ids, lab in exs: if len(cx) + len(ids) > SEQ: pad = SEQ - len(cx); X.append(cx + [PAD] * pad); Y.append(cy + [-100] * pad); cx, cy = [], [] cx += ids; cy += lab if cx: pad = SEQ - len(cx); X.append(cx + [PAD] * pad); Y.append(cy + [-100] * pad) return np.array(X, np.int32), np.array(Y, np.int32) # ---------------------------------------------------------------- replay (fineweb-edu, score>=3.5) fw = pd.read_parquet(hf_hub_download("HuggingFaceFW/fineweb-edu", "sample/10BT/000_00000.parquet", repo_type="dataset"), columns=["text", "score"]) fw = fw[fw.score >= 3.5].sample(frac=1, random_state=0) stream, n = [], 0 for i in range(0, len(fw), 5000): for e in enc(fw.text.iloc[i:i + 5000]): stream += [EOT] + e; n += len(e) + 1 if n >= REPLAY_TOKENS: break nr = len(stream) // SEQ RX = np.array(stream[:nr * SEQ], np.int32).reshape(nr, SEQ) stats["replay_fineweb_edu"] = {"tokens": int(RX.size), "loss_tokens": int(RX.size)} log("replay", stats["replay_fineweb_edu"]) TX, TY = pack(train_ex) TX = np.concatenate([TX, RX]); TY = np.concatenate([TY, RX]) perm = np.random.default_rng(0).permutation(len(TX)); TX, TY = TX[perm], TY[perm] VX, VY = pack(val_ex) for nme, a in [("train_x", TX), ("train_y", TY), ("val_x", VX), ("val_y", VY)]: np.save(f"{OUT}/{nme}.npy", a) stats["_total"] = {"train_seqs": len(TX), "train_tokens": int(TX.size), "train_loss_tokens": int((TY != -100).sum()), "val_seqs": len(VX), "fill": float((TX != PAD).mean())} json.dump(stats, open(f"{OUT}/stats.json", "w"), indent=1) log("DONE", stats["_total"])