File size: 8,835 Bytes
f1e7502 | 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 | #!/usr/bin/env python3
"""Build the minimal, fully rehydrated WildDelusion benchmark release."""
from __future__ import annotations
import argparse
import hashlib
import json
from collections import Counter
from pathlib import Path
from typing import Any
import pyarrow as pa
import pyarrow.parquet as pq
ROLE_ALIASES = {
"user": "user",
"human": "user",
"assistant": "assistant",
"llm": "assistant",
"model": "assistant",
"ai": "assistant",
}
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--verified-targets", type=Path, required=True)
parser.add_argument("--rehydrated-histories", type=Path, required=True)
parser.add_argument("--output-dir", type=Path, default=Path("hf_dataset"))
return parser.parse_args()
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def target_key(row: dict[str, Any]) -> tuple[str, str]:
return str(row["source"]), str(row["message_hash"])
def normalize_messages(messages: list[dict[str, Any]]) -> list[dict[str, str]]:
normalized = []
for message in messages:
raw_role = str(message.get("role", "")).strip().lower()
role = ROLE_ALIASES.get(raw_role)
if role is None:
raise ValueError(f"Unsupported message role: {raw_role!r}")
content = str(message.get("content") or "")
if not content:
raise ValueError("Empty message content in rehydrated transcript")
normalized.append({"role": role, "content": content})
return normalized
def canonical_digest(rows: list[dict[str, Any]]) -> str:
payload = json.dumps(
rows,
ensure_ascii=False,
sort_keys=True,
separators=(",", ":"),
).encode("utf-8")
return hashlib.sha256(payload).hexdigest()
def main() -> None:
args = parse_args()
verified = pq.read_table(args.verified_targets).to_pylist()
rehydrated = pq.read_table(args.rehydrated_histories).to_pylist()
history_by_key = {target_key(row): row for row in rehydrated}
if len(history_by_key) != len(rehydrated):
raise ValueError("Rehydrated input contains duplicate source/message keys")
rows: list[dict[str, Any]] = []
history_methods: Counter[str] = Counter()
unavailable_nontext_rows = 0
unavailable_nontext_messages = 0
for verified_row in verified:
key = target_key(verified_row)
if key not in history_by_key:
raise ValueError(f"No rehydrated history for {key}")
history = history_by_key[key]
messages = normalize_messages(history["messages"])
target_index = int(history["target_message_index"])
target_text = str(verified_row["target_text"])
if not bool(history.get("history_complete")):
raise ValueError(f"History is not marked complete for {key}")
if not 0 <= target_index < len(messages):
raise ValueError(f"Target index is out of range for {key}")
if messages[target_index]["role"] != "user":
raise ValueError(f"Target does not point to a user turn for {key}")
if messages[target_index]["content"] != target_text:
raise ValueError(f"Target text/index mismatch for {key}")
if str(history["target_text"]) != target_text:
raise ValueError(f"Verified and rehydrated target text differ for {key}")
if not any(message["role"] == "assistant" for message in messages):
raise ValueError(f"Transcript has no assistant messages for {key}")
unavailable = int(history.get("history_unavailable_message_count") or 0)
unavailable_nontext_rows += int(unavailable > 0)
unavailable_nontext_messages += unavailable
history_methods[str(history.get("history_rehydration_method"))] += 1
rows.append(
{
"example_id": str(verified_row["message_hash"]),
"source": str(verified_row["source"]),
"conversation_id": str(verified_row["conversation_id"]),
"messages": messages,
"target_message_index": target_index,
"target_text": target_text,
}
)
if len(rows) != len(verified):
raise ValueError("Output row count differs from verified target count")
if len({row["example_id"] for row in rows}) != len(rows):
raise ValueError("Output contains duplicate example IDs")
schema = pa.schema(
[
pa.field("example_id", pa.string(), nullable=False),
pa.field("source", pa.string(), nullable=False),
pa.field("conversation_id", pa.string(), nullable=False),
pa.field(
"messages",
pa.list_(
pa.struct(
[
pa.field("role", pa.string(), nullable=False),
pa.field("content", pa.string(), nullable=False),
]
)
),
nullable=False,
),
pa.field("target_message_index", pa.int32(), nullable=False),
pa.field("target_text", pa.string(), nullable=False),
]
)
data_dir = args.output_dir / "data"
data_dir.mkdir(parents=True, exist_ok=True)
output_path = data_dir / "train-00000-of-00001.parquet"
table = pa.Table.from_pylist(rows, schema=schema)
pq.write_table(table, output_path, compression="zstd")
role_counts = Counter(
message["role"] for row in rows for message in row["messages"]
)
source_counts = Counter(row["source"] for row in rows)
prior_assistant_rows = sum(
any(message["role"] == "assistant" for message in row["messages"][: row["target_message_index"]])
for row in rows
)
integrity = {
"passed": True,
"rows": len(rows),
"distinct_source_conversations": len(
{(row["source"], row["conversation_id"]) for row in rows}
),
"duplicate_example_ids": 0,
"target_index_errors": 0,
"target_text_errors": 0,
"non_user_targets": 0,
"rows_without_assistant_messages": 0,
"rows_with_prior_assistant_context": prior_assistant_rows,
"rows_without_prior_assistant_context": len(rows) - prior_assistant_rows,
"message_role_counts": dict(sorted(role_counts.items())),
"message_count_total": sum(len(row["messages"]) for row in rows),
"message_count_min": min(len(row["messages"]) for row in rows),
"message_count_max": max(len(row["messages"]) for row in rows),
"rows_with_nontext_assistant_placeholders": unavailable_nontext_rows,
"nontext_assistant_placeholders": unavailable_nontext_messages,
"history_rehydration_method_counts": dict(sorted(history_methods.items())),
"parquet_sha256": sha256(output_path),
"canonical_sha256": canonical_digest(rows),
}
manifest = {
"dataset": "danielfein/WildDelusionBenchmark",
"unit": "Gemini-verified user target turn in a complete source conversation",
"rows": len(rows),
"source_target_counts": dict(sorted(source_counts.items())),
"selection": {
"source_dataset": "danielfein/WildDelusionCombined",
"source_revision": "4749e769261c6b068da4a42aa0f91ff4903c2985",
"source_parquet_sha256": sha256(args.verified_targets),
"judge_model": "gemini-3-flash-preview",
"taxonomy": "Moore et al. user-endorses-delusion",
"threshold": 7,
"required_views": ["target_only", "three_preceding_turns"],
"pre_filter_rows": len(rehydrated),
"retained_rows": len(rows),
},
"history": {
"rehydrated_parquet_sha256": sha256(args.rehydrated_histories),
"sharechat_revision": "6fb3e27bba4185e8c05f9b8b3c5ca972192ad036",
"wildchat_revision": "eedff4afb0239e69217ffd1c276e2ba45bbfdd45",
"roles_normalized_to": ["user", "assistant"],
},
"data_file": str(output_path.relative_to(args.output_dir)),
"data_file_sha256": integrity["parquet_sha256"],
"integrity_report": "integrity_report.json",
}
(args.output_dir / "integrity_report.json").write_text(
json.dumps(integrity, indent=2) + "\n", encoding="utf-8"
)
(args.output_dir / "manifest.json").write_text(
json.dumps(manifest, indent=2) + "\n", encoding="utf-8"
)
print(json.dumps({"manifest": manifest, "integrity": integrity}, indent=2))
if __name__ == "__main__":
main()
|