Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions .github/workflows/eval-revision-reference.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
name: EVAL-REV-01 independent source-only reference
on:
push:
paths:
- 'research/delayed_revision_reference/**'
- '.github/workflows/eval-revision-reference.yml'
pull_request:
paths:
- 'research/delayed_revision_reference/**'
- '.github/workflows/eval-revision-reference.yml'
workflow_dispatch:
permissions:
contents: read
jobs:
exact:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- run: python -m unittest discover -s research/delayed_revision_reference -p 'test_*.py' -v
39 changes: 39 additions & 0 deletions research/delayed_revision_reference/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# EVAL-REV-01: evaluating revision-aware recurrent representations

**Source-only mathematical crosswalk, 18 November 2026.** Upstream [Beyond Bayes BB-CQ-05 PR #24](https://github.com/patrickdugan/beyond-bayes/pull/24), frozen `main` merge `abc89f73d223f00305eb0416a34fe5aee602494d`. Exact model: 12 known-label reports, 3 regime priors (9/20,7/20,1/5), match probabilities (19/20,13/20,3/20), delayed public correction schedule. The independent [oracle](bridge.py) and [tests](test_bridge.py) re-enumerate raw histories on smaller domains; they do not import upstream scorers.

## Evidence claim to audit

The current marginal posterior can be sufficient to predict a hidden regime **before** a correction schedule becomes visible while failing to preserve the information needed to update after the schedule arrives. For any 1≤j<n, the self-contained encoder must distinguish all 2^n old bit vectors to answer every legal delayed revision exactly. For n=12, this is 4096 classes / 12 fixed bits. Separately retaining the current count-posterior label requires an additional tag of up to 10 bits inside its largest fiber; the joint optimum remains 12 bits. If the schedule arrives **before encoding**, the calibrated accepted-report count is sufficient. An external archive can supply the old count at corrected slots; with j=6, its numeric message has 7 values / 3 bits. These omit archive/verification cost and assume full trusted versions.

The upstream exact six-revision expected Brier risks (unhalved 3-class score) are 0.170499060115450 for aggregate-only and 0.106036369270665 for full Bayes, a gap 0.064462690844785. This is inherited **mathematical** evidence, not a novel neural effect or fresh independent confirmation. The preregistered authorization gain at BB-CQ-04 was 0.006206757142 below the 0.02 practical gate, so it remains **HEADROOM_BLOCKED** for that task.

## Exact evaluation decomposition

Let `X` be the named old bit vector, `S` the correction schedule and `Y` the accepted replacements. Define `H=sigma(S,X,Y)` and `G_r=sigma(S,sum(X),Y,X[S[:r]])` for a fixed, outcome-independent disclosure order. With `p_H=P(K|H)` and `p_r=P(K|G_r)`, conditional expectation gives `p_r=E[p_H|G_r]`. For any predictor `a` computed only from `G_r`:

```
E[Brier(a,K)] - E[Brier(p_H,K)]
= E[||a-p_r||_2^2] + E[||p_r-p_H||_2^2].
```

The first term is **model approximation error**, estimated on independent issuer roots. The second is **irreducible information loss** for the explicitly count-restricted arm and is known exactly for this finite generator. An observational probe might estimate `p_r` accurately while a native hidden-state edit does not transport it forward. Label that outcome observational.

A raw-stream recurrent model receives all of `X` before `S` is revealed. After receiving `S` and `Y`, its complete input history is `H`; its final Bayes comparator is `p_H` for every `r`. Repeating old bits can help the model recover forgotten information, while the optimal full-input posterior stays fixed. Restricting hidden-state capacity leaves the model free to retain functions of `X` other than its total, so capacity alone does not make its output `G_r`-measurable. The count-restricted formula requires an enforced old-history interface containing only `sum(X)` plus the declared disclosures.

For example, with `n=4`, `S=(0,)`, `Y=(0,)`, the old vectors `(1,0,0,0)` and `(0,1,0,0)` have the same `G_0` and different accepted counts. Their full-input Bayes posteriors differ. Across the finite population, using `a=p_H` gives expected excess relative to `p_r` equal to `-E[||p_r-p_H||_2^2]`, which is negative whenever information is lost. This witness prevents interpreting that quantity as nonnegative approximation error for a learner with full old-input access.

## Gym protocol for BPD / LoopedTransformers / Control-Harness

Fix and hash the full source generator, exact oracle, model checkpoints, event grammar and all arms **before** sampling the first development root. Separate early from delayed schedule cohorts and include full replay, calibrated early-count, reduced-information Bayes, archive-verified delta, stale-native, and physically matched neural shams. Freeze `r=0..j` and the number of evidence amendments per root.

The primary registered neural endpoint should be root-level **input-matched excess Brier**, `Brier(a,K)-Brier(p_F,K)`, where `F` is that arm's complete input history and `p_F=P(K|F)`. Use a root-paired difference against a strong baseline with identical input privileges. The raw-stream arm has `F=H` after all replacements arrive. An enforced count-restricted arm has `F=G_r` and reports `Brier(p_r,K)-Brier(p_H,K)` separately. The expected approximation term is nonnegative for the matching information set; an empirical paired estimate can fluctuate below zero. For a causal-mechanism claim, intervene on native recurrent states at fixed model and dose, measure final task behavior and future logits; match random/gauge/nuisance directions and include a no-edit reference. A full-input replay advantage alone establishes input handling.

The independent unit is one issuer/source root when reusing a frozen model; for cross-training generalization count independently initialized **model roots**. Each root's 12 report slots, 3 correction sizes, disclosure stages, shams and decisions are repeated observations on that root. Do not count them as extra replications. Multiple exploration-selected endpoints must use a separately reserved confirmation cohort.

The native study must pass the existing [mechanistic resolution preflight](../../skills/evalmath-mechinterp-power/SKILL.md). Calibrate physically equal-dose shams on independent development roots, state a minimum scientifically meaningful Brier change, establish sufficient task headroom and selection-family adjustment. For a mean Brier effect, use the same paired root-mean statistic and a stated uncertainty procedure for the sham comparison. The 95/95 maximum-sham order-statistic rule needs >=59 independent calibration units under the published conditions and provides a per-root tolerance statement. A mean-effect gate requires a mean-matched sham estimator. **Zero external/new protected roots opened** by this crosswalk.

## Independent oracle scope

`python -m unittest discover -s research/delayed_revision_reference -p 'test_*.py' -v` checks the conditional posterior through raw bit-vector and named-schedule enumeration for small n, exact Brier variance decomposition and memory accounting. A named-slot collision and a negative full-input-versus-reduced expected excess check enforce the comparator's information contract. It does not claim a second full n=12 enumeration or a new Lean proof. [BB-CQ-05's archived receipt](https://github.com/patrickdugan/beyond-bayes/blob/main/results/bb_cq05_exact_v1.json) remains the canonical larger-domain source with source-hashed reproduction.

129 changes: 129 additions & 0 deletions research/delayed_revision_reference/bridge.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
"""Independent small-world Bayesian oracle for delayed evidence revisions.

No imports from Beyond Bayes. This is a finite reference for audit and
experimental design, not an authenticated evidence collector or a neural
mechanism test. A provisional report at a corrected slot is fair noise.
"""
from __future__ import annotations

from fractions import Fraction as Q
from itertools import product
from math import comb

PRIORS = (Q(9,20), Q(7,20), Q(1,5))
MATCH = (Q(19,20), Q(13,20), Q(3,20))


def binom(n: int, k: int, p: Q) -> Q:
if not 0 <= k <= n:
return Q(0)
return Q(comb(n,k))*p**k*(1-p)**(n-k)


def norm(weights):
z = sum(weights,Q(0))
if not z:
raise ValueError("impossible observation")
return tuple(w/z for w in weights)


def analytic(n: int, slots: tuple[int,...], old_m: int,
new: tuple[int,...], revealed_old: tuple[int,...]):
"""Pr(K | S, old_count, new, old prefix from slots), exact rational."""
j=len(slots);r=len(revealed_old);q=sum(new);s=sum(revealed_old)
if not (1 <= n <= 6 and 0 <= j <= n and 0 <= r <= j
and len(new)==j and len(set(slots))==j
and all(type(i)==int and 0<=i<n for i in slots)
and all(type(i)==int and i in (0,1) for i in new+revealed_old)
and type(old_m)==int and 0<=old_m<=n):
raise ValueError("invalid contract")
weights=[]
for prior,t in zip(PRIORS,MATCH):
old_valid = sum(binom(n-j,u,t)*binom(j-r,old_m-s-u,Q(1,2))
for u in range(n-j+1))
weights.append(prior*t**q*(1-t)**(j-q)*old_valid)
return norm(weights)


def independent_raw_oracle(n: int, slots: tuple[int,...], old_m: int,
new: tuple[int,...], revealed_old: tuple[int,...]):
"""Brute-force all old bit vectors; no call to the analytic count scorer."""
j=len(slots);r=len(revealed_old)
weights=[]
schedule=set(slots)
for prior,t in zip(PRIORS,MATCH):
weight=Q(0)
for old in product((0,1),repeat=n):
if sum(old)!=old_m or tuple(old[s] for s in slots[:r])!=revealed_old:
continue
w=prior
for i,bit in enumerate(old):
w*=Q(1,2) if i in schedule else (t if bit else (1-t))
for bit in new:
w*=t if bit else (1-t)
weight+=w
weights.append(weight)
return norm(weights)


def final_full(n: int, old: tuple[int,...], slots: tuple[int,...],
new: tuple[int,...]):
"""Bayes for the complete old-input stream after S and all Y arrive.

This is the input-matched final comparator for a learner that received
named old bits; further old-bit disclosures repeat existing input.
"""
if len(old)!=n or len(slots)!=len(new):
raise ValueError("wrong dimensions")
accepted=list(old)
for i,bit in zip(slots,new):
accepted[i]=bit
m=sum(accepted)
return norm(tuple(prior*t**m*(1-t)**(n-m)
for prior,t in zip(PRIORS,MATCH)))


def brier(p, regime: int):
return sum((x-int(i==regime))**2 for i,x in enumerate(p))


def raw_population(n: int, slots: tuple[int,...], r: int):
"""Exact expected Brier and squared gap; small-domain completeness oracle."""
j=len(slots)
if not (1<=n<=5 and 0<=j<=n and 0<=r<=j):
raise ValueError("outside audit domain")
schedule=set(slots)
full_risk=limited_risk=gap=mass=Q(0)
for k,(prior,t) in enumerate(zip(PRIORS,MATCH)):
for old in product((0,1),repeat=n):
likelihood=prior
for i,v in enumerate(old):
likelihood*=Q(1,2) if i in schedule else (t if v else (1-t))
for new in product((0,1),repeat=j):
p=likelihood
for v in new:
p*=t if v else (1-t)
limited=independent_raw_oracle(n,slots,sum(old),new,
tuple(old[i] for i in slots[:r]))
full=final_full(n,old,slots,new)
full_risk+=p*brier(full,k)
limited_risk+=p*brier(limited,k)
gap+=p*sum((a-b)**2 for a,b in zip(full,limited))
mass+=p
assert mass==1
assert limited_risk-full_risk==gap
return {"full_brier":full_risk,"limited_brier":limited_risk,
"regret":gap,"mass":mass}


def information_capacity(n:int,j:int):
"""Worst-case *self-contained* continuation bits under delayed schedule."""
if not (type(n)==int and type(j)==int and 1<=j<n<=12):
raise ValueError("1 <= j < n <= 12 required")
biggest=max(comb(n,m) for m in range(n+1))
return {"histories":2**n,"initial_posterior_labels":n+1,
"self_contained_bits":n,"max_label_fiber":biggest,
"extra_fixed_tag_bits":(biggest-1).bit_length(),
"verified_old_sum_message_bits":j.bit_length(),
"early_count_field_bits":n.bit_length()}

72 changes: 72 additions & 0 deletions research/delayed_revision_reference/test_bridge.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
"""Independent checks for delayed-revision posterior and scoring reference."""
import sys
import unittest
from pathlib import Path
from itertools import combinations, product
from fractions import Fraction as Q
sys.path.insert(0, str(Path(__file__).resolve().parent))
from bridge import (analytic, independent_raw_oracle, raw_population,
information_capacity, final_full)


class DelayedRevisionTests(unittest.TestCase):
def test_analytic_equals_raw_for_all_reachable_small_observations(self):
checked=0
for n in (2,3,4):
for j in range(1,n):
for slots in combinations(range(n),j):
for old in product((0,1),repeat=n):
for new in product((0,1),repeat=j):
for r in range(j+1):
prefix=tuple(old[i] for i in slots[:r])
a=analytic(n,slots,sum(old),new,prefix)
b=independent_raw_oracle(n,slots,sum(old),new,prefix)
self.assertEqual(a,b)
checked+=1
self.assertGreater(checked,200)

def test_full_reveal_and_variance_decomposition(self):
for n,slots in ((3,(1,)),(4,(0,2))):
rows=[raw_population(n,slots,r) for r in range(len(slots)+1)]
self.assertEqual(rows[-1]["regret"],Q(0))
for a,b in zip(rows,rows[1:]):
self.assertGreaterEqual(a["regret"],b["regret"])
self.assertEqual(a["mass"],Q(1))
self.assertEqual(b["mass"],Q(1))
self.assertGreater(rows[0]["regret"],0)

def test_full_input_requires_its_own_bayes_comparator(self):
n=4;slots=(0,);new=(0,)
old_a=(1,0,0,0);old_b=(0,1,0,0)
reduced_a=analytic(n,slots,sum(old_a),new,())
reduced_b=analytic(n,slots,sum(old_b),new,())
self.assertEqual(reduced_a,reduced_b)
self.assertNotEqual(final_full(n,old_a,slots,new),
final_full(n,old_b,slots,new))
row=raw_population(3,(1,),0)
full_input_excess=row["full_brier"]-row["limited_brier"]
self.assertEqual(full_input_excess,-row["regret"])
self.assertLess(full_input_excess,Q(0))

def test_exact_capacity_contract(self):
result=information_capacity(12,6)
self.assertEqual(result,{"histories":4096,
"initial_posterior_labels":13, "self_contained_bits":12,
"max_label_fiber":924, "extra_fixed_tag_bits":10,
"verified_old_sum_message_bits":3, "early_count_field_bits":4})
for args in ((12,0),(12,12),(13,6),(1,1)):
with self.assertRaises(ValueError):
information_capacity(*args)

def test_invalid_evidence_rejected(self):
for call in (lambda:analytic(4,(0,0),2,(1,0),()),
lambda:analytic(4,(1,),2,(3,),()),
lambda:analytic(4,(1,),2,(1,),(1,1)),
lambda:independent_raw_oracle(2,(0,),0,(1,),(1,))):
with self.assertRaises(ValueError):
call()


if __name__=="__main__":
unittest.main()

Loading