Download expansion_v2/experiments/contextual-discourse/source/diagnostics.py from Giuliocc/doxa-methods: direct link, hf CLI and curl.
- Browser
- Download file 18.5 kB
-
https://huggingface.co/datasets/Giuliocc/doxa-methods/resolve/main/expansion_v2/experiments/contextual-discourse/source/diagnostics.py
- Command line
-
hf download hf://datasets/Giuliocc/doxa-methods/expansion_v2/experiments/contextual-discourse/source/diagnostics.py
-
curl -L -o diagnostics.py https://huggingface.co/datasets/Giuliocc/doxa-methods/resolve/main/expansion_v2/experiments/contextual-discourse/source/diagnostics.py
18.5 kB
| """After selection: source-span retention, attribution cohorts and noise. | |
| Reference-span interventions measure sensitivity to a declared edit. They | |
| are not a new human sufficiency annotation or a learned span explanation. | |
| """ | |
| from __future__ import annotations | |
| from collections import defaultdict | |
| import json | |
| from pathlib import Path | |
| import re | |
| import resource | |
| from shutil import copy2 | |
| import time | |
| import numpy as np | |
| from transformers import AutoTokenizer | |
| from contracts import sha256 | |
| from data import ROOT, fingerprint, locked, rows, labels, prepare, write_json, input_coverage | |
| from inputs import SourceSentence, document_inputs | |
| from metrics import TASKS, summarize, decide, calibrated | |
| from modeling import ContextEncoder, deterministic, native_logits | |
| LOCAL = ROOT / "local" | |
| def runtime_artifact(): | |
| selection = json.loads((LOCAL / "LOCKED_SELECTION.json").read_text()) | |
| selected = selection["export"]["selected"] | |
| if selected is None: | |
| return None | |
| folder = LOCAL / "runtime" | |
| (folder / "onnx").mkdir(parents=True, exist_ok=True) | |
| copy2(LOCAL / "export" / f"{selected['name']}.onnx", folder / "onnx/model_quantized.onnx") | |
| for path in (LOCAL / "selected-native").glob("*"): | |
| if path.name != "model.safetensors" and path.is_file(): | |
| copy2(path, folder / path.name) | |
| manifest = {"method": "doxa-contextual-discourse-v0.2.0", "model_id": "Giuliocc/doxa-contextual-discourse", | |
| "revision": "local-audit", "publication_status": "local_candidate_withheld", "maximum_tokens": 256, | |
| "applied_rubric": "BASIL-source-annotation-v1", "calibration": selection["calibration"], | |
| "files": {"tokenizer": {"path": "tokenizer.json", "sha256": fingerprint(folder / "tokenizer.json")}, | |
| "weights": {"path": "onnx/model_quantized.onnx", "sha256": fingerprint(folder / "onnx/model_quantized.onnx"), | |
| "bytes": (folder / "onnx/model_quantized.onnx").stat().st_size}}, | |
| "scope": "BASIL final human-source lexical/informational span-presence judgments in sampled English news, with real neighboring context; other genres, named prejudice rubrics and reporter endorsement are unsupported."} | |
| write_json(folder / "runtime_manifest.json", manifest) | |
| return folder | |
| def main(): | |
| deterministic() | |
| if not (LOCAL / "EVALUATION.json").exists(): | |
| raise RuntimeError("Diagnostics follow the locked held-out evaluation") | |
| selected = json.loads((LOCAL / "LOCKED_SELECTION.json").read_text()) | |
| test = rows("test") | |
| truth = labels(test) | |
| tokenizer = AutoTokenizer.from_pretrained(LOCAL / "selected-native", local_files_only=True) | |
| model = ContextEncoder.load(LOCAL / "selected-native") | |
| packed = prepare(test, tokenizer, True) | |
| saved_predictions = [json.loads(line) for line in (LOCAL / "test_predictions.jsonl").read_text().splitlines()] | |
| if [row["id"] for row in saved_predictions] != [row["id"] for row in test]: | |
| raise RuntimeError("Diagnostic source IDs differ from the locked test evaluation") | |
| probability = np.array([row["pipelines"][selected["selected_pipeline"]]["scores"] for row in saved_predictions]) | |
| prediction = np.array([row["pipelines"][selected["selected_pipeline"]]["labels"] for row in saved_predictions]) | |
| resolution = np.array([row["pipelines"][selected["selected_pipeline"]]["resolved"] for row in saved_predictions], dtype=bool) | |
| eligible = np.array([value["status"] == "ok" for value in packed]) | |
| report = {"selection_sha256": fingerprint(LOCAL / "LOCKED_SELECTION.json"), "training_or_selection_used_diagnostics": False, | |
| "source_label_scope": "Original source span presence only", "stance_model": "not_qualified", | |
| "input_coverage": input_coverage(packed), "cohorts": {}, "reference_span_retention": {}, "reference_span_interventions": {}} | |
| report["outlet_cohorts"] = {} | |
| for outlet in sorted({row["outlet"] for row in test}): | |
| mask = np.array([row["outlet"] == outlet for row in test]) & eligible | |
| report["outlet_cohorts"][outlet] = summarize(truth[mask], prediction[mask], probability[mask], resolution[mask]) | |
| report["outlet_cohort_interpretation"] = "Task errors within the source's three outlets; these are not new-outlet tests, political neutrality tests or publisher rankings." | |
| for i, task in enumerate(TASKS): | |
| bias = ("lex", "inf")[i] | |
| cohort = {} | |
| for quote in ("yes", "no"): | |
| mask = np.array([any(span["bias"] == bias and span["quote"] == quote for span in row["upstream_spans"]) for row in test]) & eligible | |
| kept = mask & resolution[:, i] | |
| cohort["has_upstream_quote_marked_bias_span" if quote == "yes" else "has_upstream_nonquote_marked_bias_span"] = {"rows": int(mask.sum()), "binary_positive_rate_before_abstention": float(prediction[mask, i].mean()) if mask.any() else None, | |
| "resolved_rows": int(kept.sum()), "resolved_positive_rate": float(prediction[kept, i].mean()) if kept.any() else None, | |
| "mean_model_score": float(probability[mask, i].mean()) if mask.any() else None, | |
| "annotation_origin": "upstream_human_final_source_attribute", "reporter_endorsement": "not_inferred"} | |
| report["cohorts"][task] = cohort | |
| report["cohorts"][task]["membership_note"] = "Source-span quote cohorts may overlap when a target has both quoted and unquoted annotations; they are not disjoint stance classes." | |
| spans = [(row, span, index) for index, row in enumerate(test) for span in row["upstream_spans"] if span["bias"] == bias] | |
| exact = sum(row["text"][span["start"]:span["end"]] == span["txt"] for row, span, index in spans) | |
| report["reference_span_retention"][task] = {"spans": len(spans), "exact_target_slices": exact, | |
| "spans_inside_eligible_complete_targets": int(sum(eligible[index] for row, span, index in spans)), | |
| "predicted_evidence_spans": False, "sufficiency_status": "Source location alone does not establish explanation or sufficiency."} | |
| case_indices = [index for index, row in enumerate(test) if eligible[index] and any(span["bias"] == bias for span in row["upstream_spans"])] | |
| keep_rows, remove_rows = [], [] | |
| for index in case_indices: | |
| row = test[index] | |
| ranges = sorted((span["start"], span["end"]) for span in row["upstream_spans"] if span["bias"] == bias) | |
| merged = [] | |
| for start, end in ranges: | |
| if merged and start <= merged[-1][1]: | |
| merged[-1][1] = max(merged[-1][1], end) | |
| else: | |
| merged.append([start, end]) | |
| kept = " ".join(row["text"][start:end] for start, end in merged) | |
| removed = list(row["text"]) | |
| for start, end in merged: | |
| removed[start:end] = [" "] * (end - start) | |
| keep_rows.append({**row, "text": kept}) | |
| remove_rows.append({**row, "text": "".join(removed)}) | |
| # Prepare against full source role so original neighbors are retained; | |
| # only the target sentence changes for this explicit intervention. | |
| def interventions(changes): | |
| values = [] | |
| # Original neighbors stay intact; evaluate only edited targets. | |
| for target in changes: | |
| # pack exact original neighbor source strings by source order. | |
| from inputs import pack | |
| article = {row["sentence_index"]: row for row in test if row["article_id"] == target["article_id"]} | |
| position = target["sentence_index"] | |
| before = [SourceSentence(article[j]["id"], article[j]["text"]) for j in range(max(0, position - 2), position) if j in article] | |
| after = [SourceSentence(article[j]["id"], article[j]["text"]) for j in range(position + 1, position + 3) if j in article] | |
| values.append(pack(tokenizer, SourceSentence(target["id"], target["text"]), before, after)) | |
| return values | |
| kept_packed, removed_packed = interventions(keep_rows), interventions(remove_rows) | |
| kept_logits, removed_logits = native_logits(model, kept_packed), native_logits(model, removed_packed) | |
| kept_probability = calibrated(kept_logits, selected["calibration"]) | |
| removed_probability = calibrated(removed_logits, selected["calibration"]) | |
| retained = np.array([index for index, value in enumerate(kept_packed) if value["status"] == "ok"], dtype=int) | |
| removed_valid = np.array([index for index, value in enumerate(removed_packed) if value["status"] == "ok"], dtype=int) | |
| original_probability = probability[case_indices, i] | |
| threshold = selected["calibration"][i]["threshold"] | |
| report["reference_span_interventions"][task] = {"reference_positive_targets": len(case_indices), | |
| "span_only_outside_complete_sentence_contract": True, | |
| "span_only_eligible": len(retained), "span_removed_eligible": len(removed_valid), | |
| "span_only_positive_rate": float((kept_probability[retained, i] >= threshold).mean()) if len(retained) else None, | |
| "mean_score_drop_after_span_removal": float((original_probability[removed_valid] - removed_probability[removed_valid, i]).mean()) if len(removed_valid) else None, | |
| "span_removal_positive_to_negative": int(((original_probability[removed_valid] >= threshold) & (removed_probability[removed_valid, i] < threshold)).sum()), | |
| "interpretation": "Sensitivity to reference-based edits under retained context; no new human sufficiency labels, causal explanation proof or learned span detector."} | |
| articles = defaultdict(list) | |
| for row in test: | |
| articles[row["article_id"]].append(row) | |
| load_started = time.perf_counter() | |
| document_coverage = [] | |
| frozen = Path(locked()["files"]["test"]["path"]).parent | |
| for article_id, values in articles.items(): | |
| document = json.loads((frozen / values[0]["document_path"]).resolve().read_text()) | |
| sentences = [SourceSentence(row["id"], row["text"], row["start"], row["end"], str(row["paragraph_index"])) for row in sorted(values, key=lambda row: row["sentence_index"])] | |
| _, coverage = document_inputs(tokenizer, article_id, document["text"], sentences) | |
| document_coverage.append(coverage) | |
| report["hierarchical_documents"] = {"documents": len(document_coverage), "source_targets": sum(row["sentences_attempted"] for row in document_coverage), | |
| "eligible_targets": sum(row["sentences_eligible"] for row in document_coverage), | |
| "paragraphs_with_eligible_targets": sum(row["paragraphs_with_eligible_targets"] for row in document_coverage), | |
| "document_characters": sum(row["document_characters"] for row in document_coverage), | |
| "eligible_target_characters": sum(row["eligible_target_characters"] for row in document_coverage), | |
| "document_character_coverage": sum(row["eligible_target_characters"] for row in document_coverage) / max(1, sum(row["document_characters"] for row in document_coverage)), | |
| "target_scope": "Eligible source body sentences; document titles and excluded empty targets remain outside this learned-task evaluation.", | |
| "packing_seconds": time.perf_counter() - load_started, "page_limit": None, | |
| "global_context_claim": False, "missing_source_sections": "The source has paragraph structure, not reviewed academic section labels."} | |
| original_indices = np.flatnonzero(eligible)[:128] | |
| noise = {} | |
| for name in ("linebreaks", "hyphenation"): | |
| changed = [dict(row) for row in test] | |
| for index in original_indices: | |
| text = test[index]["text"] | |
| if name == "linebreaks": | |
| text = "\n".join(text.split()) | |
| else: | |
| text = re.sub(r"\b[A-Za-z]{8,}\b", lambda match: match.group()[:len(match.group())//2] + "-\n" + match.group()[len(match.group())//2:], text, count=1) | |
| changed[index]["text"] = text | |
| values = prepare(changed, tokenizer, True) | |
| z = native_logits(model, [values[index] for index in original_indices]) | |
| p = calibrated(z, selected["calibration"]) | |
| decisions = decide(p, selected["calibration"]) | |
| noise[name] = {"cases": len(original_indices), "binary_label_agreement": float((prediction[original_indices] == decisions).mean()), | |
| "mean_absolute_score_change": float(np.abs(probability[original_indices] - p).mean()), | |
| "origin": "deterministic_source_perturbation", "human_OCR_gold_available": False, "used_for_selection": False} | |
| report["noise_diagnostics"] = noise | |
| folder = runtime_artifact() | |
| if folder: | |
| predictions = [json.loads(line) for line in (LOCAL / "test_predictions.jsonl").read_text().splitlines()] | |
| fixtures = [] | |
| for index in original_indices: | |
| row = test[index] | |
| article = {value["sentence_index"]: value for value in test if value["article_id"] == row["article_id"]} | |
| position = row["sentence_index"] | |
| before = [article[j]["text"] for j in range(max(0, position - 2), position) if j in article] | |
| after = [article[j]["text"] for j in range(position + 1, position + 3) if j in article] | |
| fixtures.append({"id": row["id"], "request": {"target": row["text"], "before": before, "after": after, | |
| "language": "en", "genre": "news", "applied_rubric": "BASIL-source-annotation-v1"}, | |
| "expected_labels": predictions[index]["pipelines"]["quantized"]["labels"], | |
| "expected_scores": predictions[index]["pipelines"]["quantized"]["scores"], | |
| "expected_inputs": {name: packed[index][name] for name in ("input_ids", "attention_mask", "token_type_ids", "target_mask", "context_mask")}}) | |
| fixtures.extend([ | |
| {"id": "authored_overlong_control", "request": {"target": "LOCAL-DISCOURSE-PRIVATE " + "context " * 400, "before": ["A source sentence precedes it."], "after": [], "language": "en", "genre": "news", "applied_rubric": "BASIL-source-annotation-v1"}, "expected_status": "abstained"}, | |
| {"id": "authored_unsupported_framework_control", "request": {"target": "I oppose the cabinet's policy and call for reversal.", "before": ["The speaker discussed a policy decision."], "after": [], "language": "en", "genre": "news", "applied_rubric": "IHRA", "tasks": ["antisemitism"]}, "expected_status": "unsupported_criterion"}, | |
| {"id": "authored_missing_context_control", "request": {"target": "The committee voted six to four.", "before": [], "after": [], "language": "en", "genre": "news", "applied_rubric": "BASIL-source-annotation-v1"}, "expected_status": "insufficient_context"}, | |
| {"id": "authored_unknown_target_control", "request": {"target": "😀😀😀", "before": ["A source sentence precedes it."], "after": [], "language": "en", "genre": "news", "applied_rubric": "BASIL-source-annotation-v1"}, "expected_status": "abstained"}, | |
| {"id": "authored_string_neighbors_control", "request": {"target": "A source sentence.", "before": "A string is not a neighbor array.", "after": [], "language": "en", "genre": "news", "applied_rubric": "BASIL-source-annotation-v1"}, "expected_status": "invalid_input", "expected_top_status": "invalid_input"}, | |
| {"id": "authored_null_neighbor_control", "request": {"target": "A source sentence.", "before": [None], "after": [], "language": "en", "genre": "news", "applied_rubric": "BASIL-source-annotation-v1"}, "expected_status": "invalid_input", "expected_top_status": "invalid_input"}, | |
| {"id": "authored_invalid_tasks_control", "request": {"target": "A source sentence.", "before": ["A preceding sentence."], "after": [], "tasks": "BASIL_lexical_bias", "language": "en", "genre": "news", "applied_rubric": "BASIL-source-annotation-v1"}, "expected_top_status": "invalid_input", "expected_result_count": 0}, | |
| {"id": "authored_boolean_anchor_control", "request": {"target": "A source sentence.", "before": ["A preceding sentence."], "after": [], "language": "en", "genre": "news", "applied_rubric": "BASIL-source-annotation-v1", "source_anchor": {"document_id": "authored-source", "start": False, "end": 18, "offset_unit": "unicode_codepoint", "sha256": "0" * 64}}, "expected_status": "invalid_input", "expected_top_status": "invalid_input"}, | |
| {"id": "authored_malformed_unicode_control", "request": {"target": "Will be replaced inside the browser with a lone surrogate.", "before": ["A preceding sentence."], "after": [], "language": "en", "genre": "news", "applied_rubric": "BASIL-source-annotation-v1"}, "inject_lone_surrogate": True, "expected_status": "invalid_input", "expected_top_status": "invalid_input"}, | |
| ]) | |
| from inference import DiscourseModel | |
| from inputs import pack | |
| runtime = DiscourseModel(folder, allow_local_candidate_audit=True) | |
| authored = "😀 The café and cafe\u0301 committee recorded the vote." | |
| before, after = ["The bulletin describes a committee meeting."], ["The clerk preserved the record."] | |
| anchor = {"document_id": "authored-unicode-source", "start": 9, "end": 9 + len(authored), "offset_unit": "unicode_codepoint", "sha256": sha256(authored)} | |
| output = runtime.check(authored, before, after, source_anchor=anchor) | |
| encoded = pack(tokenizer, SourceSentence("authored-unicode-source", authored), | |
| [SourceSentence("before", before[0])], [SourceSentence("after", after[0])]) | |
| fixtures.append({"id": "authored_unicode_source_control", "request": {"target": authored, "before": before, "after": after, | |
| "language": "en", "genre": "news", "applied_rubric": "BASIL-source-annotation-v1", "source_anchor": anchor}, | |
| "expected_labels": [int(row["model_score"] >= row["decision_threshold"]) for row in output["results"]], | |
| "expected_scores": [row["model_score"] for row in output["results"]], | |
| "expected_inputs": {name: encoded[name] for name in ("input_ids", "attention_mask", "token_type_ids", "target_mask", "context_mask")}}) | |
| write_json(LOCAL / "browser-fixtures.json", fixtures) | |
| report["process_peak_rss_kib"] = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss | |
| write_json(LOCAL / "DIAGNOSTICS.json", report) | |
| print(json.dumps({"documents": len(articles), "coverage": report["input_coverage"], "noise": noise, "runtime_built": folder is not None})) | |
| if __name__ == "__main__": | |
| main() | |