File size: 42,053 Bytes
3f83737 | 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 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 | """HoVer TRAIN -> v4 class-A rows (component di_retrieval): many-hop claim verification over retrieved passages.
Contract: V4_DATA_CONTRACT_2026-09-25.md (class A, U1 approved 09-25). Output:
``data/synth-v4/classA/hover_train/{train,dev}.jsonl`` + ``manifest.json`` (+ ``_source/`` holding the pinned raw
HoVer train file). Nothing here enters a pool: the T11 gate (G5: hpqa_id / claim MinHash / paragraph hash) runs later.
Sources
-------
* **Claims + labels**: HoVer (Jiang et al. 2020, arXiv:2011.03088), ``hover_train_release_v1.1.json`` from the
GitHub repo ``hover-nlp/hover`` pinned at commit ``39b8469...`` (the HF dataset ``hover-nlp/hover`` is a loading
script that points at exactly this file; its card declares CC BY-SA 4.0; the GitHub repo LICENSE is MIT). ONLY the
train file is downloaded or read. ``hover_dev_release_v1.1.json`` (the scored split) and the unlabeled test file
are never fetched.
* **Paragraphs**: HoVer ships only (title, sentence-id) pointers into the 2017 Wikipedia intro-paragraph dump that
HotpotQA also uses. We reconstruct the paragraphs from the HotpotQA *train* distractor contexts already on disk
(``hotpotqa/hotpot_qa`` @1908d6a, both ``distractor/train-0000{0,1}-of-00002.parquet`` shards, CC BY-SA
4.0, sha256 verified; shard 0 is read in place from data/downloads, shard 1 is fetched into ``_source/``).
A claim is kept only if every supporting-fact title is present there and every sentence id is in range. The
HotpotQA validation file is never read.
Rows
----
One row per claim. ``state`` is a JSON object with our own field names: ``evidence_pool`` = list of
``{doc, page, body}`` (gold paragraphs + 1-2 distractor paragraphs, shuffled); in ~30% of rows the claim sits in
``state.claim_under_review`` instead of the question text. Question is ``noul`` (true = the passages support the
claim) or a 2-way ``choice`` whose option names are drawn from a small pool, in seeded order. Labels are HoVer's
source labels (SUPPORTED / NOT_SUPPORTED). Distractors come first from the claim's own HotpotQA context (TF-IDF hard
negatives), then from contexts in which the gold pages appear.
Selection & splits
------------------
≈1,800 claims, stratified by (num_hops, label) in the natural proportions of the full HoVer train file (label prior
= HoVer train's own distribution), ≤2 claims per hpqa_id, hash-ordered. Clusters: union-find over rows sharing an
hpqa_id or a gold page, so no page is gold in both splits. ≈7% of rows (whole clusters, none larger than 12 rows)
are held out as dev (``meta.dev_pool = "DIS"``); dev distractors never use a page that appears in any train state.
``group_id`` = ``hover_hpqa:<hpqa_id>`` (contract §7: HoVer clusters by hpqa_id); ``meta.split_cluster`` names the
wider union-find cluster. Deterministic: every random choice is seeded from sha256(seed, key).
Run: ``PYTHONPATH=src:. python -m macjev.v4data.classa_hover_train [--no-token-check] [--no-exclusions] [--offline]``
"""
from __future__ import annotations
import argparse
import collections
import hashlib
import json
import random
import re
import statistics
import urllib.request
from pathlib import Path
from typing import Callable
from ..paths import DATA_V3, DOWNLOADS, ROOT
from ..schema import content_hash, make_record, normalise_text
from . import rowspec
BUILDER_VERSION = "classa_hover_train-v1"
MODULE = "macjev.v4data.classa_hover_train"
NAME = "hover_train"
FAMILY = "hover_claim_verification"
CATEGORY = "v4_classA_hover_claim_verification"
COMPONENT = "di_retrieval"
SEED = 20260925
OUT_DIR = ROOT / "data" / "synth-v4" / "classA" / NAME
SRC_DIR = OUT_DIR / "_source"
EXCLUSIONS = DATA_V3 / "exclusions"
TOKENIZER_DIR = ROOT / "models" / "bases" / "Qwen--Qwen3.5-2B" / "15852e8c16360a2fea060d615a32b45270f8a8fc"
DI_BENCHMARK_NAME = "HoVer"
DI_BENCHMARK_ID_EXPECTED = 61
# --- HoVer (claims, labels) ---------------------------------------------------------------------------------------
REPO = "hover-nlp/hover" # HF dataset (loading script + card)
HF_REVISION = "c0e43052759879b3461642ca6c0dd26658f47691"
GH_REPO = "hover-nlp/hover"
GH_COMMIT = "39b84697f196308f398a251a7aea9b82ae0f0562"
TRAIN_FILE = "data/hover/hover_train_release_v1.1.json"
TRAIN_URL = f"https://raw.githubusercontent.com/{GH_REPO}/{GH_COMMIT}/{TRAIN_FILE}"
TRAIN_SHA256 = "1f1cd57abd616fa00c70bdc575ce77c16fc6cf1a6cffd5ff87c208030a336bb6"
TRAIN_GIT_BLOB = "49a36d7eb2f319329264b546cb687f54b8f1990f"
TRAIN_BYTES = 9205582
LICENSE = "cc-by-sa-4.0"
NEVER_READ = ("data/hover/hover_dev_release_v1.1.json", "data/hover/hover_test_release_v1.1.json")
# --- HotpotQA (paragraph text) ------------------------------------------------------------------------------------
HP_REPO = "hotpotqa/hotpot_qa"
HP_REVISION = "1908d6afbbead072334abe2965f91bd2709910ab"
# shard 0 is already on disk (data/downloads, fetched by an earlier builder); shard 1 is fetched into our own _source/
HP_SHARDS = {
"s0": {"file": "distractor/train-00000-of-00002.parquet",
"sha256": "76d3bb3048a7cc73c1958107c0c5872a00d7e7d00c105b81e92f6769e7822e68", "bytes": 165624177,
"local": DOWNLOADS / "hotpotqa--hotpot_qa" / HP_REVISION / "distractor/train-00000-of-00002.parquet"},
"s1": {"file": "distractor/train-00001-of-00002.parquet",
"sha256": "713661628434fbb19fff7392e2e321e4ed107e3c7c7784d0690946e5f722763f", "bytes": 166162479,
"local": SRC_DIR / "hotpotqa" / "distractor/train-00001-of-00002.parquet"},
}
HP_LICENSE = "cc-by-sa-4.0"
HP_NEVER_READ = ("distractor/validation-00000-of-00001.parquet",)
TARGET_ROWS = 12_000 # v4 10-25: plan §5A 1.5万 (HoVer train 18K claims)
MAX_PER_HPQA = 2
DEV_FRACTION = 0.07
DEV_MAX_CLUSTER_ROWS = 12
DISTRACTOR_CHOICES = (1, 1, 2)
CLAIM_IN_STATE_SHARE = 0.30
NOUL_SHARE = 0.50
MAX_STATE_TOKENS = 1_500
LABELS = {"SUPPORTED": "supported", "NOT_SUPPORTED": "not_supported"}
# Licence gate (same policy as the pub4 builders: unknown / NC / ND refused).
TRAINABLE = ("apache", "mit", "bsd", "cc0", "cc-by-4", "cc-by-3", "cc-by-sa", "odc", "cdla", "openmdw", "generated")
REFUSED_MARKERS = ("-nc", "nc-", "noncommercial", "non-commercial", "-nd", "nd-", "research", "unknown", "unclear",
"other")
class LicenseRefused(ValueError):
pass
def license_gate(license_: str) -> str:
lic = str(license_ or "").strip().lower()
if not lic or not lic.startswith(TRAINABLE) or any(m in lic for m in REFUSED_MARKERS):
raise LicenseRefused(f"licence {license_!r} is not trainable")
return lic
# ---------------------------------------------------------------------------------------------------------------
# Our own instruction pools (written for this module; the claim slot is either the quoted claim or a pointer to
# ``claim_under_review``). NOUL: true <=> the passages support the claim.
# ---------------------------------------------------------------------------------------------------------------
NOUL_INS = [
"Read the pages in `evidence_pool`. Do they, taken together, back up {claim}?",
"Using only the passages in `evidence_pool`, is {claim} supported?",
"Several facts from different pages may need to be combined. Is {claim} fully supported by `evidence_pool`?",
"Fact-check {claim} against `evidence_pool` alone. Does every part of it hold?",
"Treat `evidence_pool` as your only source. Can {claim} be confirmed from it?",
"Chain the relevant passages in `evidence_pool` together. Is {claim} backed by them?",
"Some passages in `evidence_pool` are unrelated. Ignoring those, do the rest confirm {claim}?",
"Verify {claim}: is each detail in it confirmed by the text in `evidence_pool`?",
"Would a careful reader of `evidence_pool` accept {claim} as supported?",
"Answer true only if the passages in `evidence_pool` establish {claim}; any wrong or unconfirmed detail means false.",
"Does `evidence_pool` contain enough to confirm {claim}, with no detail contradicted?",
"Link the entities mentioned across `evidence_pool`. Is {claim} supported by what the pages say?",
"Given the retrieved pages in `evidence_pool`, is {claim} consistent with and supported by them?",
"Check {claim} hop by hop against the pages in `evidence_pool`. Is it supported?",
"Is {claim} true according to the passages in `evidence_pool` (and only those)?",
"The pages in `evidence_pool` were retrieved for a fact-check. Do they support {claim}?",
"Do the pages in `evidence_pool` jointly entail {claim}?",
"A multi-hop check: using the linked facts in `evidence_pool`, does {claim} stand?",
"Judge {claim} strictly from `evidence_pool`. Is it supported in every detail?",
"Based solely on the paragraphs in `evidence_pool`, should {claim} be marked as supported?",
"Combine what the passages in `evidence_pool` say about each entity. Is {claim} backed up?",
"Is every fact asserted in {claim} confirmed somewhere in `evidence_pool`?",
"Can {claim} be verified from `evidence_pool` without outside knowledge?",
"Review `evidence_pool` and decide whether {claim} holds.",
]
CHOICE_INS = [
"Classify {claim} using only the pages in `evidence_pool`.",
"Which verdict does `evidence_pool` justify for {claim}?",
"Fact-check {claim} against the passages in `evidence_pool` and pick the verdict.",
"Several pages must be combined. What is the correct verdict for {claim} given `evidence_pool`?",
"Decide the status of {claim} from `evidence_pool` alone.",
"Some passages in `evidence_pool` are distractors. Using the relevant ones, label {claim}.",
"Chain the facts in `evidence_pool` and choose the verdict for {claim}.",
"Pick the label that fits {claim} given only the text of `evidence_pool`.",
"How should {claim} be labelled after checking every detail against `evidence_pool`?",
"Verify {claim} hop by hop using `evidence_pool`. Which verdict applies?",
"A reviewer has only `evidence_pool`. Which verdict should they give {claim}?",
"Label {claim}: does `evidence_pool` establish it, or not?",
"Given the retrieved passages in `evidence_pool`, choose the right verdict for {claim}.",
"Assess {claim} strictly against `evidence_pool` and select a verdict.",
"Which option describes {claim} once it is checked against the pages in `evidence_pool`?",
"Compare {claim} with the facts stated across `evidence_pool`. Select the verdict.",
"Using the paragraphs in `evidence_pool` as the only evidence, how is {claim} rated?",
"Determine whether `evidence_pool` confirms {claim}; choose the matching option.",
"Read `evidence_pool`, link the entities it mentions, and choose the verdict on {claim}.",
"What verdict follows for {claim} if `evidence_pool` is the whole evidence?",
"Grade {claim} against the retrieved pages in `evidence_pool`.",
"Choose the verdict for {claim} from `evidence_pool`; a single wrong or unconfirmed detail counts against it.",
]
CLAIM_INLINE = ["the claim \"{c}\"", "this claim: \"{c}\"", "the statement \"{c}\"", "the assertion \"{c}\""]
CLAIM_REF = ["the claim in `claim_under_review`", "the statement given in `claim_under_review`",
"the claim stored in `claim_under_review`"]
# (supported key, desc), (not-supported key, desc)
OPTION_PAIRS = [
(("supported", "the passages together confirm every detail of the claim"),
("not_supported", "at least one detail of the claim is contradicted by, or cannot be confirmed from, the passages")),
(("confirmed", "every part of the claim is established by the passages"),
("unconfirmed", "some part of the claim is wrong or not established by the passages")),
(("backed", "the evidence backs the whole claim"),
("not_backed", "the evidence does not back the whole claim: a detail is false or missing")),
(("holds", "the claim holds according to the passages"),
("does_not_hold", "the claim does not hold: the passages contradict or fail to confirm part of it")),
(("verified", "the claim is verified by combining the passages"),
("not_verified", "the claim cannot be verified: some detail is contradicted or absent")),
]
FORBIDDEN_WORDS = ("decision index", "jevbench", "jev")
FORBIDDEN_RE = re.compile(r"\b(?:decision index|jevbench|jev)\b", re.IGNORECASE)
def _h(*parts) -> str:
return hashlib.sha256("\x1f".join(str(p) for p in (SEED, *parts)).encode()).hexdigest()
def _rng(*parts) -> random.Random:
return random.Random(int(_h(*parts)[:16], 16))
def sha256_file(path: Path) -> str:
h = hashlib.sha256()
with Path(path).open("rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
# ---------------------------------------------------------------------------------------------------------------
# Licence evidence and downloads
# ---------------------------------------------------------------------------------------------------------------
def verify_license() -> dict:
"""HF card licence of hover-nlp/hover and hotpotqa/hotpot_qa at pinned revisions (anonymous, not gated), plus the
GitHub LICENSE of the claims repo. Raises LicenseRefused when any source is not trainable."""
from huggingface_hub import HfApi
api = HfApi()
ev = {}
for repo, rev in ((REPO, HF_REVISION), (HP_REPO, HP_REVISION)):
info = api.dataset_info(repo, revision=rev, token=False)
card = info.card_data
lic = card.get("license") if card is not None else None
lics = [lic] if isinstance(lic, str) else list(lic or [])
if info.sha != rev:
raise RuntimeError(f"{repo}: revision mismatch {info.sha} != {rev}")
if info.gated:
raise LicenseRefused(f"{repo} is gated")
if len(lics) != 1:
raise LicenseRefused(f"{repo}: expected exactly one card licence, got {lics}")
license_gate(lics[0])
ev[repo] = {"source": f"HF API dataset_info(token=False) at revision {rev}", "cardData.license": lics,
"tags": [t for t in (info.tags or []) if t.startswith("license:")], "gated": bool(info.gated)}
lic_url = f"https://raw.githubusercontent.com/{GH_REPO}/{GH_COMMIT}/LICENSE"
with urllib.request.urlopen(lic_url, timeout=60) as r:
lic_blob = r.read()
first = lic_blob.decode("utf-8", "replace").strip().splitlines()[0].strip()
spdx = "MIT" if first == "MIT License" else first
license_gate(spdx)
ev[f"github:{GH_REPO}"] = {"source": lic_url, "first_line": first, "spdx_id": spdx,
"sha256": hashlib.sha256(lic_blob).hexdigest(),
"note": "repository (code + data files) LICENSE at the pinned commit; the HF card for "
"the same data declares cc-by-sa-4.0, the stricter one, used for every row "
"(the paragraphs are Wikipedia text, CC BY-SA)"}
return ev
def download_train(dest_dir: Path = SRC_DIR) -> Path:
"""Fetch ONLY the HoVer train file at the pinned commit; verify size + sha256 + git blob id."""
dest = dest_dir / Path(TRAIN_FILE).name
if not (dest.exists() and sha256_file(dest) == TRAIN_SHA256):
dest.parent.mkdir(parents=True, exist_ok=True)
with urllib.request.urlopen(TRAIN_URL, timeout=120) as r:
blob = r.read()
if hashlib.sha256(blob).hexdigest() != TRAIN_SHA256:
raise RuntimeError("sha256 mismatch for HoVer train file")
dest.write_bytes(blob)
blob = dest.read_bytes()
if len(blob) != TRAIN_BYTES or hashlib.sha1(b"blob %d\0" % len(blob) + blob).hexdigest() != TRAIN_GIT_BLOB:
raise RuntimeError("HoVer train file does not match the pinned git blob")
return dest
def load_hover(path: Path) -> list[dict]:
name = Path(path).name
if any(name == Path(f).name for f in NEVER_READ) or "train" not in name:
raise PermissionError(f"refusing to read {name}: only the HoVer TRAIN file may be read")
rows = json.loads(Path(path).read_text(encoding="utf-8"))
return [{"line": i, "uid": r["uid"], "claim": str(r["claim"]).strip(), "label": r["label"],
"num_hops": int(r["num_hops"]), "hpqa_id": str(r["hpqa_id"]),
"supporting_facts": [(str(t), int(s)) for t, s in r["supporting_facts"]]} for i, r in enumerate(rows)]
def download_hotpot_shards() -> dict[str, Path]:
"""Ensure both HotpotQA *train* distractor shards are present at the pinned revision with the pinned sha256.
Shard 0 is read in place; a missing shard 1 is fetched anonymously into our own _source/ directory."""
out = {}
for tag, sh in HP_SHARDS.items():
path = Path(sh["local"])
if not path.exists():
if tag == "s0":
raise FileNotFoundError(f"{path} missing (fetched earlier by the hotpotqa download)")
from huggingface_hub import hf_hub_download
hf_hub_download(HP_REPO, sh["file"], repo_type="dataset", revision=HP_REVISION,
local_dir=SRC_DIR / "hotpotqa", token=False)
if sha256_file(path) != sh["sha256"]:
raise RuntimeError(f"HotpotQA {sh['file']} sha256 mismatch")
out[tag] = path
return out
def load_hotpot(paths: dict[str, Path]) -> list[dict]:
"""HotpotQA train contexts from the given shards; ``row`` is a global index, (``file``, ``file_row``) the origin."""
import pyarrow.parquet as pq
out = []
for tag in sorted(paths):
path = Path(paths[tag])
if Path(path).name in {Path(f).name for f in HP_NEVER_READ} or "train" not in path.name:
raise PermissionError("only HotpotQA train contexts may be read")
for i, r in enumerate(pq.read_table(path, columns=["id", "context"]).to_pylist()):
out.append({"row": len(out), "file": HP_SHARDS.get(tag, {}).get("file", path.name), "file_row": i,
"id": r["id"],
"context": list(zip(r["context"]["title"], [list(s) for s in r["context"]["sentences"]]))})
return out
# ---------------------------------------------------------------------------------------------------------------
# Paragraph index
# ---------------------------------------------------------------------------------------------------------------
class ParagraphIndex:
"""title -> sentence list, reconstructed from HotpotQA train contexts. When a title occurs with different
sentence lists, the claim's own hpqa context wins, else the version seen in most rows (ties: earliest row)."""
def __init__(self, hotpot_rows: list[dict]):
self.versions: dict[str, dict[tuple, list[int]]] = collections.defaultdict(dict)
self.by_id: dict[str, dict] = {}
self.rows_of: dict[str, list[int]] = collections.defaultdict(list)
self.rows = hotpot_rows
for r in hotpot_rows:
self.by_id.setdefault(r["id"], r)
for title, sents in r["context"]:
self.versions[title].setdefault(tuple(sents), []).append(r["row"])
self.rows_of[title].append(r["row"])
self.row_by_idx = {r["row"]: r for r in hotpot_rows}
self.conflicting_titles = sum(1 for v in self.versions.values() if len(v) > 1)
def __contains__(self, title: str) -> bool:
return title in self.versions
def sentences(self, title: str, hpqa_id: str | None = None) -> tuple[list[str], int]:
vers = self.versions[title]
own = self.by_id.get(hpqa_id) if hpqa_id else None
if own is not None:
for t, s in own["context"]:
if t == title:
return list(s), own["row"]
best = min(vers.items(), key=lambda kv: (-len(kv[1]), kv[1][0]))
return list(best[0]), best[1][0]
def own_context_titles(self, hpqa_id: str) -> list[str]:
own = self.by_id.get(hpqa_id)
return [t for t, _ in own["context"]] if own else []
def cocontext_titles(self, titles: list[str]) -> list[str]:
out, seen = [], set()
for t in titles:
for ri in sorted(set(self.rows_of.get(t, [])))[:6]:
for tt, _ in self.row_by_idx[ri]["context"]:
if tt not in seen:
seen.add(tt)
out.append(tt)
return out
def paragraph_text(sents: list[str]) -> str:
return "".join(sents).strip()
# ---------------------------------------------------------------------------------------------------------------
# Candidate filtering, selection, clustering
# ---------------------------------------------------------------------------------------------------------------
def gold_titles(c: dict) -> list[str]:
out = []
for t, _ in c["supporting_facts"]:
if t not in out:
out.append(t)
return out
def filter_candidates(claims: list[dict], idx: ParagraphIndex, dropped: collections.Counter,
excluded: Callable[[str], bool] | None = None) -> list[dict]:
ok = []
for c in claims:
if c["label"] not in LABELS or not c["claim"] or not c["supporting_facts"]:
dropped["bad_or_missing_label_claim_or_facts"] += 1
continue
titles = gold_titles(c)
if not all(t in idx for t in titles):
dropped["gold_page_not_in_hotpotqa_train_contexts"] += 1
continue
if any(s < 0 or s >= len(idx.sentences(t, c["hpqa_id"])[0]) for t, s in c["supporting_facts"]):
dropped["supporting_sentence_id_out_of_range"] += 1
continue
if any(not paragraph_text(idx.sentences(t, c["hpqa_id"])[0]) for t in titles):
dropped["empty_gold_paragraph"] += 1
continue
if excluded is not None and excluded(c["claim"]):
dropped["claim_matches_eval_exclusion_hash"] += 1
continue
ok.append(c)
# identical claim text: conflicting labels -> drop all copies; duplicates -> keep the first (by line)
by_text: dict[str, list[dict]] = collections.defaultdict(list)
for c in ok:
by_text[normalise_text(c["claim"])].append(c)
out = []
for k in sorted(by_text, key=lambda k: by_text[k][0]["line"]):
grp = by_text[k]
if len({c["label"] for c in grp}) > 1:
dropped["same_claim_conflicting_labels"] += len(grp)
continue
dropped["duplicate_claim"] += len(grp) - 1
out.append(grp[0])
if not dropped["duplicate_claim"]:
del dropped["duplicate_claim"]
return out
def natural_prior(claims: list[dict]) -> dict[tuple[int, str], float]:
cnt = collections.Counter((c["num_hops"], c["label"]) for c in claims if c["label"] in LABELS)
tot = sum(cnt.values())
return {k: v / tot for k, v in sorted(cnt.items())}
def select(cands: list[dict], prior: dict[tuple[int, str], float], target: int,
dropped: collections.Counter) -> list[dict]:
"""≤MAX_PER_HPQA per hpqa_id (hash order), then largest-remainder allocation over (hops, label) strata."""
per_hp = collections.Counter()
pool = []
for c in sorted(cands, key=lambda c: (_h("pick", c["uid"]), c["uid"])):
if per_hp[c["hpqa_id"]] >= MAX_PER_HPQA:
continue
per_hp[c["hpqa_id"]] += 1
pool.append(c)
strata: dict[tuple, list[dict]] = collections.defaultdict(list)
for c in pool:
strata[(c["num_hops"], c["label"])].append(c)
quota = {k: target * p for k, p in prior.items()}
alloc = {k: int(q) for k, q in quota.items()}
for k in sorted(quota, key=lambda k: (-(quota[k] - alloc[k]), k))[: target - sum(alloc.values())]:
alloc[k] += 1
out, short = [], collections.Counter()
for k in sorted(alloc):
got = strata.get(k, [])[: alloc[k]]
if len(got) < alloc[k]:
short[k[1]] += alloc[k] - len(got)
dropped[f"info:stratum_short:{k[0]}hop/{k[1]}"] += alloc[k] - len(got)
out += got
# a short stratum is refilled from the other hop counts of the SAME label (label prior kept), round-robin
for label in sorted(short):
rest = {k: strata.get(k, [])[alloc[k]:] for k in sorted(alloc) if k[1] == label}
need = short[label]
while need and any(rest.values()):
for k in sorted(rest):
if need and rest[k]:
out.append(rest[k].pop(0))
need -= 1
if need:
dropped[f"info:label_short:{label}"] += need
return out
def clusters(sel: list[dict]) -> dict[str, str]:
"""uid -> cluster id; rows sharing an hpqa_id or a gold page are joined."""
parent: dict[str, str] = {}
def find(x):
parent.setdefault(x, x)
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(a, b):
ra, rb = find(a), find(b)
if ra != rb:
parent[max(ra, rb)] = min(ra, rb)
for c in sel:
node = "hp:" + c["hpqa_id"]
find(node)
for t in gold_titles(c):
union(node, "page:" + t)
roots = {c["uid"]: find("hp:" + c["hpqa_id"]) for c in sel}
return {u: "hc_" + hashlib.sha256(r.encode()).hexdigest()[:12] for u, r in roots.items()}
def assign_splits(sel: list[dict], cl: dict[str, str]) -> dict[str, str]:
size = collections.Counter(cl[c["uid"]] for c in sel)
want = round(DEV_FRACTION * len(sel))
dev, n = set(), 0
for cid in sorted(size, key=lambda k: (_h("dev", k), k)):
if n >= want:
break
if size[cid] > DEV_MAX_CLUSTER_ROWS:
continue
dev.add(cid)
n += size[cid]
return {c["uid"]: ("dev" if cl[c["uid"]] in dev else "train") for c in sel}
# ---------------------------------------------------------------------------------------------------------------
# Rendering
# ---------------------------------------------------------------------------------------------------------------
def build_state(c: dict, idx: ParagraphIndex, rng: random.Random, banned: set[str]) -> tuple[list[dict], dict]:
golds = gold_titles(c)
n_d = rng.choice(DISTRACTOR_CHOICES)
own = [t for t in idx.own_context_titles(c["hpqa_id"]) if t not in golds and t not in banned]
co = [t for t in idx.cocontext_titles(golds) if t not in golds and t not in banned and t not in own]
rng.shuffle(own)
rng.shuffle(co)
distract, src = [], collections.Counter()
for pool, tag in ((own, "own_context"), (co, "gold_page_cocontext")):
for t in pool:
if len(distract) >= n_d:
break
if paragraph_text(idx.sentences(t)[0]):
distract.append(t)
src[tag] += 1
items = [(t, True) for t in golds] + [(t, False) for t in distract]
rng.shuffle(items)
passages, hp_rows, gold_docs = [], {}, []
for i, (t, is_gold) in enumerate(items):
sents, row = idx.sentences(t, c["hpqa_id"] if is_gold else None)
doc = f"D{i + 1}"
passages.append({"doc": doc, "page": t, "body": paragraph_text(sents)})
hp_rows[t] = row
if is_gold:
gold_docs.append(doc)
info = {"gold_docs": gold_docs, "distractor_source": dict(src), "hotpot_rows": hp_rows,
"n_distractors": len(distract), "short_of_distractors": n_d - len(distract)}
return passages, info
def render(c: dict, split: str, cluster: str, idx: ParagraphIndex, banned: set[str]) -> dict:
rng = _rng("row", c["uid"])
passages, info = build_state(c, idx, rng, banned)
in_state = rng.random() < CLAIM_IN_STATE_SHARE
claim_slot = rng.choice(CLAIM_REF) if in_state else rng.choice(CLAIM_INLINE).format(c=c["claim"])
state = {"claim_under_review": c["claim"], "evidence_pool": passages} if in_state else {"evidence_pool": passages}
gold = LABELS[c["label"]]
if rng.random() < NOUL_SHARE:
ins = rng.choice(NOUL_INS).format(claim=claim_slot)
question = {"t": "noul", "ins": ins, "crit": None}
valid = ["true" if gold == "supported" else "false"]
opt_meta = None
else:
ins = rng.choice(CHOICE_INS).format(claim=claim_slot)
pos, neg = rng.choice(OPTION_PAIRS)
opts = [pos, neg]
rng.shuffle(opts)
question = {"t": "choice", "ins": ins, "crit": {k: d for k, d in opts}}
valid = [pos[0] if gold == "supported" else neg[0]]
opt_meta = {"supported_key": pos[0], "not_supported_key": neg[0],
"gold_position": [k for k, _ in opts].index(valid[0])}
prov = {"dataset": GH_REPO, "revision": GH_COMMIT, "file": TRAIN_FILE, "line": c["line"], "uid": c["uid"],
"hpqa_id": c["hpqa_id"], "hover_label": c["label"], "num_hops": c["num_hops"],
"supporting_facts": [[t, s] for t, s in c["supporting_facts"]],
"paragraphs": {"dataset": HP_REPO, "revision": HP_REVISION,
"rows": {t: [idx.row_by_idx[r].get("file"), idx.row_by_idx[r].get("file_row", r)]
for t, r in info["hotpot_rows"].items()}}}
meta = {"task": "hover_claim_verification", "gold_class": gold, "num_hops": c["num_hops"],
"claim_placement": "state" if in_state else "question", "n_passages": len(passages),
"gold_docs": info["gold_docs"], "n_distractors": info["n_distractors"],
"distractor_source": info["distractor_source"],
"passage_sha256": [content_hash(p["body"]) for p in passages],
"claim_sha256": content_hash(c["claim"]), "hpqa_id": c["hpqa_id"], "hover_uid": c["uid"],
"split_cluster": cluster, "dev_pool": "DIS" if split == "dev" else None, "translate_zh": False,
"source_split": "train", "options": opt_meta}
rec = make_record(id=f"v4A_{NAME}/{split}/{c['uid']}", group_id=f"hover_hpqa:{c['hpqa_id']}", split=split,
source=GH_REPO, category=CATEGORY, lang="en", license=LICENSE, state=state,
question=question, valid=valid, provenance=prov, meta=meta)
return rowspec.enrich(rec, data_class="A", component=COMPONENT, family=FAMILY, label_method="source_label",
teacher=[], generator={"name": BUILDER_VERSION, "version": "1", "seed": SEED},
twin_id=None, di=[DI_BENCHMARK_ID_EXPECTED], jevbench=None, overlap="in_domain_train")
def build(claims: list[dict], hotpot_rows: list[dict], *, target: int = TARGET_ROWS,
excluded: Callable[[str], bool] | None = None,
state_tokens: Callable[[dict], int] | None = None) -> dict:
dropped: collections.Counter = collections.Counter()
idx = ParagraphIndex(hotpot_rows)
prior = natural_prior(claims)
cands = filter_candidates(claims, idx, dropped, excluded)
sel = select(cands, prior, target, dropped)
cl = clusters(sel)
sp = assign_splits(sel, cl)
out = {"train": [], "dev": []}
# train distractors never use a page that is gold in dev; dev distractors never use any page shown in train
dev_gold = {t for c in sel if sp[c["uid"]] == "dev" for t in gold_titles(c)}
train_pages: set[str] = set()
for split in ("train", "dev"):
banned = train_pages if split == "dev" else dev_gold
for c in sorted((c for c in sel if sp[c["uid"]] == split), key=lambda c: c["line"]):
rec = render(c, split, cl[c["uid"]], idx, banned)
if state_tokens is not None and state_tokens(rec["state"]) > MAX_STATE_TOKENS:
dropped[f"{split}:state_over_{MAX_STATE_TOKENS}_tokens"] += 1
continue
errs = rowspec.validate_v4(rec)
if errs:
dropped[f"{split}:validate_v4_failed"] += 1
continue
if FORBIDDEN_RE.search(json.dumps([rec["state"], rec["question"]], ensure_ascii=False)):
dropped[f"{split}:forbidden_name_in_text"] += 1
continue
if split == "train":
train_pages |= {p["page"] for p in rec["state"]["evidence_pool"]}
out[split].append(rec)
# dev rows must not share a gold page or an hpqa id with train (asserted, never expected to fire)
tr_hp = {r["meta"]["hpqa_id"] for r in out["train"]}
tr_gold = {p["page"] for r in out["train"] for p in r["state"]["evidence_pool"]}
for r in out["dev"]:
gold_pages = {p["page"] for p in r["state"]["evidence_pool"] if p["doc"] in r["meta"]["gold_docs"]}
assert r["meta"]["hpqa_id"] not in tr_hp and not (gold_pages & tr_gold), "dev/train leak"
for s in out:
out[s].sort(key=lambda r: (_h("order", r["id"]), r["id"]))
return {**out, "dropped": dropped, "prior": prior, "n_candidates": len(cands), "n_selected": len(sel),
"conflicting_titles": idx.conflicting_titles}
# ---------------------------------------------------------------------------------------------------------------
# Exclusions, tokens, manifest
# ---------------------------------------------------------------------------------------------------------------
def load_exclusion_hashes() -> set[str]:
hashes: set[str] = set()
for path in sorted(EXCLUSIONS.glob("*.jsonl")):
with path.open() as f:
for line in f:
i = line.find('"hash": "')
if i >= 0:
hashes.add(line[i + 9:i + 73])
return hashes
def prompt_text(rec: dict) -> str:
q = rec["question"]
crit = "\n".join(f"{k}: {v}" for k, v in (q["crit"] or {}).items())
return f"{json.dumps(rec['state'], ensure_ascii=False)}\n{q['ins']}\n{crit}".rstrip()
def _stats(xs: list[int]) -> dict:
if not xs:
return {}
s = sorted(xs)
return {"n": len(s), "mean": round(statistics.fmean(s), 1), "p50": s[len(s) // 2],
"p95": s[min(len(s) - 1, int(0.95 * len(s)))], "max": s[-1], "total": sum(s)}
def token_stats(splits: dict[str, list[dict]], tok) -> dict:
out = {}
for split, recs in splits.items():
if not recs:
out[split] = {}
continue
st = [len(x) for x in tok([json.dumps(r["state"], ensure_ascii=False) for r in recs],
add_special_tokens=False)["input_ids"]]
pt = [len(x) for x in tok([prompt_text(r) for r in recs], add_special_tokens=False)["input_ids"]]
out[split] = {"state_tokens": _stats(st), "prompt_tokens": _stats(pt)}
return out
def summary(recs: list[dict]) -> dict:
c = collections.Counter
return {"rows": len(recs), "by_qtype": dict(sorted(c(r["question"]["t"] for r in recs).items())),
"by_lang": dict(c(r["lang"] for r in recs)),
"by_gold": dict(sorted(c(r["meta"]["gold_class"] for r in recs).items())),
"by_hops_gold": {f"{a}hop/{b}": n for (a, b), n in sorted(
c((r["meta"]["num_hops"], r["meta"]["gold_class"]) for r in recs).items())},
"by_claim_placement": dict(sorted(c(r["meta"]["claim_placement"] for r in recs).items())),
"n_passages": dict(sorted(c(r["meta"]["n_passages"] for r in recs).items())),
"state_empty": sum(1 for r in recs if r["meta"]["state_empty"]),
"groups": len({r["group_id"] for r in recs}),
"split_clusters": len({r["meta"]["split_cluster"] for r in recs})}
def write_jsonl(path: Path, recs: list[dict]) -> str:
rowspec.write_jsonl(path, recs)
return sha256_file(path)
def main(argv: list[str] | None = None) -> dict:
ap = argparse.ArgumentParser()
ap.add_argument("--no-token-check", action="store_true")
ap.add_argument("--no-exclusions", action="store_true")
ap.add_argument("--offline", action="store_true", help="skip the HF/GitHub licence API calls")
args = ap.parse_args(argv)
di_id = rowspec.di_ids()[DI_BENCHMARK_NAME]
if di_id != DI_BENCHMARK_ID_EXPECTED:
raise RuntimeError(f"DI id for HoVer changed: {di_id}")
lic_ev = None if args.offline else verify_license()
train_path = download_train()
claims = load_hover(train_path)
hp_paths = download_hotpot_shards()
hotpot = load_hotpot(hp_paths)
excluded = None
if not args.no_exclusions:
hashes = load_exclusion_hashes()
excluded = lambda text: content_hash(text) in hashes # noqa: E731
tok = state_tokens = None
if not args.no_token_check:
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained(str(TOKENIZER_DIR))
state_tokens = lambda st: len(tok(json.dumps(st, ensure_ascii=False), add_special_tokens=False)["input_ids"]) # noqa: E731
res = build(claims, hotpot, excluded=excluded, state_tokens=state_tokens)
shas = {s: write_jsonl(OUT_DIR / f"{s}.jsonl", res[s]) for s in ("train", "dev")}
prior = res["prior"]
sup = sum(v for (h, l), v in prior.items() if l == "SUPPORTED")
manifest = {
"builder": BUILDER_VERSION, "module": MODULE, "seed": SEED, "name": NAME, "family": FAMILY,
"component": COMPONENT, "data_class": "A", "label_method": "source_label",
"repo": GH_REPO, "revision": GH_COMMIT, "hf_repo": REPO, "hf_revision": HF_REVISION,
"license": LICENSE,
"license_evidence": lic_ev or {"note": "offline run: licence APIs not queried"},
"attribution": "HoVer (Jiang et al., Findings of EMNLP 2020), hover-nlp/hover, CC BY-SA 4.0; passages: "
"Wikipedia (2017 intro dump) via HotpotQA (Yang et al., EMNLP 2018), hotpotqa/hotpot_qa, "
"CC BY-SA 4.0. Rows are adaptations and are shared under CC BY-SA 4.0.",
"source_files": {
"hover_train": {"repo": GH_REPO, "commit": GH_COMMIT, "path": TRAIN_FILE, "url": TRAIN_URL,
"local": str(train_path.relative_to(ROOT)), "sha256": sha256_file(train_path),
"git_blob": TRAIN_GIT_BLOB, "bytes": train_path.stat().st_size, "rows": len(claims)},
**{f"hotpotqa_train_{tag}": {"repo": HP_REPO, "revision": HP_REVISION, "path": sh["file"],
"local": str(Path(hp_paths[tag]).relative_to(ROOT)), "sha256": sh["sha256"],
"bytes": Path(hp_paths[tag]).stat().st_size,
"rows": sum(1 for r in hotpot if r["file"] == sh["file"]),
"license": HP_LICENSE, "role": "paragraph text only"}
for tag, sh in HP_SHARDS.items()}},
"splits_used": {"train": "HoVer train (held-in clusters)",
"dev": "HoVer train (held-out clusters, ~7% of rows; meta.dev_pool=DIS)",
"paragraphs": "HotpotQA train distractor contexts (both train shards)"},
"forbidden_splits": {"hover-nlp/hover:dev (" + NEVER_READ[0] + ")": "never read, never downloaded "
"(the scored split)",
"hover-nlp/hover:test (" + NEVER_READ[1] + ")": "never read, never downloaded "
"(unlabeled)",
"hotpotqa/hotpot_qa:" + HP_NEVER_READ[0]: "never read"},
"class_A_benchmark": di_id, "class_A_benchmark_name": DI_BENCHMARK_NAME,
"label_prior": {"source": "natural distribution of the full HoVer train file (18,171 claims), "
"stratified by (num_hops, label)",
"supported": round(sup, 4), "not_supported": round(1 - sup, 4),
"by_hops_label": {f"{h}hop/{l}": round(v, 4) for (h, l), v in prior.items()}},
"selection": {"target_rows": TARGET_ROWS, "max_claims_per_hpqa_id": MAX_PER_HPQA,
"candidates_after_filters": res["n_candidates"], "selected": res["n_selected"],
"distractors_per_row": list(DISTRACTOR_CHOICES), "claim_in_state_share": CLAIM_IN_STATE_SHARE,
"noul_share": NOUL_SHARE, "dev_fraction": DEV_FRACTION,
"dev_max_cluster_rows": DEV_MAX_CLUSTER_ROWS,
"hotpot_titles_with_conflicting_versions": res["conflicting_titles"]},
"instruction_pools": {"noul": len(set(NOUL_INS)), "choice": len(set(CHOICE_INS)),
"option_pairs": len(OPTION_PAIRS)},
"outputs": {s: {"file": f"{s}.jsonl", "sha256": shas[s], **summary(res[s])} for s in ("train", "dev")},
"token_stats": ({"tokenizer": str(TOKENIZER_DIR.relative_to(ROOT)),
**token_stats({s: res[s] for s in ("train", "dev")}, tok)} if tok is not None else None),
"max_state_tokens": MAX_STATE_TOKENS,
"decontamination": {
"eval_exclusion_hashes": None if args.no_exclusions else "content_hash(claim) vs "
"data/master-v3/exclusions/*.jsonl",
"pending": "T11 DI gate G1-G3 + G5 (hpqa_id / hover uid, claim MinHash >= 0.3, paragraph hash vs DI "
"HoVer states) must run before any pool use; per-row keys in provenance.hpqa_id, "
"provenance.uid, meta.claim_sha256, meta.passage_sha256",
"dev_isolation": "union-find over hpqa_id + gold page; dev distractor pages never appear in train states"},
"teacher_jobs": [],
"translate_zh": "not applicable (retrieval component; zh quota applies to knowledge/language families)",
"drops": dict(sorted(res["dropped"].items())),
}
errs = rowspec.validate_manifest_v4(manifest, data_class="A")
if errs:
raise RuntimeError(f"manifest invalid: {errs}")
(OUT_DIR / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n")
return manifest
if __name__ == "__main__":
m = main()
print(json.dumps({k: m[k] for k in ("outputs", "token_stats", "drops", "label_prior")}, indent=2))
|