Lottolabs's picture
LFM3-1.7B self-distillation set: 42,591 train + 324 eval rows (63.35M output tokens), source refs, licenses, scripts
f970b46 verified
Raw History Blame Contribute Delete
14.7 kB
#!/usr/bin/env python3
"""Build the drafter's prompt sets: data/prompts_train.jsonl and data/prompts_eval.jsonl.
Each line: {id, domain (chat|code|math|tool|multi|bench), src, thinking (0|1), sampling (greedy|liquid), seed,
max_tokens, prompt_ids}. Prompts are rendered with LFM3's chat_template.jinja (generation prompt; enable_thinking per
record; tools passed as `tools`), so the server only sees token ids (/v1/completions).
Disjointness: the train set never uses UltraChat test_sft, GSM8K test, nor any prompt whose text overlaps the quality
eval set (ref/eval/eval3.jsonl user turns) or the held-out drafter eval prompts.
Run: venv/bin/python prep_prompts.py"""
import json
import random
import re
import sys
from pathlib import Path
from datasets import load_dataset
from transformers import AutoTokenizer
D = Path(__file__).parent / "out"
REV = {"HuggingFaceH4/ultrachat_200k": "8049631c405ae6576f93f445c6b8166f76f5505a",
"allenai/WildChat-1M": "7d6490e462285cf85d91eabea0f9a954fbddcd1f",
"OpenAssistant/oasst2": "179dd21fc55192153d94adb0e0ce8f69e222bf75",
"CohereForAI/aya_dataset": "f9ea04583f02a8f86404ff6c58bf75fe637df8a2",
"ise-uiuc/Magicoder-OSS-Instruct-75K": "5f839b1f368a76b161028bb9edff055db34022b2",
"theblackcat102/evol-codealpaca-v1": "c75242318519b5470635e84064baed7c78594020",
"openai/gsm8k": "740312add88f781978c0658806c59bc2815b9866",
"meta-math/MetaMathQA": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18",
"AI-MO/NuminaMath-CoT": "9d8d210c9f6a36c8f3cd84045668c9b7800ef517",
"NousResearch/hermes-function-calling-v1": "dae3e1d28cfbcf4b915c04ea1e072030529b4bda",
"glaiveai/glaive-function-calling-v2": "e7f4b6456019f5d8bcb991ef0dd67d8ff23221ac"}
_load = load_dataset
def load_dataset(name, *args, **kw):
ds = _load(name, *args, revision=REV[name], **kw)
if not kw.get("streaming"):
ds = ds.add_column("_row", list(range(len(ds))))
return ds
def ref(ds_id, r, cfg=None, split="train", **native):
out = {"dataset": ds_id, "revision": REV[ds_id], "split": split, "row": r.get("_row")}
if cfg:
out["config"] = cfg
out.update(native)
return out
HF = "/var/tmp/lfm3/hf"
MAX_PROMPT = 3072
EVAL_PER = 60 # held-out prompts per domain
tok = AutoTokenizer.from_pretrained(HF, trust_remote_code=True)
rng = random.Random(1234)
def norm_text(s):
return re.sub(r"\s+", " ", s).strip().lower()[:300]
# quality-eval texts (ref/eval): decoded once, user turns kept as 300-char keys
EVAL_KEYS = set()
for line in open("/var/tmp/lfm3/ref/eval/eval3.jsonl"):
r = json.loads(line)
text = tok.decode(r["token_ids"])
for seg in text.split("<|im_start|>user\n")[1:]:
EVAL_KEYS.add(norm_text(seg.split("<|im_end|>")[0]))
GSM_TEST = {norm_text(json.loads(l)["question"]) for l in open("/var/tmp/lfm3/ref/gsm8k/gsm8k-prompts.jsonl")}
def render(messages, thinking, tools=None):
kw = {"tools": tools} if tools else {}
ids = tok.apply_chat_template(messages, add_generation_prompt=True, enable_thinking=bool(thinking),
tokenize=True, **kw)
if not isinstance(ids, list):
ids = ids["input_ids"]
return list(ids)
def chat_first_turns(conv, max_turns):
"""[{role, content}] -> messages ending with a user turn (1..max_turns user turns)."""
msgs = [m for m in conv if m["role"] in ("user", "assistant") and m["content"].strip()]
users = [i for i, m in enumerate(msgs) if m["role"] == "user"]
if not users:
return None
k = rng.randint(1, min(max_turns, len(users)))
return msgs[: users[k - 1] + 1]
def gen_ultrachat(split, n, skip=0):
ds = load_dataset("HuggingFaceH4/ultrachat_200k", split=split).shuffle(seed=1)
out = []
for r in ds.select(range(skip, len(ds))):
conv = r["messages"]
msgs = chat_first_turns(conv, 3 if rng.random() < 0.25 else 1)
if msgs:
out.append(("ultrachat", msgs, None, ref("HuggingFaceH4/ultrachat_200k", r, split=split,
prompt_id=r["prompt_id"])))
if len(out) >= n:
break
return out
def gen_wildchat(n_en, n_multi):
ds = load_dataset("allenai/WildChat-1M", split="train", streaming=True).shuffle(seed=2, buffer_size=20000)
en, multi = [], []
for r in ds:
if any(m.get("flagged") for m in r["openai_moderation"]):
continue
conv = [{"role": m["role"], "content": m["content"]} for m in r["conversation"]]
msgs = chat_first_turns(conv, 2 if rng.random() < 0.2 else 1)
if not msgs or len(msgs[-1]["content"]) < 15:
continue
if r["language"] == "English":
if len(en) < n_en:
en.append(("wildchat", msgs, None, ref("allenai/WildChat-1M", r, conversation_hash=r["conversation_hash"],
turn_identifier=r["conversation"][0].get("turn_identifier"))))
elif len(multi) < n_multi:
multi.append(("wildchat-" + r["language"], msgs, None,
ref("allenai/WildChat-1M", r, conversation_hash=r["conversation_hash"],
turn_identifier=r["conversation"][0].get("turn_identifier"))))
if len(en) >= n_en and len(multi) >= n_multi:
break
return en, multi
def gen_oasst(n_en, n_multi):
ds = load_dataset("OpenAssistant/oasst2", split="train")
roots = [r for r in ds if r["parent_id"] is None and r["role"] == "prompter"]
rng.shuffle(roots)
en = [("oasst2", [{"role": "user", "content": r["text"]}], None,
ref("OpenAssistant/oasst2", r, message_id=r["message_id"])) for r in roots if r["lang"] == "en"][:n_en]
multi = [("oasst2-" + r["lang"], [{"role": "user", "content": r["text"]}], None,
ref("OpenAssistant/oasst2", r, message_id=r["message_id"]))
for r in roots if r["lang"] != "en"][:n_multi]
return en, multi
def gen_aya(n):
ds = load_dataset("CohereForAI/aya_dataset", split="train").shuffle(seed=3)
out = []
for r in ds:
if r["language_code"] == "eng" or len(r["inputs"]) < 20:
continue
out.append(("aya-" + r["language_code"], [{"role": "user", "content": r["inputs"]}], None,
ref("CohereForAI/aya_dataset", r)))
if len(out) >= n:
break
return out
def gen_code(n_magic, n_evol):
a = load_dataset("ise-uiuc/Magicoder-OSS-Instruct-75K", split="train").shuffle(seed=4).select(range(n_magic))
b = load_dataset("theblackcat102/evol-codealpaca-v1", split="train").shuffle(seed=5).select(range(n_evol))
return ([("magicoder", [{"role": "user", "content": r["problem"]}], None,
ref("ise-uiuc/Magicoder-OSS-Instruct-75K", r, index=r.get("index"))) for r in a]
+ [("evolcode", [{"role": "user", "content": r["instruction"]}], None,
ref("theblackcat102/evol-codealpaca-v1", r)) for r in b])
def gen_math(n_gsm, n_meta, n_numina):
g = load_dataset("openai/gsm8k", "main", split="train").shuffle(seed=6).select(range(n_gsm))
m = load_dataset("meta-math/MetaMathQA", split="train").shuffle(seed=7)
k = load_dataset("AI-MO/NuminaMath-CoT", split="train").shuffle(seed=8).select(range(n_numina))
meta, seen = [], set()
for r in m:
key = norm_text(r["original_question"])
if key in GSM_TEST or key in seen:
continue
seen.add(key)
meta.append(("metamath", [{"role": "user", "content": r["query"]}], None, ref("meta-math/MetaMathQA", r)))
if len(meta) >= n_meta:
break
return ([("gsm8k-train", [{"role": "user", "content": r["question"]}], None, ref("openai/gsm8k", r, cfg="main"))
for r in g] + meta
+ [("numina", [{"role": "user", "content": r["problem"]}], None, ref("AI-MO/NuminaMath-CoT", r)) for r in k])
def parse_hermes_calls(text):
calls = []
for blob in re.findall(r"<tool_call>\s*(.*?)\s*</tool_call>", text, re.S):
try:
c = json.loads(blob)
except json.JSONDecodeError:
try:
import ast
c = ast.literal_eval(blob)
except Exception:
return None
if not isinstance(c, dict) or "name" not in c:
return None
calls.append({"type": "function", "function": {"name": c["name"], "arguments": c.get("arguments", {})}})
return calls
def gen_tools(n_glaive):
out = []
for cfg in ("func_calling_singleturn", "func_calling"):
ds = load_dataset("NousResearch/hermes-function-calling-v1", cfg, split="train")
for r in ds:
try:
tools = json.loads(r["tools"])
except Exception:
continue
if not isinstance(tools, list) or not tools:
continue
conv = r["conversations"]
msgs = []
for t in conv:
if t["from"] == "system":
continue
if t["from"] == "human":
msgs.append({"role": "user", "content": t["value"]})
elif t["from"] == "gpt":
calls = parse_hermes_calls(t["value"])
if calls:
msgs.append({"role": "assistant", "content": "", "tool_calls": calls})
else:
msgs.append({"role": "assistant", "content": t["value"]})
elif t["from"] == "tool":
for resp in re.findall(r"<tool_response>\s*(.*?)\s*</tool_response>", t["value"], re.S) or [t["value"]]:
msgs.append({"role": "tool", "content": resp})
# cut points: before the first assistant turn, and (multi-turn config) after the first tool results
if msgs and msgs[0]["role"] == "user":
out.append(("hermes-" + cfg, msgs[:1], tools,
ref("NousResearch/hermes-function-calling-v1", r, cfg=cfg, id=r.get("id"))))
if cfg == "func_calling":
for i in range(1, len(msgs)):
if msgs[i - 1]["role"] == "tool" and (i == len(msgs) or msgs[i]["role"] != "tool"):
out.append(("hermes-toolresult", msgs[:i], tools,
ref("NousResearch/hermes-function-calling-v1", r, cfg=cfg, id=r.get("id"),
cut_messages=i)))
break
g = load_dataset("glaiveai/glaive-function-calling-v2", split="train").shuffle(seed=9)
dec = json.JSONDecoder()
n = 0
for r in g:
sysmsg = r["system"]
if "-" not in sysmsg:
continue
body = sysmsg.split("Use them if required -", 1)[-1].strip()
fns, i = [], 0
try:
while i < len(body):
while i < len(body) and body[i] in " \n\r\t,":
i += 1
if i >= len(body):
break
obj, i = dec.raw_decode(body, i)
fns.append(obj)
except json.JSONDecodeError:
continue
if not fns:
continue
m = re.match(r"\s*USER:\s*(.*?)\s*(?:ASSISTANT:|$)", r["chat"], re.S)
if not m or len(m.group(1)) < 10:
continue
tools = [{"type": "function", "function": f} for f in fns]
out.append(("glaive", [{"role": "user", "content": m.group(1)}], tools,
ref("glaiveai/glaive-function-calling-v2", r)))
n += 1
if n >= n_glaive:
break
return out
def main():
D.mkdir(exist_ok=True)
pools = {}
pools["chat"] = gen_ultrachat("train_sft", 9000)
wen, wmulti = gen_wildchat(7000, 3500)
oen, omulti = gen_oasst(1500, 1000)
pools["chat"] += wen + oen
pools["multi"] = wmulti + omulti + gen_aya(2500)
pools["code"] = gen_code(5000, 4000)
pools["math"] = gen_math(3000, 3000, 3000)
pools["tool"] = gen_tools(3000)
print({k: len(v) for k, v in pools.items()}, flush=True)
def make(domain, src, msgs, tools, idx, split, rowref):
thinking = int(rng.random() < 0.5)
sampling = "greedy" if rng.random() < 0.5 else "liquid"
try:
ids = render(msgs, thinking, tools)
except Exception as e: # template refuses a malformed conversation
print("render failed", src, repr(e)[:120], flush=True)
return None
if len(ids) > MAX_PROMPT:
return None
return {"id": f"{split}-{domain}-{idx}", "domain": domain, "src": src, "thinking": thinking,
"sampling": sampling, "seed": rng.randrange(1 << 30), "max_tokens": 4096 if thinking else 2048,
"prompt_ids": ids, "source_ref": rowref}
train, evals, seen = [], [], set(EVAL_KEYS)
for domain, items in pools.items():
rng.shuffle(items)
kept = 0
for idx, (src, msgs, tools, rowref) in enumerate(items):
key = norm_text(msgs[-1]["content"] if msgs[-1]["content"] else json.dumps(msgs[-1]))
if key in seen:
continue
seen.add(key)
split = "eval" if kept < EVAL_PER else "train"
rec = make(domain, src, msgs, tools, idx, split, rowref)
if rec is None:
continue
kept += 1
(evals if split == "eval" else train).append(rec)
# the speed benchmark's workloads (src/lfm3/tests/http_spec_bench.py), greedy + liquid seeds 1-3
sys.path.insert(0, "/var/tmp/lfm3/src/lfm3/tests")
import http_spec_bench as hb
for name, w in hb.workloads().items():
thinking = 0 if w.get("extra") else 1
ids = render(w["messages"], thinking, w.get("tools"))
for sampling, seed in (("greedy", 0), ("liquid", 1), ("liquid", 2), ("liquid", 3)):
evals.append({"id": f"eval-bench-{name}-{sampling}{seed}", "domain": "bench", "src": name,
"thinking": thinking, "sampling": sampling, "seed": seed,
"max_tokens": w.get("max_tokens", 1536), "prompt_ids": ids})
rng.shuffle(train)
with open(D / "prompts_train.jsonl", "w") as f:
for r in train:
f.write(json.dumps(r) + "\n")
with open(D / "prompts_eval.jsonl", "w") as f:
for r in evals:
f.write(json.dumps(r) + "\n")
from collections import Counter
print("train", len(train), Counter(r["domain"] for r in train), "eval", len(evals),
Counter(r["domain"] for r in evals), flush=True)
if __name__ == "__main__":
main()