Download expansion_v2/experiments/contextual-discourse/source/package_release.py from Giuliocc/doxa-methods: direct link, hf CLI and curl.
- Browser
- Download file 19.4 kB
-
https://huggingface.co/datasets/Giuliocc/doxa-methods/resolve/main/expansion_v2/experiments/contextual-discourse/source/package_release.py
- Command line
-
hf download hf://datasets/Giuliocc/doxa-methods/expansion_v2/experiments/contextual-discourse/source/package_release.py
-
curl -L -o package_release.py https://huggingface.co/datasets/Giuliocc/doxa-methods/resolve/main/expansion_v2/experiments/contextual-discourse/source/package_release.py
19.4 kB
| """Stage original tools/aggregate receipts and a separate parameter review. | |
| The public tools stage never acquires raw article text, raw annotations, | |
| row-level gold, TF-IDF vocabularies or private source fixtures. | |
| """ | |
| from pathlib import Path | |
| import json | |
| from shutil import copy2 | |
| from data import ROOT, fingerprint, write_json | |
| from metrics import TASKS | |
| from build_runtime_package import build | |
| LOCAL = ROOT / "local" | |
| PROJECT = ROOT.parents[1] | |
| SOURCES = ( | |
| "PROTOCOL.json", "DATA_LOCK.json", "DATA_REPAIR.md", "PUBLIC_DATA_REFERENCES.json", "BASE_MODEL_FILES.json", "HEADS_CONTRACT.json", "response.schema.json", "NOTICE", "REPRODUCE.md", "requirements.txt", | |
| "contracts.py", "inputs.py", "data.py", "metrics.py", "modeling.py", "train.py", "run_experiment.py", "inference.py", "diagnostics.py", | |
| "test_contracts.py", "test_reader.py", "test_runtime_validation.py", "build_runtime_package.py", "fresh_loader_check.py", "constant_control.py", "score_consistency.py", "score_contextful_consistency.py", "legacy_transfer.py", "browser-runtime.ts", "browser-worker.ts", "browser-client.ts", "browser_check.mjs", "tsconfig.json", "package_release.py", | |
| ) | |
| def checksum(folder, names): | |
| names = sorted(set(names) | {"SHA256SUMS"}) | |
| (folder / "SHA256SUMS").write_text("".join(f"{fingerprint(folder/name)} {name}\n" for name in names if name != "SHA256SUMS")) | |
| return names | |
| def public_measurements(value): | |
| """Retain aggregate evidence without fitted classifier policy values.""" | |
| if isinstance(value, list): | |
| return [public_measurements(item) for item in value] | |
| if isinstance(value, dict): | |
| excluded = {"calibration", "threshold", "margin", "scale", "intercept", "coefficient", "coefficients", | |
| "decision_threshold", "abstention_margin", "training_prevalence", "most_frequent_labels"} | |
| return {key: public_measurements(item) for key, item in value.items() if key not in excluded} | |
| return value | |
| def main(): | |
| evaluation = json.loads((LOCAL / "EVALUATION.json").read_text()) | |
| selection = json.loads((LOCAL / "LOCKED_SELECTION.json").read_text()) | |
| diagnostics = json.loads((LOCAL / "DIAGNOSTICS.json").read_text()) | |
| browser = json.loads((LOCAL / "BROWSER_PARITY.json").read_text()) if (LOCAL / "BROWSER_PARITY.json").exists() else None | |
| browser_pass = bool(browser and browser["label_agreement"] >= .98 and browser["exact_packing_agreement"] == 1 and not browser["source_payloads_sent"]) | |
| evaluation["gates"]["browser"] = browser_pass | |
| technical = evaluation["gates"]["native"] and evaluation["gates"]["quantized"] and browser_pass | |
| evaluation["gates"]["technical_passed"] = technical | |
| evaluation["gates"]["release"] = False | |
| write_json(LOCAL / "RELEASE_DECISION.json", {"evaluation_input_sha256": fingerprint(LOCAL / "EVALUATION.json"), | |
| "browser_receipt_sha256": fingerprint(LOCAL / "BROWSER_PARITY.json") if browser else None, | |
| "gates": evaluation["gates"], "public_model_parameters": "withheld"}) | |
| stage = ROOT / "stage" | |
| stage.mkdir(exist_ok=True) | |
| names = [] | |
| for source in SOURCES: | |
| path = stage / "source" / source | |
| path.parent.mkdir(exist_ok=True) | |
| copy2(ROOT / source, path) | |
| names.append(path.relative_to(stage).as_posix()) | |
| copy2(PROJECT / "LICENSE", stage / "LICENSE") | |
| names.append("LICENSE") | |
| package = build(stage) | |
| names.extend(path.relative_to(stage).as_posix() for path in package.glob("*.py")) | |
| for source, destination in ( | |
| (PROJECT / "expansion_release/context_data/SOURCE_RIGHTS.md", "SOURCE_RIGHTS.md"), | |
| (PROJECT / "expansion_release/context_data/source_rights.json", "source_rights.json"), | |
| (PROJECT / "expansion_release/quality/BASIL_INTEGRITY.json", "audit/BASIL_INTEGRITY.json"), | |
| (PROJECT / "expansion_release/quality/DISCOURSE_PREFIT_OBSERVATION.json", "audit/DISCOURSE_PREFIT_OBSERVATION.json"), | |
| (PROJECT / "expansion_release/quality/BASIL_DATA_REPAIRED_PREFIT_OBSERVATION.json", "audit/BASIL_DATA_REPAIRED_PREFIT_OBSERVATION.json"), | |
| (PROJECT / "expansion_release/quality/DISCOURSE_SELECTION_PRETEST_OBSERVATION.json", "audit/DISCOURSE_SELECTION_PRETEST_OBSERVATION.json"), | |
| (PROJECT / "expansion_release/quality/DISCOURSE_MODEL_INTEGRITY.json", "audit/DISCOURSE_MODEL_INTEGRITY.json"), | |
| ): | |
| if source.exists(): | |
| (stage / destination).parent.mkdir(parents=True, exist_ok=True) | |
| copy2(source, stage / destination) | |
| names.append(destination) | |
| for name in ("EVALUATION.json", "DIAGNOSTICS.json", "FRESH_LOADER.json", "CONSTANT_BASELINE.json", "LEGACY_TRANSFER.json", "input-coverage-fit.json", "fine_target_only-history.json", "fine_context-history.json", "BROWSER_PARITY.json"): | |
| source = LOCAL / name | |
| if source.exists(): | |
| value = json.loads(source.read_text()) | |
| if name == "EVALUATION.json": | |
| value = evaluation | {"private_audited_evaluation_sha256": fingerprint(source), | |
| "public_redactions": ["fitted_calibration_maps", "selected_decision_thresholds", "selected_abstention_margins", "row_level_outputs", "learned_weights"]} | |
| if name == "FRESH_LOADER.json": | |
| value["actual_custom_forward_cases"] = len(value.pop("illustrations", [])) | |
| if name == "BROWSER_PARITY.json": | |
| value.pop("rows", None) | |
| if name == "CONSTANT_BASELINE.json": | |
| for row in value["metrics"]["tasks"].values(): | |
| row.pop("reliability", None) | |
| if name == "LEGACY_TRANSFER.json": | |
| value.pop("previous_threshold", None) | |
| write_json(stage / name, public_measurements(value)) | |
| names.append(name) | |
| write_json(stage / "SELECTION_RECEIPT.json", { | |
| "selection_sha256": fingerprint(LOCAL / "LOCKED_SELECTION.json"), | |
| "protocol_sha256": selection["protocol_sha256"], "data_lock_sha256": selection["data_lock_sha256"], | |
| "selected_pipeline": selection["selected_pipeline"], "base_model": selection["base_model"], | |
| "base_revision": selection["base_revision"], "selected_native_weights_sha256": selection["native_weights_sha256"], | |
| "validation_export_receipt_sha256": fingerprint(LOCAL / "export/validation.json"), | |
| "selected_graph_sha256": selection["export"]["selected"]["sha256"] if selection["export"]["selected"] else None, | |
| "selection_used_test": False, "source_code_sha256": selection["source_code_sha256"], | |
| "private_parameters_and_selected_thresholds_published": False, | |
| }) | |
| names.append("SELECTION_RECEIPT.json") | |
| ids = ("M02", "M03", "M04", "M05", "M06", "M11", "M12", "M13", "M15") | |
| status = { | |
| "M02": {"status": "measured_candidate", "context_benefit_claim_qualified": evaluation["context_benefit_claim_qualified"], "scope": "BASIL lexical/informational source labels, real neighboring context"}, | |
| "M03": {"status": "two_source_task_heads_trained", "technical_qualification": technical, "six_prejudice_head_upgrade": "withheld_no_eligible_new_labels"}, | |
| "M04": {"status": "source_quote_behavior_measured_stance_contract_implemented", "stance_model": "withheld_no_endorse_report_rebut_labels"}, | |
| "M05": {"status": "implemented_and_measured", "coverage": evaluation["input_coverage"], "whole_document_global_attention": False}, | |
| "M06": {"status": "exact_anchors_and_reference_sensitivity_measured", "predicted_span_rationale": "not_supported", "human_sufficiency_labels": "not_available"}, | |
| "M11": {"status": "contract_implemented_model_withheld", "dependency": "Matched-case comparability/standard-specific human reference labels"}, | |
| "M12": {"status": "rubric_eligibility_implemented_heads_withheld", "dependency": "Framework/version-specific independent reviewed labels"}, | |
| "M13": {"status": "validation_calibration_and_test_reliability_measured", "domain_guard": "caller_declared_metadata_not_learned_OOD"}, | |
| "M15": {"status": "actual_artifact_measured" if "quantized" in evaluation else "withheld_no_validation_qualified_export", "native_gate": evaluation["gates"]["native"], "quantized_gate": evaluation["gates"]["quantized"], "browser_gate": browser_pass}, | |
| } | |
| status = {"release": "doxa-expansion-v0.2.0", "new_spend_usd": 0, "tasks": status, | |
| "technical_gates_passed": technical, "parameter_publication_status": "pending_lead_artifact_rights_review" if technical else "withheld_failed_technical_gate", | |
| "new_independent_human_reviews_by_DOXA": 0, "raw_source_and_annotation_publication": "withheld_no_affirmative_license_located"} | |
| write_json(stage / "ITEM_STATUS.json", status) | |
| write_json(ROOT / "ITEM_STATUS.json", status) | |
| names.append("ITEM_STATUS.json") | |
| candidate = evaluation["pipelines"][evaluation["selected_pipeline"]] | |
| control = evaluation["pipelines"][evaluation["strongest_lexical_control"]] | |
| native_interval = evaluation["native_bootstrap"]["gain_interval_95"] | |
| context_interval = evaluation["context_bootstrap"]["gain_interval_95"] | |
| quantized = evaluation.get("quantized") | |
| table = "\n".join(f"| {name} | {row['mean_positive_f1']:.3f} | {row['tasks']['BASIL_lexical_bias']['positive_f1']:.3f} | {row['tasks']['BASIL_informational_bias']['positive_f1']:.3f} |" for name, row in evaluation["pipelines"].items()) | |
| if (LOCAL / "CONSTANT_BASELINE.json").exists(): | |
| value = json.loads((LOCAL / "CONSTANT_BASELINE.json").read_text())["metrics"] | |
| table = f"| Training most-frequent labels | {value['mean_positive_f1']:.3f} | {value['tasks']['BASIL_lexical_bias']['positive_f1']:.3f} | {value['tasks']['BASIL_informational_bias']['positive_f1']:.3f} |\n" + table | |
| if quantized: | |
| value = quantized["metrics"] | |
| table += f"\n| Actual singleton quantized artifact | {value['mean_positive_f1']:.3f} | {value['tasks']['BASIL_lexical_bias']['positive_f1']:.3f} | {value['tasks']['BASIL_informational_bias']['positive_f1']:.3f} |" | |
| graph_text = "No validation-qualified quantized graph was available." | |
| if quantized: | |
| q_interval = quantized["bootstrap"]["gain_interval_95"] | |
| graph_text = f"The private singleton quantized graph reached {quantized['metrics']['mean_positive_f1']:.3f}, gain {quantized['gain']:+.3f}, with paired interval [{q_interval[0]:+.3f}, {q_interval[1]:+.3f}]. Native/export label agreement was {quantized['native_label_agreement']:.2%}; the withheld graph occupies {quantized['bytes']:,} bytes." | |
| readme = f"""# DOXA contextual discourse research | |
| Two independently scored source tasks: lexical bias and informational bias | |
| as operationalized by the original BASIL annotations. The input is a | |
| complete source sentence plus its real neighbors. This experiment does | |
| not turn these labels into prejudice categories or a political-neutrality | |
| score. Exact source anchors, input coverage, quote boundaries and unresolved | |
| results remain inspectable. | |
| [TACITUS](https://tacitus.me/doxa/) · [DOXA Lab](https://doxa.tacitus.me/) | |
| · [GitHub](https://github.com/sargonxg/DOXA-by-TACITUS) | |
| · [Context data](https://huggingface.co/datasets/Giuliocc/doxa-context-bias/tree/abf78298dd80709867fef522a35acb6ed63745c8) | |
| · [Matched coverage](https://huggingface.co/datasets/Giuliocc/doxa-matched-coverage/tree/44eff54fae2f21e6c63bd449cde2c966125ac1d7) | |
| ## Measured comparison | |
| The fixed event/source split has 5,016 training, 1,647 validation and 1,313 | |
| held-out source sentences. The test contains 17 event/source families. | |
| Checkpoint, head regularization, Platt maps, thresholds, uncertainty margins | |
| and quantized representation were selected on validation before test output. | |
| The primary metric averages the positive-class F1 for the two tasks. This | |
| prevents the many negative cases from hiding missed bias spans. Each task's | |
| class metrics, confusion matrix, reference prevalence and reliability curve | |
| are retained in EVALUATION.json. | |
| | Pipeline | Mean positive F1 | Lexical positive F1 | Informational positive F1 | | |
| |---|---:|---:|---:| | |
| {table} | |
| Validation selected `{evaluation['selected_pipeline']}`. Its native primary | |
| gain over the strongest held-out TF-IDF control was | |
| {evaluation['native_gain']:+.3f}; paired 95% event-group bootstrap interval | |
| [{native_interval[0]:+.3f}, {native_interval[1]:+.3f}], 2,000 draws. Native | |
| qualification: **{evaluation['gates']['native']}**. | |
| {graph_text} | |
| Direct artifact qualification: **{evaluation['gates']['quantized']}**. | |
| Browser qualification: **{browser_pass}**. Aggregate technical gates: | |
| **{technical}**. **No new contextual model is released.** Both improvement | |
| intervals include zero, and the contextual pipeline is worse than its | |
| target-only control. Original tools and aggregate failure evidence are | |
| published; learned weights, fitted calibration maps, selected decision | |
| policies and row-level outputs remain private. Browser compatibility does | |
| not override the failed quality gate. Existing qualified DOXA models remain | |
| unchanged. | |
| The contextual pipeline's difference from the strongest target-only | |
| ablation was {evaluation['context_gain']:+.3f}, interval | |
| [{context_interval[0]:+.3f}, {context_interval[1]:+.3f}]. The specific claim | |
| that adding neighbors improves quality is qualified: | |
| **{evaluation['context_benefit_claim_qualified']}**. Input length and extra | |
| context alone are not evidence of better decisions. | |
| ## Source and annotation provenance | |
| The source is [BASIL](https://github.com/launchnlp/BASIL) at revision | |
| `4fdbc4f68d5ddae648990063cb6dd11424d96222`, described by | |
| [Fan et al., 2019](https://aclanthology.org/D19-1664/). Its 300 source articles | |
| contain 7,984 original body sentence records. Eight unannotated normalized | |
| empty targets were excluded from modeling, leaving 7,976. Final human spans | |
| are aggregated to these two source-task labels. The paper describes two | |
| annotators discussing consensus; individual vote records are unavailable. | |
| DOXA added no new independent human judgments. | |
| Public paragraph/context nominations are unannotated and were not used as | |
| supervised bias labels. The public source metadata/restoration package and | |
| its exact revisions are recorded in source/PUBLIC_DATA_REFERENCES.json. | |
| Source-record-specific identities repair reused upstream UUIDs. The first | |
| restoration and interrupted controls are rejected and retained locally. | |
| Independent checks passed exact source offsets, original spans, event/URL/ | |
| near-duplicate grouping and prior DOXA overlap. The split contains the same | |
| three source outlets across roles; it does not test new-outlet generalization. | |
| Unsupervised base-encoder pretraining overlap is unknown. See | |
| [source repair](source/DATA_REPAIR.md), [data lock](source/DATA_LOCK.json) | |
| and the independent integrity receipts in `audit/`. | |
| No affirmative redistribution license for dataset annotations or source | |
| article text was found. Public tools/receipts contain original code and | |
| aggregate measurements. Article passages, raw spans/rationales, row-level | |
| gold, TF-IDF vocabularies and browser source fixtures stay local. No author | |
| permission or general training-data license is claimed. A parameters-only | |
| artifact has a separate publication review. | |
| ## Input, evidence and limits | |
| The packer preserves the full target and uses up to two preceding and two | |
| following source sentences, within 256 tokens. Context budget loss and | |
| target/document/paragraph coverage are measured. Overlong targets abstain; | |
| the pipeline has no fixed document page or sentence-count cap. This is | |
| bounded local context, with no claim of global book-length attention. | |
| Exact source anchors identify where language came from. Human reference | |
| spans in the local benchmark are not a predicted rationale for arbitrary | |
| uploads. Reference-span interventions report score sensitivity and do not | |
| constitute new sufficiency annotations or a causal explanation. This model | |
| does not produce a trained evidence-span detector. | |
| Quote/polarity reference attributes remain outside model inputs. A quoted | |
| source's biased language does not establish the reporter's endorsement. | |
| Endorse/report/rebut stance, the six broader DOXA criteria, named antisemitism | |
| frameworks, omission and comparative double standards need their own labels | |
| and evidence. Contracts return unresolved/unsupported outputs for them. | |
| The evaluated genre is English news. Academic papers, other languages, | |
| other periods and different political settings need independent task | |
| validation. Language/genre checks use caller metadata, not a learned domain | |
| detector. Scores are validation-calibrated source-task model scores, not harm | |
| severity, misconduct probabilities or certifications of political neutrality. | |
| Forceful policy criticism and advocacy may legitimately contain wording the | |
| source task labels as biased; a model flag does not establish wrongdoing. | |
| ## Reproduce and extend | |
| Original code, fixed protocol, repaired source lock, every candidate's | |
| validation history, failed gates and actual export receipts are provided. | |
| See source/REPRODUCE.md. Native full fine-tuning and frozen semantic heads | |
| use the 22.7M-parameter MiniLM encoder pinned at | |
| `1110a243fdf4706b3f48f1d95db1a4f5529b4d41`; the base card declares Apache-2.0. | |
| Training uses one local CPU thread and zero new spend. No hosted inference | |
| or paid training job is implied. | |
| The next data requirement is independent reviewed labels for the specific | |
| new task and target genre, with source/event grouping and explicit rights. | |
| Contracts keep those missing capabilities visible without fabricating a | |
| detector, human review or reference-standard status. | |
| """ | |
| (stage / "README.md").write_text(readme) | |
| names.append("README.md") | |
| public = checksum(stage, names) | |
| write_json(ROOT / "PUBLIC_FILES.json", public) | |
| if technical: | |
| candidate_stage = ROOT / "parameters_candidate" | |
| (candidate_stage / "onnx").mkdir(parents=True, exist_ok=True) | |
| runtime = LOCAL / "runtime" | |
| parameter_names = [] | |
| for path in runtime.rglob("*"): | |
| if path.is_file(): | |
| name = path.relative_to(runtime) | |
| (candidate_stage / name).parent.mkdir(parents=True, exist_ok=True) | |
| copy2(path, candidate_stage / name) | |
| parameter_names.append(name.as_posix()) | |
| copy2(LOCAL / "selected-native/model.safetensors", candidate_stage / "model.safetensors") | |
| parameter_names.append("model.safetensors") | |
| architecture = {"architecture": "ContextEncoder", "base_model": "sentence-transformers/all-MiniLM-L6-v2", | |
| "base_revision": "1110a243fdf4706b3f48f1d95db1a4f5529b4d41", "input_names": ["input_ids", "attention_mask", "token_type_ids", "target_mask", "context_mask"], | |
| "pooling": "L2 normalized attention-masked target/context means concatenated", "independent_sigmoid_tasks": list(TASKS), | |
| "native_weights_sha256": fingerprint(candidate_stage / "model.safetensors"), "publication_review": "pending_lead_decision"} | |
| write_json(candidate_stage / "architecture.json", architecture) | |
| parameter_names.append("architecture.json") | |
| write_json(ROOT / "PARAMETER_REVIEW_FILES.json", checksum(candidate_stage, parameter_names)) | |
| print(json.dumps({"public_original_tool_files": len(public), "technical_passed": technical, | |
| "parameters_staged_for_lead_review": technical, "raw_text_or_gold_published": False, "new_spend_usd": 0})) | |
| if __name__ == "__main__": | |
| main() | |