"""Prepare model documentation and an explicit public file manifest.""" import hashlib import json from pathlib import Path from shutil import copy2 from inference import WordingModel ROOT = Path(__file__).resolve().parent STAGE = ROOT / "stage" PROJECT = ROOT.parents[1] def write_json(path, value): path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n") def main(): evaluation = json.loads((STAGE / "EVALUATION.json").read_text()) manifest = json.loads((STAGE / "runtime_manifest.json").read_text()) gate = evaluation["release_gate"] if not gate["passed"]: raise RuntimeError("The candidate failed the registered promotion gate") if not (STAGE / "BROWSER_PARITY.json").exists(): raise RuntimeError("Browser parity is pending") parity = json.loads((STAGE / "BROWSER_PARITY.json").read_text()) if parity["agreement"] < .98: raise RuntimeError("Browser parity failed") for name in ("EVALUATION_REGISTRATION.md", "EVALUATION_AMENDMENT_1.md", "EXPORT_PLAN.md", "EXPORT_REPAIR.md", "REPRODUCE.md", "requirements.txt", "NOTICE", "inference.py"): copy2(ROOT / name, STAGE / name) copy2(PROJECT / "LICENSE", STAGE / "LICENSE") (STAGE / "training").mkdir(exist_ok=True) for name in ("train.py", "repair_export.py", "finalize_export.py", "browser_parity.mjs", "package_model.py"): copy2(ROOT / name, STAGE / "training" / name) copy2(ROOT / "work/training_history.json", STAGE / "training_history.json") copy2(ROOT / "work/validation_controls.json", STAGE / "validation_controls.json") model = WordingModel(STAGE) examples = [ ("factual_statement", "The committee voted six to four to approve the policy."), ("evaluative_wording", "The committee's reckless and disgraceful policy betrayed every resident."), ("attributed_judgment", "The minister called the policy reckless; the report attributed that judgment to her."), ] illustration = [{"id": key, "origin": "original_fictional_illustration", "text": text, "result": model.check(text)} for key, text in examples] write_json(STAGE / "illustrations.json", illustration) predictions = [json.loads(line) for line in (STAGE / "test_predictions.jsonl").read_text().splitlines()] errors = sorted((row for row in predictions if row["candidate_label"] != row["reference_label"]), key=lambda row: max(row["model_score"], 1 - row["model_score"]), reverse=True) write_json(STAGE / "errors.json", {"errors": len(errors), "most_confident_errors": errors[:20], "text_policy": "Review source IDs through the linked benchmark; article text is excluded from this package."}) candidate = evaluation["candidate"] quantized = evaluation["quantized"] interval = evaluation["bootstrap"]["gain_interval_95"] selected = evaluation["selected_pipeline"] role = "full encoder and classification head fine-tuning" if selected == "fine_tuned_encoder" else "a trained logistic head over a frozen mean-pooled MiniLM encoder" table = "\n".join(f"| {name} | {row['macro_f1']:.3f} | {row['accuracy']:.3f} |" for name, row in evaluation["controls"].items()) table += f"\n| Selected contextual pipeline | {candidate['macro_f1']:.3f} | {candidate['accuracy']:.3f} |" table += f"\n| Quantized browser model | {quantized['macro_f1']:.3f} | {quantized['accuracy']:.3f} |" report = f"""# Contextual wording evaluation The selected pipeline uses {role}. Selection used validation macro-F1 after the fixed search. The held-out cohort contains 384 upstream expert-majority judgments in {evaluation['bootstrap']['groups']} article/source components. | Pipeline | Test macro-F1 | Accuracy | |---|---:|---:| {table} The existing DOXA framing head is a task-mismatch proxy: its binary control uses present/(present+absent), with original abstention states retained in the JSON receipt. It was trained for the broader evaluative-framing review criterion. The strongest control here was the character TF-IDF wording classifier, so the reported improvement does not depend on that proxy. The selected pipeline's gain over the strongest lexical/current-model control was {evaluation['macro_f1_gain']:.4f}. Its paired 95% source-group bootstrap interval was [{interval[0]:.4f}, {interval[1]:.4f}], using 2,000 draws. The registered minimum gain was 0.02 with a positive lower bound. The deployed quantized model's point gain over that control was {evaluation['quantized_macro_f1_gain']:.4f}. Its separately reported 95% group-bootstrap interval was [{evaluation['quantized_bootstrap']['gain_interval_95'][0]:.4f}, {evaluation['quantized_bootstrap']['gain_interval_95'][1]:.4f}]. That interval includes zero. The native model's positive interval and the registered quantization-parity gate support this provisional release; standalone superiority of the browser export at 95% is not established. Fine-tuning's observed macro-F1 difference from the frozen contextual pipeline was {evaluation['fine_tuning_gain_over_frozen']:.4f}. Both contextual pipelines were evaluated after validation selection. That comparison remains distinct from the product promotion gate. The original gate and its pre-test amendment are published alongside the export plan. The initial matrix-only and default matrix-plus-embedding quantized exports failed parity. After those held-out measurements, a bounded four-setting exporter comparison used validation passages to select per-channel, reduced-range QInt8. The final graph uses singleton inference matching the browser. Learned weights, calibration and registered release thresholds stayed fixed. EXPORT_REPAIR.md, EXPORT_VALIDATION.json and EXPORT_ATTEMPTS.json preserve the process and failures. The export repair occurred after initial held-out measurement; it is not a second untouched model-selection experiment. Quantized/native class agreement was {evaluation['native_quantized_agreement']:.3%}. The quantized graph is {evaluation['quantized_bytes']:,} bytes. Browser/native agreement was {parity['agreement']:.3%} over {parity['cases']} deterministic cases. Input above 256 tokens returns unresolved in the browser. Test input-limit counts are recorded in EVALUATION.json. Scores were temperature-scaled on validation and the uncertainty threshold was selected there. These model scores need validation for additional populations and genres. The temperature grid was fitted on the native validation outputs and chose 1.0, which leaves logits unchanged. The native validation outputs also chose the 0.70 resolution threshold. The exported graph uses those same locked settings; it has no separately fitted calibration. Its held-out Brier score was {quantized['brier']:.3f}, negative log likelihood {quantized['negative_log_likelihood']:.3f} and 10-bin ECE {quantized['ece_10_bins']:.3f}. Its resolved coverage was {quantized['resolved_coverage']:.1%}, with resolved macro-F1 {quantized['resolved_macro_f1']:.3f}. These coverage figures are distinct from full-cohort quality and are not model confidence guarantees. ## Data and interpretation The benchmark contains human wording judgments from BABE. DOXA added no new human annotations. It uses article URLs and exact/near-duplicate components to separate roles. The same outlets can occur across roles. Source metadata has known imperfections, including an upstream topic/link mismatch for case `babe-sg2-00611`. This is an article-group evaluation within the collected outlets, with those source limitations retained. The input is the supplied sentence/passage text. Outlet, topic, source IDs, annotators, reference labels and rationales stay outside the model input. Additional document context has no supervised BABE wording label here. English news is the evaluated genre. Academic papers, historical speech, translation, other languages and different political settings require separate validation. A wording flag can describe advocacy, criticism, quotation or an allegation that is warranted in context. No author ideology, prejudice category, factual-truth score or political neutrality certification follows from this binary wording screen. Use the other DOXA criteria and the original sources for their declared tasks. Review disagreements and the ID-only error records before drawing a finding. """ (STAGE / "EVALUATION.md").write_text(report) card = f"""--- language: en license: apache-2.0 library_name: transformers pipeline_tag: text-classification base_model: sentence-transformers/all-MiniLM-L6-v2 datasets: - Giuliocc/doxa-wording-benchmark tags: - political-discourse - media-bias - wording - onnx - contextual-review --- # DOXA contextual wording encoder Check wording in a supplied English passage with a compact contextual model, then read the speaker, evidence and surrounding context. The selected model uses {role}. Its original source task is BABE's expert-majority word-choice bias judgment. It returns a wording flag, no wording flag or an unresolved result under the published uncertainty threshold. [Use DOXA](https://doxa.tacitus.me/) · [TACITUS](https://tacitus.me/doxa/) · [GitHub](https://github.com/sargonxg/DOXA-by-TACITUS) · [Benchmark](https://huggingface.co/datasets/Giuliocc/doxa-wording-benchmark) · [Evaluation and limits](EVALUATION.md) The selected native pipeline reached **{candidate['macro_f1']:.3f} macro-F1** on 384 judgments from held-out source groups. Its gain over the strongest lexical or current DOXA control was {evaluation['macro_f1_gain']:.3f}, with paired 95% group-bootstrap interval [{interval[0]:.3f}, {interval[1]:.3f}]. The quantized model reached {quantized['macro_f1']:.3f}. Inspect the complete control table, failures and coverage in the evaluation report. The quantized export's own 95% gain interval includes zero; its point gain and native-model parity support a provisional wording screen, with further independent evaluation needed. ## Local inference The browser uses the checked quantized ONNX graph and tokenizer, totaling about {evaluation['quantized_bytes']/1_000_000:.1f} MB of model weights. Inference runs locally after the public asset download. The Python `inference.py` helper uses ONNX Runtime and the published runtime manifest. The native Transformer head returns two class logits. The helper and browser apply the validation temperature and uncertainty threshold, and retain input limits in their structured result. ```python from inference import WordingModel model = WordingModel("path/to/downloaded/model") result = model.check("The committee voted six to four to approve the policy.") print(result) ``` `model_score` is the positive wording class's score after validation temperature scaling. The output records that calibration method, resolution threshold and actual token count. Input longer than 256 tokens is unresolved. Long documents require passage selection and source context, as in DOXA Lab. The [fictional illustrations](illustrations.json) contain actual outputs and retain their authored provenance. ## Training and source provenance The benchmark's 3,639 admitted judgments retain original expert votes, strict majority admission and source-group roles. Article text was restored locally from the pinned upstream source for training. Public model artifacts contain IDs and predictions in place of article excerpts. The original source's licenses and article rights are documented by the benchmark. The base encoder is pinned at `1110a243fdf4706b3f48f1d95db1a4f5529b4d41` under Apache-2.0. Training used local CPU compute, seed 1729 and zero new spend. The registration, amendment, export plan, training history and code are included. Reproduction needs the DOXA project source, the benchmark restoration recipe and the pinned Python dependencies. Keep restored article text in the local benchmark workspace. See [REPRODUCE.md](REPRODUCE.md) for the complete experiment and export steps. The public benchmark release is pinned at `bea9a3f2d53b03069b0d814094ea860d75f1c322` (tag `v0.1.0`). The admitted split contains 2,950 training, 305 validation and 384 held-out judgments. Fixed search used learning rates 2e-5 and 5e-5, three epochs each, AdamW, balanced cross entropy and 256-token input. Validation selected learning rate 5e-5 at epoch 2. Candidate and frozen controls use the passage text alone; annotator votes, source, outlet and topic stay outside features. ## Scope This is a provisional wording screen for contextual review. Its evaluated genre is sampled English news. Academic papers and other domains need separate validation. A positive wording judgment can occur in legitimate criticism, declared advocacy or attributed speech. Read the original source and preserve supported political meaning when considering a revision. The current dataset supports a binary wording task. Other prejudice, research-validity and comparative-bias questions need their own evidence and labels. The same news outlets can occur in training and test roles, and known source-URL imperfections remain documented. Additional independent evaluation is needed before broad service-quality claims. """ if selected != "fine_tuned_encoder": card = card.replace("library_name: transformers", "library_name: onnxruntime") (STAGE / "README.md").write_text(card) scope = "A provisional screen trained on English news sentences labeled for wording bias. Academic and other genres require separate validation. Read the surrounding context." manifest["scope"] = scope write_json(STAGE / "runtime_manifest.json", manifest) space = ROOT / "space" space.mkdir(exist_ok=True) write_json(space / "manifest.json", manifest) public = sorted({path.relative_to(STAGE).as_posix() for path in STAGE.rglob("*") if path.is_file()} | {"SHA256SUMS"}) (ROOT / "PUBLIC_FILES.json").write_text(json.dumps(public, indent=2) + "\n") (STAGE / "SHA256SUMS").write_text("".join(f"{hashlib.sha256((STAGE/name).read_bytes()).hexdigest()} {name}\n" for name in public if name != "SHA256SUMS")) print(json.dumps({"selected_pipeline": selected, "files": len(public), "gate": gate, "new_spend_usd": 0})) if __name__ == "__main__": main()