doxa-wording-encoder / inference.py
Giuliocc's picture
Release CPU-trained contextual wording encoder with heldout and runtime audits
b6e07f2 verified
Raw History Blame Contribute Delete
2.88 kB
"""Run the checked wording model locally with ONNX Runtime."""
import hashlib
import json
from pathlib import Path
import numpy as np
import onnxruntime as ort
from tokenizers import Tokenizer
class WordingModel:
def __init__(self, folder, threads=1):
folder = Path(folder)
self.manifest = json.loads((folder / "runtime_manifest.json").read_text())
for asset in self.manifest["files"].values():
if hashlib.sha256((folder / asset["path"]).read_bytes()).hexdigest() != asset["sha256"]:
raise ValueError("A model asset does not match the published manifest")
self.tokenizer = Tokenizer.from_file(str(folder / "tokenizer.json"))
if json.loads((folder / "tokenizer.json").read_text()).get("truncation"):
raise ValueError("The tokenizer must preserve full input length")
options = ort.SessionOptions()
options.intra_op_num_threads = threads
options.inter_op_num_threads = 1
self.session = ort.InferenceSession(str(folder / "onnx/model_quantized.onnx"),
sess_options=options, providers=["CPUExecutionProvider"])
def check(self, text):
if not isinstance(text, str) or not text.strip():
raise ValueError("Choose a non-empty passage")
manifest = self.manifest
encoded = self.tokenizer.encode(text)
length = len(encoded.ids)
result = {
"method": manifest["method"], "task": manifest["task"], "decision": "unresolved",
"model_score": None, "class_scores": None, "score_calibration": manifest["score_calibration"],
"decision_threshold": manifest["threshold"], "token_count": length,
"maximum_tokens": manifest["maximum_tokens"], "model_id": manifest["model_id"],
"model_revision": manifest["revision"], "context_used": False, "reason": None,
"scope": manifest["scope"],
}
if length > manifest["maximum_tokens"]:
return result | {"reason": "input_too_long"}
values = {"input_ids": encoded.ids, "attention_mask": encoded.attention_mask, "token_type_ids": encoded.type_ids}
inputs = {item.name: np.array([values[item.name]], dtype=np.int64) for item in self.session.get_inputs()}
logits = self.session.run(None, inputs)[0][0] / manifest["temperature"]
probabilities = np.exp(logits - logits.max())
probabilities /= probabilities.sum()
positive = float(probabilities[1])
result["model_score"] = positive
result["class_scores"] = {"no_biased_wording": 1 - positive, "biased_wording": positive}
if max(positive, 1 - positive) < manifest["threshold"]:
result["reason"] = "below_resolution_threshold"
else:
result["decision"] = "wording_flag" if positive >= .5 else "no_wording_flag"
return result