Giuliocc's picture
Publish source-aware model SDK, forty-deliverable evidence and annotated-review tooling
1f5647a verified
Raw History Blame Contribute Delete
5.38 kB
"""Strict reader for the independently frozen local BASIL restoration."""
import hashlib
import json
from pathlib import Path
import numpy as np
from inputs import SourceSentence, pack
ROOT = Path(__file__).resolve().parent
LABELS = ("lexical_bias", "informational_bias")
def fingerprint(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def write_json(path, value):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n")
def locked():
value = json.loads((ROOT / "DATA_LOCK.json").read_text())
if value["protocol_sha256"] != fingerprint(ROOT / "PROTOCOL.json"):
raise ValueError("The pre-fit protocol changed")
if value["source_manifest_sha256"] != fingerprint(value["source_manifest_path"]):
raise ValueError("The source split manifest changed")
return value
def rows(role):
record = locked()["files"][role]
if fingerprint(record["path"]) != record["sha256"]:
raise ValueError(f"Frozen {role} input bytes changed")
values = [json.loads(line) for line in Path(record["path"]).read_text().splitlines() if line]
if len(values) != record["rows"] or any(row["split"] != role for row in values):
raise ValueError("Frozen row counts or role labels changed")
if len({row["id"] for row in values}) != len(values):
raise ValueError("Source sentence identities collide")
if len({(row["article_id"], row["sentence_index"]) for row in values}) != len(values):
raise ValueError("Source article/order identities collide")
documents = {}
for row in values:
if any(row["labels"][label] not in (0, 1) for label in LABELS):
raise ValueError("Only actual source task binary labels are supported")
if hashlib.sha256(row["text"].encode()).hexdigest() != row["text_sha256"]:
raise ValueError("Original source target text changed")
document_path = (Path(record["path"]).parent / row["document_path"]).resolve()
if document_path not in documents:
documents[document_path] = json.loads(document_path.read_text())
document = documents[document_path]
text = document["text"]
if document["id"] != row["article_id"] or hashlib.sha256(text.encode()).hexdigest() != row["document_text_sha256"]:
raise ValueError("A source document identity or checksum does not match its sentence")
if text[row["start"]:row["end"]] != row["text"]:
raise ValueError("The exact target offset does not reproduce the original source")
before, after = row["context_before"], row["context_after"]
if before and text[row["context_before_start"]:row["context_before_start"] + len(before)] != before:
raise ValueError("The preceding context does not reproduce the original source")
if after and text[row["context_after_end"] - len(after):row["context_after_end"]] != after:
raise ValueError("The following context does not reproduce the original source")
if any(row["text"][span["start"]:span["end"]] != span["txt"] for span in row["upstream_spans"]):
raise ValueError("A human reference span does not reproduce the original target")
return values
def labels(values):
return np.array([[row["labels"][label] for label in LABELS] for row in values], dtype=np.int64)
def prepare(values, tokenizer, context):
articles = {}
for row in values:
articles.setdefault(row["article_id"], {})[row["sentence_index"]] = row
def sentence(row):
return SourceSentence(row["id"], row["text"], row["start"], row["end"],
paragraph_id=f"{row['article_id']}:{row['paragraph_index']}")
output = []
for row in values:
article = articles[row["article_id"]]
index = row["sentence_index"]
before = [sentence(article[i]) for i in range(max(0, index - 2), index) if i in article]
after = [sentence(article[i]) for i in range(index + 1, index + 3) if i in article]
output.append(pack(tokenizer, sentence(row), before, after, include_context=context))
return output
def lexical_inputs(packed, tokenizer):
return [tokenizer.decode(row["input_ids"], skip_special_tokens=True) if row["status"] == "ok" else "" for row in packed]
def input_coverage(packed):
eligible = [row for row in packed if row["status"] == "ok"]
targets = sum(row["target_tokens"] for row in packed)
available = sum(row["context_tokens_available"] for row in packed)
retained = sum(row["context_tokens_retained"] for row in packed)
return {"rows": len(packed), "eligible_rows": len(eligible), "unresolved_rows": len(packed) - len(eligible),
"eligible_fraction": len(eligible) / len(packed), "target_tokens": targets,
"target_tokens_retained": sum(row["target_tokens_retained"] for row in packed),
"context_tokens_available": available, "context_tokens_retained": retained,
"context_token_retention": retained / available if available else None,
"maximum_actual_tokens": max((row["actual_tokens"] for row in eligible), default=0),
"maximum_target_tokens": max(row["target_tokens"] for row in packed),
"missing_context_rows": sum(not row["context_available"] for row in eligible)}