bactrainus-hotpotqa / scripts /validate_release.py
Iman998's picture
Publish complete validated Bactrainus HotpotQA training data
7f3a1d4 verified
Raw
History Blame Contribute Delete
27.1 kB
#!/usr/bin/env python3
"""Validate a Bactrainus HotpotQA dataset release and write SHA-256 checksums.
The validator is intentionally strict. It accepts only the documented,
train-only configurations and writes the checksum manifest only after every
schema, identity, content, and cross-configuration check succeeds.
"""
from __future__ import annotations
import argparse
import hashlib
import os
import re
import sys
import tempfile
from collections import Counter
from collections.abc import Iterable, Iterator, Sequence
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
try:
import pyarrow as pa
import pyarrow.parquet as pq
except ModuleNotFoundError: # Report a concise installation hint in main().
pa = None # type: ignore[assignment]
pq = None # type: ignore[assignment]
EXPECTED_ROWS = 90_447
MIN_PARAGRAPHS = 2
MAX_PARAGRAPHS = 10
EXPECTED_PARAGRAPH_COUNTS = {
2: 262,
3: 156,
4: 94,
5: 88,
6: 53,
7: 77,
8: 60,
9: 48,
10: 89_609,
}
EXPECTED_DIFFICULTY_COUNTS = {
"easy": 17_972,
"medium": 56_814,
"hard": 15_661,
}
CONFIGS = (
"structured",
"reader-sft",
"cot-reader-sft",
"paragraph-selector-sft",
"question-decomposer-sft",
"sentence-selector-sft",
"decomposed-sentence-selector-sft",
"joint-selector-reader-sft",
)
EXPECTED_TASKS = {
"reader-sft": "reader",
"cot-reader-sft": "cot_reader",
"paragraph-selector-sft": "paragraph_selector",
"question-decomposer-sft": "question_decomposer",
"sentence-selector-sft": "sentence_selector",
"decomposed-sentence-selector-sft": "decomposed_sentence_selector",
"joint-selector-reader-sft": "joint_selector_reader",
}
STRUCTURED_FIELDS = frozenset(
{
"source_id",
"question",
"answer",
"question_type",
"difficulty",
"candidate_paragraphs",
"supporting_facts",
"gold_paragraph_titles",
}
)
SFT_FIELDS = frozenset({"source_id", "task", "messages"})
ALLOWED_QUESTION_TYPES = frozenset({"bridge", "comparison"})
ALLOWED_DIFFICULTIES = frozenset(EXPECTED_DIFFICULTY_COUNTS)
ALLOWED_MESSAGE_ROLES = frozenset({"system", "user", "assistant"})
# These names indicate benchmark leakage or bundled experimental outputs. The
# check applies recursively to nested Parquet fields after identifier tokenizing.
FORBIDDEN_FIELD_TOKENS = frozenset(
{
"dev",
"test",
"validation",
"eval",
"evaluation",
"prediction",
"predictions",
"metric",
"metrics",
"score",
"scores",
"result",
"results",
"leaderboard",
"accuracy",
"f1",
"exactmatch",
"response",
"responses",
"output",
"outputs",
"generation",
"generations",
}
)
FORBIDDEN_FILENAME_TOKENS = FORBIDDEN_FIELD_TOKENS
@dataclass
class Problems:
"""Collect a bounded number of actionable validation errors."""
limit: int = 100
items: list[str] = field(default_factory=list)
suppressed: int = 0
def add(self, message: str) -> None:
if len(self.items) < self.limit:
self.items.append(message)
else:
self.suppressed += 1
@property
def any(self) -> bool:
return bool(self.items) or self.suppressed > 0
def render(self) -> str:
lines = [f" - {item}" for item in self.items]
if self.suppressed:
lines.append(f" - ... {self.suppressed} additional error(s) suppressed")
return "\n".join(lines)
@dataclass(frozen=True)
class ConfigStats:
"""Validated summary for one configuration."""
name: str
rows: int
unique_ids: int
shards: int
def identifier_tokens(value: str) -> set[str]:
"""Normalize a field or filename into lowercase alphanumeric tokens."""
return {token for token in re.split(r"[^a-z0-9]+", value.lower()) if token}
def walk_arrow_type(data_type: Any, prefix: str) -> Iterator[str]:
"""Yield nested paths contained by an Arrow type."""
assert pa is not None
if pa.types.is_struct(data_type):
for child in data_type:
child_path = f"{prefix}.{child.name}"
yield child_path
yield from walk_arrow_type(child.type, child_path)
elif (
pa.types.is_list(data_type)
or pa.types.is_large_list(data_type)
or pa.types.is_fixed_size_list(data_type)
):
yield from walk_arrow_type(data_type.value_type, prefix)
elif pa.types.is_map(data_type):
yield from walk_arrow_type(data_type.key_type, f"{prefix}.key")
yield from walk_arrow_type(data_type.item_type, f"{prefix}.value")
def iter_schema_paths(schema: Any) -> Iterator[str]:
"""Yield every top-level and nested Arrow field path."""
for arrow_field in schema:
yield arrow_field.name
yield from walk_arrow_type(arrow_field.type, arrow_field.name)
def check_schema_for_forbidden_fields(
config: str,
schema: Any,
problems: Problems,
) -> None:
"""Reject fields associated with evaluation records or experimental output."""
for path in iter_schema_paths(schema):
matched = identifier_tokens(path) & FORBIDDEN_FIELD_TOKENS
if matched:
labels = ", ".join(sorted(matched))
problems.add(
f"{config}: forbidden evaluation/result field '{path}' "
f"(matched: {labels})"
)
def require_fields(
config: str,
available: set[str],
required: frozenset[str],
problems: Problems,
) -> bool:
"""Check that a Parquet schema contains its documented required fields."""
missing = sorted(required - available)
if missing:
problems.add(f"{config}: missing required field(s): {', '.join(missing)}")
return False
return True
def clean_source_id(value: Any, context: str, problems: Problems) -> str | None:
"""Validate and return a canonical source ID."""
if not isinstance(value, str) or not value.strip():
problems.add(f"{context}: source_id must be a non-empty string")
return None
if value != value.strip():
problems.add(f"{context}: source_id contains leading or trailing whitespace")
return None
return value
def validate_candidate_paragraphs(
value: Any,
context: str,
problems: Problems,
) -> dict[str, list[str]] | None:
"""Validate the canonical candidate set and return title-to-sentences."""
if not isinstance(value, list):
problems.add(f"{context}: candidate_paragraphs must be a list")
return None
if not MIN_PARAGRAPHS <= len(value) <= MAX_PARAGRAPHS:
problems.add(
f"{context}: expected {MIN_PARAGRAPHS} to {MAX_PARAGRAPHS} "
f"candidate paragraphs, found {len(value)}"
)
by_title: dict[str, list[str]] = {}
structurally_valid = True
for position, paragraph in enumerate(value):
item_context = f"{context}.candidate_paragraphs[{position}]"
if not isinstance(paragraph, dict):
problems.add(f"{item_context}: paragraph must be a struct")
structurally_valid = False
continue
title = paragraph.get("title")
sentences = paragraph.get("sentences")
if not isinstance(title, str) or not title.strip():
problems.add(f"{item_context}.title: expected a non-empty string")
structurally_valid = False
continue
if title in by_title:
problems.add(f"{item_context}.title: duplicate candidate title {title!r}")
structurally_valid = False
continue
if not isinstance(sentences, list) or not sentences:
problems.add(f"{item_context}.sentences: expected a non-empty list")
structurally_valid = False
continue
if any(not isinstance(sentence, str) for sentence in sentences):
problems.add(f"{item_context}.sentences: every sentence must be a string")
structurally_valid = False
continue
by_title[title] = sentences
if not structurally_valid or not MIN_PARAGRAPHS <= len(value) <= MAX_PARAGRAPHS:
return None
return by_title
def validate_supporting_facts(
value: Any,
paragraphs: dict[str, list[str]] | None,
context: str,
problems: Problems,
) -> list[str] | None:
"""Validate evidence title/index pairs and return unique titles in order."""
if not isinstance(value, list) or not value:
problems.add(f"{context}: supporting_facts must be a non-empty list")
return None
valid = True
ordered_titles: list[str] = []
seen_titles: set[str] = set()
for position, fact in enumerate(value):
item_context = f"{context}.supporting_facts[{position}]"
if not isinstance(fact, dict):
problems.add(f"{item_context}: supporting fact must be a struct")
valid = False
continue
title = fact.get("title")
sentence_index = fact.get("sentence_index")
if not isinstance(title, str) or not title.strip():
problems.add(f"{item_context}.title: expected a non-empty string")
valid = False
continue
if not isinstance(sentence_index, int) or isinstance(sentence_index, bool):
problems.add(f"{item_context}.sentence_index: expected an integer")
valid = False
continue
if paragraphs is None:
valid = False
continue
if title not in paragraphs:
problems.add(f"{item_context}: evidence title {title!r} is not a candidate")
valid = False
continue
if sentence_index < 0 or sentence_index >= len(paragraphs[title]):
problems.add(
f"{item_context}: sentence_index {sentence_index} is outside "
f"[0, {len(paragraphs[title])}) for {title!r}"
)
valid = False
continue
if title not in seen_titles:
seen_titles.add(title)
ordered_titles.append(title)
return ordered_titles if valid else None
def validate_gold_titles(
value: Any,
expected: list[str] | None,
context: str,
problems: Problems,
) -> None:
"""Check the order-preserving unique supporting-paragraph title list."""
if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
problems.add(f"{context}: gold_paragraph_titles must be a list of strings")
return
if expected is not None and value != expected:
problems.add(
f"{context}: gold_paragraph_titles does not equal the order-preserving "
"unique supporting-fact titles"
)
def validate_nonempty_text(
value: Any, field_name: str, context: str, problems: Problems
) -> None:
"""Require a non-empty textual scalar."""
if not isinstance(value, str) or not value.strip():
problems.add(f"{context}.{field_name}: expected a non-empty string")
def validate_messages(value: Any, context: str, problems: Problems) -> None:
"""Validate the documented role/content SFT chat representation."""
if not isinstance(value, list) or len(value) < 2:
problems.add(
f"{context}: messages must contain at least user and assistant turns"
)
return
roles: list[str] = []
for position, message in enumerate(value):
item_context = f"{context}.messages[{position}]"
if not isinstance(message, dict):
problems.add(f"{item_context}: message must be a struct")
continue
role = message.get("role")
content = message.get("content")
if role not in ALLOWED_MESSAGE_ROLES:
problems.add(
f"{item_context}.role: expected one of "
f"{sorted(ALLOWED_MESSAGE_ROLES)}, found {role!r}"
)
else:
roles.append(role)
if not isinstance(content, str) or not content.strip():
problems.add(f"{item_context}.content: expected a non-empty string")
if "user" not in roles:
problems.add(f"{context}: messages does not contain a user turn")
if roles and roles[-1] != "assistant":
problems.add(f"{context}: final message must be the assistant training target")
def validate_structured_row(
row: dict[str, Any],
context: str,
problems: Problems,
difficulty_counts: Counter[str],
paragraph_counts: Counter[int],
) -> None:
"""Validate one canonical HotpotQA record."""
validate_nonempty_text(row.get("question"), "question", context, problems)
validate_nonempty_text(row.get("answer"), "answer", context, problems)
question_type = row.get("question_type")
if question_type not in ALLOWED_QUESTION_TYPES:
problems.add(
f"{context}.question_type: expected one of "
f"{sorted(ALLOWED_QUESTION_TYPES)}, found {question_type!r}"
)
difficulty = row.get("difficulty")
if difficulty not in ALLOWED_DIFFICULTIES:
problems.add(
f"{context}.difficulty: expected one of "
f"{sorted(ALLOWED_DIFFICULTIES)}, found {difficulty!r}"
)
else:
difficulty_counts[difficulty] += 1
paragraphs = validate_candidate_paragraphs(
row.get("candidate_paragraphs"), context, problems
)
candidate_value = row.get("candidate_paragraphs")
if isinstance(candidate_value, list):
paragraph_counts[len(candidate_value)] += 1
evidence_titles = validate_supporting_facts(
row.get("supporting_facts"), paragraphs, context, problems
)
validate_gold_titles(
row.get("gold_paragraph_titles"), evidence_titles, context, problems
)
def validate_sft_row(row: dict[str, Any], context: str, problems: Problems) -> None:
"""Validate one deterministic supervised-fine-tuning record."""
validate_nonempty_text(row.get("task"), "task", context, problems)
validate_messages(row.get("messages"), context, problems)
# If a task view retains canonical evidence columns, validate them rather
# than allowing malformed duplicated provenance to pass unnoticed.
has_paragraphs = "candidate_paragraphs" in row
has_facts = "supporting_facts" in row
if has_paragraphs != has_facts:
problems.add(
f"{context}: candidate_paragraphs and supporting_facts must be retained together"
)
elif has_paragraphs:
paragraphs = validate_candidate_paragraphs(
row.get("candidate_paragraphs"), context, problems
)
validate_supporting_facts(
row.get("supporting_facts"), paragraphs, context, problems
)
def parquet_files_for_config(root: Path, config: str, problems: Problems) -> list[Path]:
"""Return the complete, train-only shard set for a configuration."""
config_dir = root / "data" / config
if not config_dir.is_dir():
problems.add(f"{config}: missing directory {config_dir.relative_to(root)}")
return []
all_parquet = sorted(config_dir.rglob("*.parquet"))
shards = sorted(config_dir.glob("train-*.parquet"))
if not shards:
problems.add(f"{config}: no data/{config}/train-*.parquet shards found")
unexpected = sorted(set(all_parquet) - set(shards))
for path in unexpected:
problems.add(
f"{config}: unexpected Parquet file {path.relative_to(root).as_posix()}; "
"only direct train-*.parquet shards are allowed"
)
for path in all_parquet:
matched = identifier_tokens(path.name) & FORBIDDEN_FILENAME_TOKENS
if matched:
problems.add(
f"{config}: forbidden filename {path.name!r} "
f"(matched: {', '.join(sorted(matched))})"
)
return shards
def reject_unsupported_configs(root: Path, problems: Problems) -> None:
"""Allow only documented config directories and Parquet data files."""
data_dir = root / "data"
if not data_dir.is_dir():
problems.add("missing data directory")
return
allowed = set(CONFIGS)
for child in sorted(data_dir.iterdir()):
if child.is_dir() and child.name not in allowed:
problems.add(
f"unsupported dataset configuration directory: data/{child.name}"
)
elif child.is_file() and child.suffix.lower() == ".parquet":
problems.add(
f"Parquet files must be stored under data/<config>: data/{child.name}"
)
for path in sorted(data_dir.rglob("*")):
if path.is_file() and path.suffix.lower() != ".parquet":
problems.add(
f"unexpected non-Parquet data artifact: "
f"{path.relative_to(root).as_posix()}"
)
def iter_rows(
parquet_file: Any, columns: Sequence[str], batch_size: int
) -> Iterator[dict[str, Any]]:
"""Yield selected Parquet columns as Python records in bounded batches."""
for batch in parquet_file.iter_batches(
batch_size=batch_size, columns=list(columns)
):
yield from batch.to_pylist()
def validate_config(
root: Path,
config: str,
problems: Problems,
batch_size: int,
) -> tuple[ConfigStats, set[str], list[Path]]:
"""Validate all shards in one configuration."""
assert pq is not None
shards = parquet_files_for_config(root, config, problems)
if not shards:
return ConfigStats(config, 0, 0, 0), set(), []
required = STRUCTURED_FIELDS if config == "structured" else SFT_FIELDS
reference_schema = None
ids: set[str] = set()
row_count = 0
difficulty_counts: Counter[str] = Counter()
paragraph_counts: Counter[int] = Counter()
observed_tasks: set[str] = set()
for shard in shards:
relative = shard.relative_to(root).as_posix()
try:
parquet_file = pq.ParquetFile(shard)
schema = parquet_file.schema_arrow
except (OSError, TypeError, ValueError) as exc:
problems.add(f"{config}: cannot open {relative}: {exc}")
continue
if reference_schema is None:
reference_schema = schema
elif not reference_schema.equals(schema, check_metadata=False):
problems.add(f"{config}: schema drift detected in {relative}")
available = set(schema.names)
check_schema_for_forbidden_fields(config, schema, problems)
if not require_fields(config, available, required, problems):
continue
if config != "structured" and (
("candidate_paragraphs" in available) != ("supporting_facts" in available)
):
problems.add(
f"{config}: candidate_paragraphs and supporting_facts must be "
f"retained together in {relative}"
)
selected = list(required)
if config != "structured" and {
"candidate_paragraphs",
"supporting_facts",
}.issubset(available):
selected.extend(["candidate_paragraphs", "supporting_facts"])
try:
for row in iter_rows(parquet_file, selected, batch_size):
row_count += 1
context = f"{config}[row={row_count}, shard={shard.name}]"
source_id = clean_source_id(row.get("source_id"), context, problems)
if source_id is not None:
if source_id in ids:
problems.add(f"{context}: duplicate source_id {source_id!r}")
else:
ids.add(source_id)
if config == "structured":
validate_structured_row(
row,
context,
problems,
difficulty_counts,
paragraph_counts,
)
else:
task = row.get("task")
if isinstance(task, str) and task.strip():
observed_tasks.add(task)
validate_sft_row(row, context, problems)
except (OSError, TypeError, ValueError) as exc:
problems.add(f"{config}: failed while reading {relative}: {exc}")
if row_count != EXPECTED_ROWS:
problems.add(f"{config}: expected {EXPECTED_ROWS:,} rows, found {row_count:,}")
if len(ids) != EXPECTED_ROWS:
problems.add(
f"{config}: expected {EXPECTED_ROWS:,} unique source IDs, found {len(ids):,}"
)
if config == "structured" and dict(difficulty_counts) != EXPECTED_DIFFICULTY_COUNTS:
problems.add(
f"structured: unexpected difficulty counts; expected "
f"{EXPECTED_DIFFICULTY_COUNTS}, found {dict(difficulty_counts)}"
)
if config == "structured" and dict(paragraph_counts) != EXPECTED_PARAGRAPH_COUNTS:
problems.add(
"structured: unexpected candidate-paragraph distribution; expected "
f"{EXPECTED_PARAGRAPH_COUNTS}, found {dict(paragraph_counts)}"
)
if config != "structured" and len(observed_tasks) != 1:
problems.add(
f"{config}: expected one stable non-empty task identifier, "
f"found {sorted(observed_tasks)!r}"
)
if config != "structured" and observed_tasks != {EXPECTED_TASKS[config]}:
problems.add(
f"{config}: expected task {EXPECTED_TASKS[config]!r}, "
f"found {sorted(observed_tasks)!r}"
)
return ConfigStats(config, row_count, len(ids), len(shards)), ids, shards
def compare_id_sets(id_sets: dict[str, set[str]], problems: Problems) -> None:
"""Require every deterministic task view to use the canonical ID set."""
canonical = id_sets.get("structured", set())
for config in CONFIGS[1:]:
current = id_sets.get(config, set())
missing = canonical - current
extra = current - canonical
if missing or extra:
missing_sample = sorted(missing)[:5]
extra_sample = sorted(extra)[:5]
problems.add(
f"{config}: source-ID set differs from structured "
f"(missing={len(missing):,}, extra={len(extra):,}, "
f"missing_sample={missing_sample!r}, extra_sample={extra_sample!r})"
)
def sha256_file(path: Path, chunk_size: int = 1024 * 1024) -> str:
"""Compute a file SHA-256 digest without loading it into memory."""
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(chunk_size), b""):
digest.update(chunk)
return digest.hexdigest()
def resolve_manifest_path(root: Path, manifest_argument: str) -> Path:
"""Resolve a manifest path and prevent writes outside the release root."""
candidate = Path(manifest_argument)
target = (candidate if candidate.is_absolute() else root / candidate).resolve()
try:
target.relative_to(root)
except ValueError as exc:
raise ValueError("checksum manifest must be located inside --root") from exc
return target
def write_checksum_manifest(root: Path, files: Iterable[Path], manifest: Path) -> None:
"""Atomically write sorted SHA-256 entries for validated Parquet shards."""
unique_files = sorted(
set(files), key=lambda path: path.relative_to(root).as_posix()
)
entries = [
f"{sha256_file(path)} {path.relative_to(root).as_posix()}"
for path in unique_files
]
manifest.parent.mkdir(parents=True, exist_ok=True)
temp_name = ""
try:
with tempfile.NamedTemporaryFile(
mode="w",
encoding="utf-8",
newline="\n",
dir=manifest.parent,
prefix=f".{manifest.name}.",
suffix=".tmp",
delete=False,
) as handle:
temp_name = handle.name
handle.write("\n".join(entries) + "\n")
os.replace(temp_name, manifest)
finally:
if temp_name:
Path(temp_name).unlink(missing_ok=True)
def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
"""Parse command-line arguments."""
package_root = Path(__file__).resolve().parents[1]
parser = argparse.ArgumentParser(
description=(
"Validate all Bactrainus HotpotQA train configurations and "
"write a SHA-256 manifest after success."
)
)
parser.add_argument(
"--root",
type=Path,
default=package_root,
help=f"dataset repository root (default: {package_root})",
)
parser.add_argument(
"--manifest",
default="CHECKSUMS.sha256",
help="manifest path relative to --root (default: CHECKSUMS.sha256)",
)
parser.add_argument(
"--batch-size",
type=int,
default=2_048,
help="Parquet validation batch size (default: 2048)",
)
return parser.parse_args(argv)
def main(argv: Sequence[str] | None = None) -> int:
"""Run release validation and checksum generation."""
args = parse_args(argv)
if pa is None or pq is None:
print(
"error: pyarrow is required; install it with `python -m pip install pyarrow`",
file=sys.stderr,
)
return 2
if args.batch_size <= 0:
print("error: --batch-size must be positive", file=sys.stderr)
return 2
root = args.root.resolve()
if not root.is_dir():
print(f"error: dataset root does not exist: {root}", file=sys.stderr)
return 2
try:
manifest = resolve_manifest_path(root, args.manifest)
except ValueError as exc:
print(f"error: {exc}", file=sys.stderr)
return 2
problems = Problems()
reject_unsupported_configs(root, problems)
stats: list[ConfigStats] = []
id_sets: dict[str, set[str]] = {}
parquet_files: list[Path] = []
for config in CONFIGS:
config_stats, config_ids, config_files = validate_config(
root, config, problems, args.batch_size
)
stats.append(config_stats)
id_sets[config] = config_ids
parquet_files.extend(config_files)
compare_id_sets(id_sets, problems)
if problems.any:
print("Release validation failed:\n" + problems.render(), file=sys.stderr)
print("The checksum manifest was not updated.", file=sys.stderr)
return 1
write_checksum_manifest(root, parquet_files, manifest)
for item in stats:
print(
f"{item.name}: {item.rows:,} rows, {item.unique_ids:,} unique IDs, "
f"{item.shards} shard(s)"
)
print(
f"Validated {len(CONFIGS)} configurations and {len(parquet_files)} Parquet shards."
)
print(f"Wrote SHA-256 manifest: {manifest.relative_to(root).as_posix()}")
return 0
if __name__ == "__main__":
raise SystemExit(main())