hermeneutic-dive / create_dataset.py
Exxe's picture
Upload 55 files
5f874f8 verified
Raw History Blame Contribute Delete
10.4 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""HermeneuticDive v3.0.0 — provenance / reproduction script.
Rebuilds data/<config>/<split>-*.parquet from the raw JSONL inputs in this
repository, recomputes stats.json, and verifies build invariants:
- qa_sft and qa_rl question sets are disjoint (no SFT/RL overlap)
- message turns carry tool_call_id on every tool result, each referencing an
earlier assistant tool call
- trajectories and DPO pairs inherit their question's split
- row counts match stats.json
The decontamination hook now implements CONTAINMENT metrics (v2; replaces the
v1 Jaccard-over-concatenated-fields check the audit found too dilute):
1. substring containment (normalised, >= 20 chars, either direction)
2. token-set containment >= 0.75 (stopwords removed, >= 6 tokens per side)
3. character-shingle (n=5) Jaccard >= 0.5
Usage:
python create_dataset.py # rebuild parquet + stats
python create_dataset.py --decontaminate benchmarks_dir_or.jsonl
benchmarks: one JSON per line with a "question" field (or any text fields),
or a directory of such .jsonl files. The release was checked against
7,900 questions from HotpotQA, 2WikiMultihopQA, MuSiQue and TriviaQA
(fetched 2026-11-12 in v2; INHERITED, not re-run in v3 — see decontamination_report.json).
Author pipeline: HermeneuticDive maintainers (independent project;
LLM-assisted authoring under human direction). NOT affiliated with Z.ai or
the original DeepDive authors.
License: CC0-1.0 for all authored content (see LICENSE and README: Licensing).
"""
import argparse, json, re, sys, unicodedata
from pathlib import Path
from collections import defaultdict
import pyarrow as pa
import pyarrow.parquet as pq
HERE = Path(__file__).parent
CONFIGS = ["qa_sft", "qa_rl", "trajectories_sft", "dpo", "dpo_matched"]
RAW_OF = {"qa_sft": "qa_sft_raw.jsonl", "qa_rl": "qa_rl_raw.jsonl",
"trajectories_sft": "trajectories_raw.jsonl", "dpo": "dpo_raw.jsonl",
"dpo_matched": "dpo_matched_raw.jsonl"}
SPLITS = ["train", "validation", "test"]
TYPE_MAP = {"string": pa.string(), "int32": pa.int32(), "float64": pa.float64(),
"bool": pa.bool_(), "int64": pa.int64()}
def spec_to_arrow(spec):
t = spec.get("_type")
if t == "Value":
return TYPE_MAP[spec["dtype"]]
if t == "List":
return pa.list_(spec_to_arrow(spec["feature"]))
if t == "struct":
return pa.struct([(k, spec_to_arrow(v)) for k, v in spec["fields"].items()])
raise ValueError(f"unsupported spec: {spec}")
def schema_for(features_json):
return pa.schema([(name, spec_to_arrow(spec)) for name, spec in features_json.items()])
def load_rows(cfg):
return [json.loads(l) for l in (HERE / RAW_OF[cfg]).read_text(encoding="utf-8").splitlines()]
def clean(row, schema):
return {name: row.get(name) for name in schema.names}
def rebuild():
stats = {}
for cfg in CONFIGS:
rows = load_rows(cfg)
features_json = json.loads((HERE / f"features_{cfg}.json").read_text())
schema = schema_for(features_json)
out_dir = HERE / "data" / cfg
out_dir.mkdir(parents=True, exist_ok=True)
by_split = defaultdict(list)
for r in rows:
by_split[r["split"]].append(clean(r, schema))
cfg_stats = {}
for split in SPLITS:
srows = by_split.get(split, [])
table = pa.Table.from_pylist(srows, schema=schema)
path = out_dir / f"{split}-00000-of-00001.parquet"
pq.write_table(table, path)
cfg_stats[split] = {"num_examples": len(srows),
"num_bytes": table.nbytes,
"download_size": path.stat().st_size,
"shards": [path.name]}
print(f"{cfg}/{split}: {len(srows)} rows -> {path.name}")
stats[cfg] = {
"splits": cfg_stats,
"download_size": sum(s["download_size"] for s in cfg_stats.values()),
"dataset_size": sum(s["num_bytes"] for s in cfg_stats.values()),
"num_examples": sum(s["num_examples"] for s in cfg_stats.values()),
}
(HERE / "stats.json").write_text(json.dumps(stats, indent=2, ensure_ascii=False))
verify(stats)
print("stats.json written; invariants verified.")
def verify(stats):
# v2: SFT and RL pools disjoint
sft_ids = {r["id"] for r in load_rows("qa_sft")}
rl_ids = {r["id"] for r in load_rows("qa_rl")}
assert not (sft_ids & rl_ids), f"SFT/RL question overlap: {sorted(sft_ids & rl_ids)[:5]}"
# split integrity: a question id lives in exactly one split across configs
split_of = {}
for cfg in ["qa_sft", "qa_rl"]:
for r in load_rows(cfg):
if r["id"] in split_of:
assert split_of[r["id"]] == r["split"], f"split leakage: {r['id']}"
split_of[r["id"]] = r["split"]
# trajectories + dpo inherit their question's split (question must be in qa_sft)
qa = {r["id"]: r["split"] for r in load_rows("qa_sft")}
for t in load_rows("trajectories_sft"):
assert t["qa_id"] in qa, f"trajectory references non-SFT question: {t['qa_id']}"
assert t["split"] == qa[t["qa_id"]], f"trajectory split mismatch: {t['id']}"
for cfg_ in ("dpo", "dpo_matched"):
for d in load_rows(cfg_):
assert d["qa_id"] in qa, f"{cfg_} references non-SFT question: {d['qa_id']}"
assert d["split"] == qa[d["qa_id"]], f"{cfg_} split mismatch: {d['id']}"
# v2: tool_call_id integrity in every message list of every config
def check_messages(msgs, ctx):
for i, t in enumerate(msgs):
if t.get("role") == "tool":
assert t.get("tool_call_id"), f"{ctx}: tool turn without tool_call_id"
ids = {c["id"] for tt in msgs[:i] if tt.get("role") == "assistant"
for c in tt.get("tool_calls") or []}
assert t["tool_call_id"] in ids, f"{ctx}: dangling tool_call_id {t['tool_call_id']}"
for r in load_rows("qa_sft"):
check_messages(r["messages"], f"qa_sft/{r['id']}")
for t in load_rows("trajectories_sft"):
check_messages(t["turns"], f"traj/{t['id']}")
for cfg_ in ("dpo", "dpo_matched"):
for d in load_rows(cfg_):
check_messages(d["chosen"], f"{cfg_}/{d['id']}/chosen")
check_messages(d["rejected"], f"{cfg_}/{d['id']}/rejected")
# v3: a matched pair differs ONLY in the final answer line (no length/tool-call confound)
for d in load_rows("dpo_matched"):
assert d["chosen"][:-1] == d["rejected"][:-1], f"matched pair differs before the final turn: {d['id']}"
assert d["chosen"][-1]["content"].rsplit("Final answer:", 1)[0] == d["rejected"][-1]["content"].rsplit("Final answer:", 1)[0], d["id"]
# counts match stats
for cfg, s in stats.items():
assert s["num_examples"] == len(load_rows(cfg)), cfg
print("invariants OK: SFT/RL disjoint, split sync, tool_call_id integrity, linkage, counts.")
# ── containment decontamination (v2) ────────────────────────────────────────
STOPWORDS = {
"the", "a", "an", "of", "in", "on", "at", "to", "for", "and", "or", "is",
"are", "was", "were", "be", "been", "by", "as", "that", "this", "these",
"those", "it", "its", "his", "her", "their", "who", "what", "which", "when",
"where", "how", "did", "do", "does", "name", "named", "called", "from",
"with", "into", "about", "first", "one", "whom", "he", "she", "they",
}
def _norm(s):
s = unicodedata.normalize("NFC", s).lower()
s = re.sub(r"[^\w\u4e00-\u9fff\u0400-\u04ff\u0900-\u097f\u3040-\u30ff]+", " ", s)
return re.sub(r"\s+", " ", s).strip()
def _tokens(s):
t = _norm(s)
if re.search(r"[\u4e00-\u9fff\u3040-\u30ff]", t):
return set(t.replace(" ", ""))
return {w for w in t.split() if w not in STOPWORDS}
def _shingles(s, n=5):
t = _norm(s)
return set(t[i:i+n] for i in range(len(t) - n + 1)) or {t}
def decontaminate(target):
p = Path(target)
bench = []
sources = sorted(p.glob("*.jsonl")) if p.is_dir() else [p]
assert sources, f"no benchmark files at {target}"
for src in sources:
for line in src.read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
obj = json.loads(line)
q = obj.get("question") or " ".join(str(v) for v in obj.values()
if isinstance(v, (str, int, float)))
bench.append(q)
assert bench, f"no benchmark questions loaded from {target}: a check against nothing is not a pass"
b_pre = [(_norm(b), _tokens(b), _shingles(b)) for b in bench]
hits = []
for cfg in ["qa_sft", "qa_rl"]:
for r in load_rows(cfg):
qn, qt, qs = _norm(r["question"]), _tokens(r["question"]), _shingles(r["question"])
for i, (bn, bt, bs) in enumerate(b_pre):
if (len(qn) >= 20 and qn in bn) or (len(bn) >= 20 and bn in qn):
hits.append((r["id"], i, "substring", 1.0)); continue
if min(len(qt), len(bt)) >= 6:
cont = len(qt & bt) / min(len(qt), len(bt))
if cont >= 0.75:
hits.append((r["id"], i, "token_containment", round(cont, 3))); continue
jac = len(qs & bs) / max(1, len(qs | bs))
if jac >= 0.5:
hits.append((r["id"], i, "shingle_jaccard", round(jac, 3)))
if hits:
print(f"CONTAMINATION CANDIDATES ({len(hits)}):")
for h in hits[:50]:
print(" ", h)
sys.exit(1)
print(f"decontamination clean: 0 overlaps against {len(bench)} benchmark questions "
f"(substring; token containment >= 0.75; shingle-5 Jaccard >= 0.5)")
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--decontaminate", metavar="BENCHMARKS", default=None,
help="containment check of all questions vs benchmark dumps "
"(.jsonl file or directory of .jsonl files)")
args = ap.parse_args()
if args.decontaminate:
decontaminate(args.decontaminate)
else:
rebuild()