nur-dev's picture
Upload folder using huggingface_hub
de7d913 verified
Raw
History Blame Contribute Delete
11.4 kB
#!/usr/bin/env python3
"""Verify integrity and pre-specified classification rules for the public release."""
from __future__ import annotations
import csv
import hashlib
import json
import subprocess
import sys
from collections import Counter
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
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 check_manifest() -> int:
manifest = ROOT / "MANIFEST.sha256"
if not manifest.is_file():
raise AssertionError("MANIFEST.sha256 is missing")
count = 0
for line in manifest.read_text(encoding="utf-8").splitlines():
expected, relative = line.split(" ", 1)
path = ROOT / relative
if not path.is_file():
raise AssertionError(f"manifest file is missing: {relative}")
actual = sha256(path)
if actual != expected:
raise AssertionError(f"checksum mismatch for {relative}: {actual} != {expected}")
count += 1
return count
def check_groups() -> tuple[int, int, Counter[str]]:
with (ROOT / "data/group_classifications.csv").open(newline="", encoding="utf-8") as handle:
rows = list(csv.DictReader(handle))
if len(rows) != 384:
raise AssertionError("group classification must contain 384 rows")
identities = {(int(row["layer"]), int(row["kv_group"])) for row in rows}
if identities != {(layer, group) for layer in range(24) for group in range(16)}:
raise AssertionError("group identities are incomplete or duplicated")
candidates = []
selected = []
for row in rows:
expected_candidate = (
float(row["graph_substitutability"]) >= 0.95
and float(row["typed_advantage"]) >= 0.20
)
if (row["candidate_by_registered_rule"] == "true") != expected_candidate:
raise AssertionError(f"candidate rule mismatch at layer/group {row['layer']}/{row['kv_group']}")
if expected_candidate:
candidates.append(row)
if row["q25_selected"] == "true":
selected.append(row)
if not expected_candidate:
raise AssertionError("selected group is not a pre-specified candidate")
modes = Counter(row["q25_mode"] for row in rows)
if len(candidates) != 118 or len(selected) != 96:
raise AssertionError(f"candidate/selection count mismatch: {len(candidates)}/{len(selected)}")
if modes != Counter({"GLOBAL": 288, "LOCAL": 81, "LOCAL_GRAPH": 15}):
raise AssertionError(f"mode counts differ: {modes}")
by_layer = Counter(int(row["layer"]) for row in selected)
if len(by_layer) > 10 or min(by_layer.values()) < 2:
raise AssertionError(f"compact-layer constraints fail: {by_layer}")
graph_rows = [row for row in selected if row["q25_mode"] == "LOCAL_GRAPH"]
if sum(int(row["layer"]) == 23 for row in graph_rows) < 10:
raise AssertionError("layer-23 graph-group constraint fails")
coverage: Counter[str] = Counter()
for row in graph_rows:
coverage.update(set(row["q25_active_programs"].split(";")))
expected = json.loads((ROOT / "raw/frontier/q25.json").read_text(encoding="utf-8"))["physical_export"]["graph_program_coverage"]
if dict(coverage) != expected:
raise AssertionError(f"graph-program coverage mismatch: {dict(coverage)} != {expected}")
return len(candidates), len(selected), modes
def check_interactions() -> int:
nodes = json.loads((ROOT / "raw/interactions/nodes.json").read_text(encoding="utf-8"))["nodes"]
candidate_ids = {(int(row["layer"]), int(row["head"])) for row in nodes}
if len(candidate_ids) != 118:
raise AssertionError("interaction node set must contain 118 unique candidates")
with (ROOT / "raw/interactions/pairs.jsonl").open(encoding="utf-8") as handle:
raw_pairs = {row["key"]: row for row in (json.loads(line) for line in handle)}
pairs = set()
with (ROOT / "data/pair_interactions.csv").open(newline="", encoding="utf-8") as handle:
for row in csv.DictReader(handle):
members = tuple(sorted((
(int(row["group_a_layer"]), int(row["group_a_kv_group"])),
(int(row["group_b_layer"]), int(row["group_b_kv_group"])),
)))
if members[0] not in candidate_ids or members[1] not in candidate_ids:
raise AssertionError("pair contains a non-candidate group")
raw = raw_pairs.get(row["key"])
if raw is None:
raise AssertionError(f"flattened pair is absent from raw data: {row['key']}")
if float(row["semantic_interaction"]) != float(raw["semantic_interaction"]):
raise AssertionError(f"flattened interaction differs from raw data: {row['key']}")
pairs.add(members)
if len(raw_pairs) != 6903 or len(pairs) != 6903:
raise AssertionError(f"expected 6903 unique pairs, found {len(pairs)}")
return len(pairs)
def check_postreview() -> None:
payload = json.loads(
(ROOT / "raw/postreview/q25_confirmation.json").read_text(encoding="utf-8")
)
lm = payload["language_model"]
if lm["documents"] != 470 or lm["tokens"] != 3_850_240:
raise AssertionError("post-review LM support differs")
if lm["graph_state"] != "disabled/zero for both selection and evaluation":
raise AssertionError("post-review graph/PPL boundary differs")
if not lm["noninferiority_pass"]:
raise AssertionError("post-review PPL non-inferiority failed")
if lm["paired_document_bootstrap"]["ppl_ratio_upper"] >= 1.03:
raise AssertionError("post-review PPL interval exceeds the margin")
semantic = payload["semantic_confirmation"]
if not semantic["untouched_by_training_selection_or_thresholding"]:
raise AssertionError("semantic confirmation is not untouched")
metrics = semantic["metrics"]
expected = {
"correct": 0.999,
"untyped": 0.187,
"wrong_role": 0.0,
"wrong_event": 0.1335,
"random": 0.1335,
"zero": 0.1335,
}
for name, value in expected.items():
if float(metrics[name]["accuracy"]) != value:
raise AssertionError(f"semantic confirmation differs for {name}")
state = payload["persistent_state"]
if state["token_kv_reduction"] != 0.21875:
raise AssertionError("token-KV accounting differs")
architecture = payload["architecture"]
if architecture["query_heads_per_kv_head"] != 1:
raise AssertionError("the released backbone is not the verified 1:1 MHA geometry")
cached = json.loads(
(ROOT / "raw/reproducibility/q25_cached_decode_profile.json").read_text(
encoding="utf-8"
)
)
if not all(
row["numerically_equivalent"]
for row in cached["verification"].values()
):
raise AssertionError("cached decode did not match the full-sequence path")
prefix_8k = {
int(row["batch_size"]): row
for row in cached["rows"]
if int(row["prefix_length"]) == 8160
}
if set(prefix_8k) != {1, 4, 8, 16}:
raise AssertionError("cached 8k batch matrix is incomplete")
if any(row["ratios"]["persistent_kv"] != 0.78125 for row in prefix_8k.values()):
raise AssertionError("cached persistent-KV ratio differs")
def check_replications() -> None:
payload = json.loads(
(ROOT / "raw/replication/q25_replications.json").read_text(encoding="utf-8")
)
if payload["fresh_replications"] != 2:
raise AssertionError("expected two fresh Q25 campaigns")
if not payload["all_localization_and_typed_path_passed"]:
raise AssertionError("localization/typed-path replication failed")
if payload["all_corrected_matched_h0_passed"]:
raise AssertionError("corrected matched-capacity attribution must remain failed")
if len(payload["runs"]) != 3:
raise AssertionError("replication summary must contain three campaigns")
for run in payload["runs"]:
if run["selected_groups"] != 96:
raise AssertionError("a replication did not select 96 heads")
if run["interaction_pairs"] != 6903 or run["interaction_triples"] != 128:
raise AssertionError("a fresh interaction audit is incomplete")
if run["expanded_ppl_ratio_upper"] >= 1.03 or run["expanded_typed"] < 0.95:
raise AssertionError("a localization/typed-path replication metric failed")
interval = run["corrected_marginal_correct"]
if not interval["lower"] <= 0 <= interval["upper"]:
raise AssertionError("corrected matched-capacity interval unexpectedly excludes zero")
def check_public_paths() -> None:
offenders = []
for path in ROOT.rglob("*"):
if not path.is_file() or path.name == "MANIFEST.sha256":
continue
if path.suffix.lower() not in {".md", ".json", ".jsonl", ".csv", ".py", ".cff", ""}:
continue
text = path.read_text(encoding="utf-8", errors="replace")
banned = ("/home/" + "llmuser1/", "/mnt/" + "storage/")
if any(prefix in text for prefix in banned):
offenders.append(str(path.relative_to(ROOT)))
if offenders:
raise AssertionError("internal absolute paths remain in: " + ", ".join(offenders))
def check_metadata() -> None:
readme = (ROOT / "README.md").read_text(encoding="utf-8")
if not readme.startswith("---\n") or "license: cc-by-4.0" not in readme:
raise AssertionError("README lacks Hugging Face YAML metadata")
for config in (
"group-classifications",
"pair-interactions",
"computational-taxonomy",
"use-case-classifications",
"reported-metrics",
):
if f"config_name: {config}" not in readme:
raise AssertionError(f"README lacks dataset configuration {config}")
citation = (ROOT / "CITATION.cff").read_text(encoding="utf-8")
for required in (
"cff-version: 1.2.0",
"Kadyrbek",
"Mansurova",
"0000-0002-5461-8899",
"0000-0002-9680-2758",
):
if required not in citation:
raise AssertionError(f"citation metadata lacks {required}")
model = json.loads(
(ROOT / "raw/reproducibility/model_release.json").read_text(encoding="utf-8")
)
if model["hub_commit"] != "60b2ea8dc02c1b847faf3770105fecb2e9a74d7d":
raise AssertionError("linked model release commit differs")
if model["physical_modes"] != {"GLOBAL": 288, "LOCAL": 81, "LOCAL_GRAPH": 15}:
raise AssertionError("linked model release mode counts differ")
def main() -> None:
subprocess.run([sys.executable, str(ROOT / "scripts/reproduce.py"), "--check"], check=True)
candidates, selected, modes = check_groups()
pairs = check_interactions()
check_postreview()
check_replications()
check_public_paths()
check_metadata()
files = check_manifest()
print(
f"verified {files} files; 384 groups, {candidates} candidates, "
f"{selected} Q25 selections ({modes['LOCAL']} LOCAL, "
f"{modes['LOCAL_GRAPH']} LOCAL_GRAPH), {pairs} interactions, post-review confirmation, "
"and two fresh Q25 campaigns"
)
if __name__ == "__main__":
main()