File size: 11,823 Bytes
3b070ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
"""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"])