Download expansion_v2/experiments/contextual-discourse/source/inference.py from Giuliocc/doxa-methods: direct link, hf CLI and curl.
- Browser
- Download file 9.5 kB
-
https://huggingface.co/datasets/Giuliocc/doxa-methods/resolve/main/expansion_v2/experiments/contextual-discourse/source/inference.py
- Command line
-
hf download hf://datasets/Giuliocc/doxa-methods/expansion_v2/experiments/contextual-discourse/source/inference.py
-
curl -L -o inference.py https://huggingface.co/datasets/Giuliocc/doxa-methods/resolve/main/expansion_v2/experiments/contextual-discourse/source/inference.py
9.5 kB
| """Local, source-anchored inference for a qualified discourse artifact. | |
| No network requests are made. Set allow_local_candidate_audit only in an | |
| explicit research audit; an unqualified candidate is not a production model. | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import re | |
| import time | |
| import numpy as np | |
| import onnxruntime as ort | |
| from tokenizers import Tokenizer | |
| from contracts import eligibility, sha256 | |
| from inputs import SourceSentence, pack | |
| TASKS = ("BASIL_lexical_bias", "BASIL_informational_bias") | |
| class RuntimeTokenizer: | |
| def __init__(self, path): | |
| self.tokenizer = Tokenizer.from_file(str(path)) | |
| self.cls_token_id = self.tokenizer.token_to_id("[CLS]") | |
| self.sep_token_id = self.tokenizer.token_to_id("[SEP]") | |
| self.unk_token_id = self.tokenizer.token_to_id("[UNK]") | |
| def __call__(self, text, **kwargs): | |
| value = self.tokenizer.encode(text, add_special_tokens=False) | |
| return {"input_ids": value.ids, "offset_mapping": value.offsets} | |
| def calibrated(logits, calibration): | |
| return np.column_stack([1 / (1 + np.exp(-np.clip(logits[:, i] * row["scale"] + row["intercept"], -60, 60))) | |
| for i, row in enumerate(calibration)]) | |
| class DiscourseModel: | |
| def __init__(self, folder, *, allow_local_candidate_audit=False): | |
| self.folder = Path(folder) | |
| self.manifest = json.loads((self.folder / "runtime_manifest.json").read_text()) | |
| self.audit = bool(allow_local_candidate_audit) | |
| for asset in self.manifest["files"].values(): | |
| if hashlib.sha256((self.folder / asset["path"]).read_bytes()).hexdigest() != asset["sha256"]: | |
| raise ValueError("The discourse asset does not match its pinned checksum") | |
| if self.manifest["publication_status"] != "qualified_release" and not self.audit: | |
| raise ValueError("This local candidate has no qualified release") | |
| self.tokenizer = RuntimeTokenizer(self.folder / "tokenizer.json") | |
| if json.loads((self.folder / "tokenizer.json").read_text()).get("truncation"): | |
| raise ValueError("The discourse tokenizer must retain complete target length") | |
| options = ort.SessionOptions() | |
| options.intra_op_num_threads = 1 | |
| options.inter_op_num_threads = 1 | |
| self.session = ort.InferenceSession(str(self.folder / self.manifest["files"]["weights"]["path"]), | |
| sess_options=options, providers=["CPUExecutionProvider"]) | |
| def check(self, target, before, after, *, applied_rubric="BASIL-source-annotation-v1", language="en", genre="news", | |
| tasks=TASKS, source_anchor=None): | |
| started = time.perf_counter() | |
| valid_tasks = isinstance(tasks, (list, tuple)) and bool(tasks) and all(isinstance(task, str) and task.strip() for task in tasks) | |
| valid_tasks = valid_tasks and len(set(tasks)) == len(tasks) | |
| output_tasks = list(tasks) if valid_tasks else [] | |
| rubric = applied_rubric if isinstance(applied_rubric, str) else None | |
| common = {"method": self.manifest["method"], "model_id": self.manifest["model_id"], | |
| "model_revision": self.manifest["revision"], "applied_rubric": rubric, | |
| "scope": self.manifest["scope"], "publication_status": self.manifest["publication_status"], | |
| "source_anchor": None, "evidence_role": "exact_target_location_not_a_model_rationale", | |
| "reporter_endorsement": "unresolved", "speaker_stance_model": "not_qualified", | |
| "reference_span_prediction": "not_supported", "source_payloads_sent": False, | |
| "results": []} | |
| def invalid(reason): | |
| result = [{"task": task, "applied_rubric": rubric, "prediction_status": "invalid_input", "model_score": None, | |
| "suggested_decision": None, "review_priority": "unassigned", "reason": reason} for task in output_tasks] | |
| return common | {"prediction_status": "invalid_input", "reason": reason, "results": result, | |
| "elapsed_ms": (time.perf_counter() - started) * 1000} | |
| if not valid_tasks: | |
| return invalid("tasks must be a non-empty list or tuple of unique, non-empty task strings") | |
| if not isinstance(target, str) or not target.strip(): | |
| return invalid("target must be a non-empty source string") | |
| if not all(isinstance(side, (list, tuple)) and all(isinstance(text, str) for text in side) for side in (before, after)): | |
| return invalid("before and after must be lists or tuples of source strings; a string is not a neighbor array") | |
| if applied_rubric is not None and not isinstance(applied_rubric, str): | |
| return invalid("applied_rubric must be a string or null") | |
| if not isinstance(language, str) or not language.strip() or not isinstance(genre, str) or not genre.strip(): | |
| return invalid("language and genre must be non-empty declared strings") | |
| try: | |
| for text in (target, *before, *after): | |
| text.encode("utf-8", errors="strict") | |
| except UnicodeEncodeError: | |
| return invalid("source strings must contain well-formed Unicode") | |
| if source_anchor is not None: | |
| if not isinstance(source_anchor, dict): | |
| return invalid("source_anchor must be an object or null") | |
| valid_anchor = (isinstance(source_anchor.get("document_id"), str) and bool(source_anchor["document_id"].strip()) | |
| and type(source_anchor.get("start")) is int and type(source_anchor.get("end")) is int | |
| and source_anchor["start"] >= 0 and source_anchor["end"] > source_anchor["start"] | |
| and source_anchor.get("offset_unit") == "unicode_codepoint" | |
| and isinstance(source_anchor.get("sha256"), str) and re.fullmatch(r"[a-f0-9]{64}", source_anchor["sha256"])) | |
| if not valid_anchor: | |
| return invalid("source_anchor needs a document ID, integer codepoint bounds, unicode_codepoint offset unit and SHA256") | |
| if source_anchor["end"] - source_anchor["start"] != len(target) or source_anchor["sha256"] != sha256(target): | |
| return invalid("target does not match the declared exact source anchor") | |
| common["source_anchor"] = {name: source_anchor[name] for name in ("document_id", "start", "end", "offset_unit", "sha256")} | |
| qualified = self.manifest["publication_status"] == "qualified_release" or self.audit | |
| results = [eligibility(task, applied_rubric=applied_rubric, language=language, genre=genre, | |
| model_qualified=qualified, context_available=any(text.strip() for text in (*before, *after))) for task in output_tasks] | |
| common["results"] = results | |
| eligible = [row for row in results if row["prediction_status"] == "eligible"] | |
| if not eligible: | |
| return common | {"elapsed_ms": (time.perf_counter() - started) * 1000} | |
| packed = pack(self.tokenizer, SourceSentence("input-target", target), | |
| [SourceSentence(f"before-{i}", text) for i, text in enumerate(before[-2:])], | |
| [SourceSentence(f"after-{i}", text) for i, text in enumerate(after[:2])]) | |
| if packed["status"] != "ok": | |
| for row in eligible: | |
| row.update(prediction_status="abstained", reason=packed["reason"]) | |
| return common | {"elapsed_ms": (time.perf_counter() - started) * 1000} | |
| if not packed["context_available"] or packed["context_tokens_retained"] == 0: | |
| for row in eligible: | |
| row.update(prediction_status="insufficient_context" if not packed["context_available"] else "abstained", | |
| reason="No evaluated source context tokens fit the input budget.") | |
| return common | {"elapsed_ms": (time.perf_counter() - started) * 1000} | |
| target_ids = [value for value, mask in zip(packed["input_ids"], packed["target_mask"]) if mask] | |
| if all(value == self.tokenizer.unk_token_id for value in target_ids): | |
| for row in eligible: | |
| row.update(prediction_status="abstained", reason="no_known_target_tokens") | |
| return common | {"elapsed_ms": (time.perf_counter() - started) * 1000} | |
| values = {item.name: np.array([packed[item.name]], dtype=np.int64) for item in self.session.get_inputs()} | |
| logits = self.session.run(None, values)[0] | |
| probability = calibrated(logits, self.manifest["calibration"])[0] | |
| for row in eligible: | |
| index = TASKS.index(row["task"]) | |
| calibration = self.manifest["calibration"][index] | |
| score = float(probability[index]) | |
| row.update(model_score=score, decision_threshold=calibration["threshold"], | |
| abstention_margin=calibration["margin"], calibration=calibration["method"]) | |
| if abs(score - calibration["threshold"]) < calibration["margin"]: | |
| row.update(prediction_status="abstained", reason="Inside the validation-selected unresolved margin.") | |
| else: | |
| row.update(prediction_status="ok", suggested_decision="present" if score >= calibration["threshold"] else "absent", reason=None) | |
| return common | {"token_coverage": {key: packed[key] for key in ("maximum_tokens", "target_tokens", "target_tokens_retained", | |
| "context_tokens_available", "context_tokens_retained", "actual_tokens")}, | |
| "elapsed_ms": (time.perf_counter() - started) * 1000} | |