File size: 14,952 Bytes
1f5647a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
"""Stage original code and aggregate receipts only; never learned parameters."""
from hashlib import sha256
import json
from pathlib import Path
import shutil

HERE = Path(__file__).resolve().parent
PRIVATE = HERE / "work/private"
PUBLIC = HERE / "public"


def load(path):
    return json.loads(path.read_text())


def main():
    validation = load(PUBLIC / "VALIDATION_RESULTS.json")
    test = load(PUBLIC / "TEST_RESULTS.json") if (PUBLIC / "TEST_RESULTS.json").exists() else None
    if test:
        test["model_promotion"] = "withheld_technical_gate_failed" if not test["technical_gate_pass"] else "withheld_pending_explicit_lead_rights_approval"
        test["original_private_result_sha256"] = sha256((PRIVATE / "test_results.json").read_bytes()).hexdigest()
        (PUBLIC / "TEST_RESULTS.json").write_text(json.dumps(test, ensure_ascii=False, indent=2) + "\n")
    current = test or validation
    geometry = load(PUBLIC / "VALIDATION_FAILURE_GEOMETRY.json")["methods_heads"]
    val_lex, val_inf = geometry["frozen_minilm_probe/lex"], geometry["frozen_minilm_probe/inf"]
    status = "Held-out source-span evaluation complete" if test else "Development fit complete; held-out test remains locked"
    rows = []
    for method, result in current["methods"].items():
        rows.append(f"| {method} | {result['heads']['lex']['token']['f1']:.4f} | {result['heads']['inf']['token']['f1']:.4f} | {result['macro']['token_f1']:.4f} | {result['macro']['strict_span_f1']:.4f} | {result['macro']['relaxed_span_f1']:.4f} |")
    train_receipt = load(PRIVATE / "train-feature-receipt.json")
    val_receipt = load(PRIVATE / "validation-feature-receipt.json")
    coverage = {"train": train_receipt, "validation": val_receipt}
    if test:
        coverage["test"] = load(PRIVATE / "test-feature-receipt.json")
    (PUBLIC / "COVERAGE_RUNTIME.json").write_text(json.dumps(coverage, indent=2) + "\n")
    text = f'''# DOXA source-span probe

**{status}. Parameters remain local and are not released.**

This bounded experiment asks whether a frozen Hugging Face MiniLM encoder plus two small trained token heads can recover the exact lexical/informational spans marked by the original BASIL annotators. It uses actual source annotations, retains original sentence/article offsets, and compares against task-matched token controls. A recovered source mark is not proof of political prejudice, evidence sufficiency, the model's faithful reasoning or an author's beliefs.

The underlying BASIL paper reports two annotators reaching discussion consensus. Individual votes are unavailable. No DOXA human review has been invented. Outside a marked span means no released annotation under that task, not certified harmless or unbiased language. The original lexical/informational task is not automatically mapped to DOXA's broader taxonomy.

## Actual measurements

Current table: **{current['split']}**, {current['sentences']:,} sentences / {current['events']} event groups / {current['covered_tokens']:,} covered regex tokens. Validation thresholds were selected on validation only; development results do not qualify as held-out improvement.

| Fixed method | Lexical token F1 | Informational token F1 | Macro token F1 | Strict span F1 | IoU≥.5 span F1 |
|---|---:|---:|---:|---:|---:|
''' + "\n".join(rows) + f'''

The frozen-base probe's validation macro token F1 is {validation['methods']['frozen_minilm_probe']['macro']['token_f1']:.4f}, versus {validation['methods'][validation['selected_control_by_validation']]['macro']['token_f1']:.4f} for the validation-selected token control. Its strict span F1 is {validation['methods']['frozen_minilm_probe']['macro']['strict_span_f1']:.4f}, versus {validation['methods'][validation['selected_control_by_validation']]['macro']['strict_span_f1']:.4f}. These weak boundary results do not justify a new deployed highlight feature. No additional candidate or threshold search follows these outcomes.

The validation probe emits {val_lex['predicted_spans']:,} lexical spans for {val_lex['reference_spans']} references and {val_inf['predicted_spans']:,} informational spans for {val_inf['reference_spans']} references. Of these, {val_lex.get('predicted_spans_without_reference_overlap',0):,} lexical predictions and {val_inf.get('predicted_spans_without_reference_overlap',0):,} informational predictions have no reference overlap; {val_inf.get('reference_spans_fragmented_across_predictions',0)} informational reference spans are fragmented across multiple predictions. These predictions have poor precision and fragmented boundaries. The head is withheld from user-facing highlights. Reference-unmatched predictions count as benchmark errors; the annotation does not establish an author's beliefs or certify unmarked language as harmless. Aggregate per-method geometry is published separately; source text and annotation rows remain local.

Train encoder coverage is {train_receipt['encoder_coverage']:.6%}; validation coverage is {val_receipt['encoder_coverage']:.6%}. All positive train/validation tokens are covered. All 317 validation reference spans have boundaries aligned to the declared regex-token units; reconstructing spans from gold token labels yields strict span F1=1.0 for both validation types. Thus the weak development scores are not concealed truncation or an impossible-boundary artifact. Exact duplicate annotation intervals are counted once in span metrics while original record IDs and duplicate counts remain in local receipts. The pre-test `GOLD_TOKEN_RECONSTRUCTION.json` covers training/validation only, including the slight training informational-boundary loss.

Frozen base feature extraction took {train_receipt['seconds']:.2f}s for training and {val_receipt['seconds']:.2f}s for validation on one CPU thread. Head/control fitting plus validation selection took {validation['selection_seconds']:.2f}s. These measurements exclude downloads, model loading and article restoration. Five source-integrity unit checks cover Unicode source offsets, overlapping types, contiguous-span boundaries, one-to-one matching, duplicate references and the test-access lock.

Actual validation source linkage passes 52,641 automated checks across 66 original article hashes, all 1,647 sentences, all 317 human source marks, every method/head prediction record and 34,141 predicted local-to-article span conversions. The aggregate receipt is `VALIDATION_ANCHOR_INTEGRITY.json`; this checks coordinates and source versions, not prediction meaning.

## Registered gate and current disposition

The protocol was independently observed before fitting. Event/source-family roles come directly from the accepted frozen-v2 BASIL source lock. The probe uses only focal sentence text and the original pinned frozen MiniLM base; event/outlet/date, source IDs, speaker, target, quotation/polarity labels and annotation notes are never features. The main contextual model selection is separate. No test file can be opened by this tool until the original contextual selection and this probe selection have been explicitly locked and independently observed. Source holdout is relative to this experiment; base-encoder pretraining exposure is unknown.

The preregistered technical gate requires a macro token F1 gain of at least five percentage points over every fixed control, a positive paired event-bootstrap lower confidence bound against the validation-selected control, no material per-head regression, strict/relaxed span noninferiority and near-complete input coverage. All method outcomes, false-positive/miss counts and uncertainty are retained when test scoring is authorized. A failing gate is reported, not tuned away.

Even a technical pass does not approve rights. BASIL article text and released annotations have unresolved reuse/redistribution permissions in the checked source package. This public bundle contains original DOXA code, protocol, hashes and aggregate diagnostics only. It contains **no publisher prose, original annotation rows/spans, token vocabulary, embeddings, fitted weights, learned thresholds or per-row predictions**. Source text, labels and all trained parameters remain in a separate local-only directory. Lead approval of artifact rights is mandatory before any parameter release. Public weights eligibility remains false.

## Exact source and method

Original source: BASIL, revision `4fdbc4f68d5ddae648990063cb6dd11424d96222`; Fan et al. (2019), [In Plain Sight: Media Bias Through the Lens of Factual Reporting](https://aclanthology.org/D19-1664/). Body reference offsets are end-exclusive Unicode code points relative to the exact sentence. Article offsets add the original sentence start; paragraph starts are not substituted. Title spans are excluded.

Encoder: `sentence-transformers/all-MiniLM-L6-v2`, revision `1110a243fdf4706b3f48f1d95db1a4f5529b4d41`, frozen throughout. Fast-tokenizer offsets map original regex tokens to mean pooled last-layer WordPiece vectors. Special/padding tokens are excluded. Overlapping 256-token windows preserve complete tokens; missing coverage is counted. Independent logistic heads are fitted on training only. Token-character and frequency controls also use training-only data. Thresholds are selected on validation once, then all parameters and receipts are locked.

Strict span F1 uses exact original start/end matches. Relaxed F1 uses maximum-cardinality one-to-one matching at intersection-over-union ≥.5. Token and character metrics use original reference unions; two types can overlap. Event-cluster resampling preserves dependence among sentences from the same event. None of these overlap metrics establishes a sufficient explanation or evidence for a claim.

The original tools require local restoration and the pinned source-role manifests. Use a CPU environment with `requirements.txt`; run feature extraction on train/validation, then `fit`. The `score_test` path remains blocked until the recorded selection unlock and independent observation exist. Unresolved source rights are not cleared by running a local experiment. No hosted inference, paid training or new service is used. **New spend: $0.**

The useful next step is better task-matched, rights-clear span supervision and a separately registered contextual span model with genuine human boundary review. Existing head parameters are not presented as an advanced bias-analysis service.
'''
    if test:
        interval = test["paired_event_bootstrap_95pct"]
        text += ("\n## Held-out decision\n\nTechnical gate: **" + ("PASS" if test["technical_gate_pass"] else "FAIL")
                 + f"**. Against the validation-selected control, macro token F1 changes by {test['probe_minus_selected_control_macro_token_f1']:+.4f}; the paired {test['events']}-event bootstrap 95% interval is [{interval[0]:+.4f}, {interval[1]:+.4f}] (2,000 resamples, seed1729).\n\n"
                 + "| Preregistered condition | Result |\n|---|---|\n"
                 + "\n".join(f"| {name} | {'PASS' if value else 'FAIL'} |" for name, value in test["technical_gate_checks"].items())
                 + "\n\nEvery fixed method and all failure counts remain available. A token-level gain cannot substitute for failed span recovery or missing rights. Parameters remain local and excluded from user-facing highlights. No post-test refitting, threshold search or source-role change is performed.\n")
        audit = HERE.parent / "quality/SPAN_PROBE_INTEGRITY.json"
        if audit.exists():
            assert load(audit)["status"] == "pass"
            shutil.copy2(audit, PUBLIC / "INDEPENDENT_REPLAY.json")
            text += "\nThe independent automated replay passes: original source labels/offsets, all method/head confusion counts, validation threshold choices and all 2,000 event-bootstrap draws reproduce. `INDEPENDENT_REPLAY.json` confirms the technical gate failure. This audit adds zero human reviews.\n"
    rights = load(PUBLIC / "RIGHTS_RELEASE_DECISION.json")
    rights["technical_test_gate_evaluated"] = bool(test)
    rights["technical_test_gate_pass"] = test["technical_gate_pass"] if test else None
    (PUBLIC / "RIGHTS_RELEASE_DECISION.json").write_text(json.dumps(rights, indent=2) + "\n")
    (PUBLIC / "README.md").write_text(text, encoding="utf-8")
    tools = PUBLIC / "tools"
    tools.mkdir(exist_ok=True)
    for name in ("probe.py", "test_probe.py", "register_protocol.py", "report.py", "oracle_diagnostics.py", "analyze_failures.py", "audit_anchors.py", "requirements.txt"):
        shutil.copy2(HERE / name, tools / name)
    (PUBLIC / "NOTICE").write_text("Original DOXA code: Apache-2.0. Documentation and protocol: CC BY 4.0, attribution TACITUS / DOXA. No license to BASIL publisher prose, annotations, vocabulary or derived parameters is granted. These remain excluded. Base MiniLM has its own upstream Apache-2.0 license. No trained parameters are released in this bundle.\n")
    allowed = {"PROTOCOL.json", "IMPLEMENTATION_LOCK.json", "PROBE_SELECTION_LOCK.json", "TEST_SOURCE_HASH_COMMITMENT.json", "VALIDATION_RESULTS.json", "COVERAGE_RUNTIME.json", "GOLD_TOKEN_RECONSTRUCTION.json", "VALIDATION_FAILURE_GEOMETRY.json", "VALIDATION_ANCHOR_INTEGRITY.json", "RIGHTS_RELEASE_DECISION.json", "ENCODER_RECEIPT.json", "README.md", "NOTICE",
               *("tools/" + name for name in ("probe.py", "test_probe.py", "register_protocol.py", "report.py", "oracle_diagnostics.py", "analyze_failures.py", "audit_anchors.py", "requirements.txt"))}
    if test:
        allowed.add("TEST_RESULTS.json")
        if (PUBLIC / "TEST_FAILURE_GEOMETRY.json").exists():
            allowed.add("TEST_FAILURE_GEOMETRY.json")
        if (PUBLIC / "TEST_ANCHOR_INTEGRITY.json").exists():
            allowed.add("TEST_ANCHOR_INTEGRITY.json")
        if (PUBLIC / "INDEPENDENT_REPLAY.json").exists():
            allowed.add("INDEPENDENT_REPLAY.json")
    actual = {str(path.relative_to(PUBLIC)) for path in PUBLIC.rglob("*") if path.is_file() and path.name != "publication_manifest.json"}
    assert actual == allowed, {"unexpected": sorted(actual - allowed), "missing": sorted(allowed - actual)}
    files = [{"path": name, "bytes": (PUBLIC / name).stat().st_size, "sha256": sha256((PUBLIC / name).read_bytes()).hexdigest()} for name in sorted(allowed)]
    (PUBLIC / "publication_manifest.json").write_text(json.dumps({"files": files, "public_parameters": False, "public_source_text": False,
        "public_source_annotations": False, "public_vocabulary": False, "status": status, "spent_usd": 0}, indent=2) + "\n")
    (HERE / "BUILD_STATUS.md").write_text(f"# Span probe status\n\n{status}. Train/validation selection locked; parameters withheld. Source task: upstream marked spans only. Test access is separately gated. Public bundle contains original code/aggregate receipts only. $0 spent.\n")
    print(json.dumps({"status": status, "public_files": len(files), "public_parameters": False}, indent=2))


if __name__ == "__main__":
    main()