quant-fidelity-eval / build_public.py
prabodbc's picture
Trim the card; the builder writes the JSONL prompts only
d7f4f7c verified
Raw History Blame Contribute Delete
6.51 kB
"""Builds the quant-fidelity prompt sets from public datasets.
usage: python build_public.py <out dir>
Selection is deterministic: each dataset is read at a pinned revision in a seeded streaming shuffle, rows fill the
on-policy quota and then the forced quota, and the turn to cut at is chosen by hash. Writes public_on_prompts.jsonl,
public_off_prompts.jsonl and public_manifest.json.
"""
import hashlib, json, re, sys
from datasets import load_dataset
OUT = sys.argv[1]; SEED = 0; MAX_PREFIX = 24000
H = lambda s: int(hashlib.sha256(s.encode()).hexdigest()[:8], 16)
def mchars(m): return len(m.get("content") or "")
def norm_ultrachat(r): return r["prompt_id"], [{"role": m["role"], "content": m["content"]} for m in r["messages"]]
def norm_hermes(r):
conv = r["conversations"]
if isinstance(conv, str):
try: conv = json.loads(conv)
except ValueError: return None
if not isinstance(conv, list): return None
try: conv = [json.loads(c) if isinstance(c, str) else c for c in conv]
except ValueError: return None
if not all(isinstance(c, dict) for c in conv): return None
r = dict(r, conversations=conv)
rid = r.get("id") or r.get("hash") or (str(r["idx"]) if r.get("idx") is not None else None) or hashlib.sha256(json.dumps(r["conversations"]).encode()).hexdigest()[:16]
role = {"system": "system", "human": "user", "gpt": "assistant"}
return str(rid), [{"role": role[c["from"]], "content": c["value"]} for c in r["conversations"] if c["from"] in role]
def norm_tulu(r):
if "wildchat" in (r.get("source") or "").lower(): return None
return r["id"], [{"role": m["role"], "content": m["content"]} for m in r["messages"]]
def norm_orca(r):
msgs = ([{"role": "system", "content": r["system_prompt"]}] if r["system_prompt"] else [])
return r["id"], msgs + [{"role": "user", "content": r["question"]}, {"role": "assistant", "content": r["response"]}]
def norm_sweagent(r):
role = {"system": "system", "user": "user", "ai": "assistant"}; out = []
for m in r["trajectory"]:
c = m.get("system_prompt") if m["role"] == "system" else m.get("text")
if m["role"] in role and c: out.append({"role": role[m["role"]], "content": c})
return f"{r['instance_id']}|{r['model_name']}", out
def norm_openhands(r, i=[0]):
i[0] += 1; msgs = [{"role": m["role"], "content": m["content"]} for m in r["messages"] if m["role"] in ("system", "user", "assistant")]
return hashlib.sha256(json.dumps(r["messages"][:3]).encode()).hexdigest()[:16], msgs
def norm_glaive(r):
parts = re.split(r"(USER:|ASSISTANT:|FUNCTION RESPONSE:)", r["chat"]); msgs = []
sysm = re.sub(r"^SYSTEM:\s*", "", r["system"]).strip()
if sysm: msgs.append({"role": "system", "content": sysm})
for tag, body in zip(parts[1::2], parts[2::2]):
body = body.replace("<|endoftext|>", "").strip()
if not body: continue
if tag == "USER:": msgs.append({"role": "user", "content": body})
elif tag == "ASSISTANT:": msgs.append({"role": "assistant", "content": body})
else: msgs.append({"role": "user", "content": "Function response: " + body})
return hashlib.sha256((r["system"] + r["chat"]).encode()).hexdigest()[:16], msgs
SOURCES = [ # name, repo, revision, split, normaliser, on-policy quota, forced quota, min forced chars, shuffle
("ultrachat", "HuggingFaceH4/ultrachat_200k", "8049631c40", "test_sft", norm_ultrachat, 20, 15, 800, True),
("openhermes", "teknium/OpenHermes-2.5", "b820378210", "train", norm_hermes, 20, 15, 800, True),
("tulu3", "allenai/tulu-3-sft-mixture", "b14afda60f", "train", norm_tulu, 25, 15, 800, True),
("openorca", "Open-Orca/OpenOrca", "e9c87b4abb", "train", norm_orca, 15, 0, 800, True),
("swe_agent", "nebius/SWE-agent-trajectories", "68195a1450", "train", norm_sweagent, 20, 20, 400, True),
("openhands", "SWE-Gym/OpenHands-SFT-Trajectories", "4aaa5a4a4b", "train.success.oss", norm_openhands, 20, 20, 400, False),
("glaive_fc", "glaiveai/glaive-function-calling-v2", "e7f4b64560", "train", norm_glaive, 20, 15, 150, True),
]
on, off, manifest = [], [], []
for name, repo, rev, split, norm, qg, qf, minf, shuf in SOURCES:
from huggingface_hub import HfApi
full_rev = HfApi().dataset_info(repo).sha; assert full_rev.startswith(rev), (repo, full_rev)
ds = load_dataset(repo, split=split, streaming=True, revision=full_rev)
if shuf: ds = ds.shuffle(seed=SEED, buffer_size=5000)
ng = nf = 0; seen = 0
for r in ds:
if ng >= qg and nf >= qf: break
seen += 1
x = norm(r)
if not x: continue
rid, msgs = x
pre = [0]
for m in msgs: pre.append(pre[-1] + mchars(m))
def cands(forced):
return [k for k, m in enumerate(msgs) if m["role"] == "assistant" and k >= 1 and pre[k] <= MAX_PREFIX
and any(y["role"] == "user" for y in msgs[:k]) and (not forced or mchars(m) >= minf)]
if ng < qg and cands(False):
c = cands(False); k = c[H(f"{name}\0{rid}\0on") % len(c)]
on.append({"id": f"{name}-{ng:02d}", "category": name, "messages": msgs[:k]})
manifest.append({"set": "public_on", "id": f"{name}-{ng:02d}", "dataset": repo, "revision": full_rev, "split": split, "row_id": rid, "cut_before_message": k}); ng += 1
elif nf < qf and cands(True):
c = cands(True); k = c[H(f"{name}\0{rid}\0off") % len(c)]
off.append({"id": f"{name}-{nf:02d}", "category": name, "messages": msgs[:k + 1], "forced_turn": True})
manifest.append({"set": "public_off", "id": f"{name}-{nf:02d}", "dataset": repo, "revision": full_rev, "split": split, "row_id": rid, "forced_message": k}); nf += 1
print(f"{name}: greedy {ng}/{qg} forced {nf}/{qf} (rows read {seen})", flush=True)
for fname, prompts in (("public_on_prompts.jsonl", on), ("public_off_prompts.jsonl", off)):
with open(f"{OUT}/{fname}", "w") as handle:
for prompt in prompts:
handle.write(json.dumps({**prompt, "forced_turn": prompt.get("forced_turn", False)}, ensure_ascii=False) + "\n")
json.dump({"seed": SEED, "max_prefix_chars": MAX_PREFIX, "selection": "seeded streaming shuffle (buffer 5000) except OpenHands; "
"rows in order fill the on-policy quota first, then forced; cut point = sha256(source, row id, set) mod candidates; "
"Tulu WildChat rows excluded",
"prompts": manifest}, open(f"{OUT}/public_manifest.json", "w"), indent=1)
print("on", len(on), "off", len(off))