Celestis-RL / src /celestis_rl /sequential_audit.py
PureOne's picture
Release Celestis-RL v2.0.0: audited research reference
f95cbd4 verified
Raw History Blame Contribute Delete
9.43 kB
"""Sequential, multi-metric, bounded paired evaluation.
Uses established empirical-Bernstein and Hoeffding bounds with explicit
union-bound spending across proposals, registered looks, metrics and bounds.
Proposal/environment/distribution must remain fixed during its evaluation.
No choice of statistical test can certify unmeasured qualities.
"""
from dataclasses import dataclass,asdict
import json
import math
from pathlib import Path
import numpy as np
from .certificates import ConfidenceLedger
@dataclass(frozen=True)
class MetricSpec:
name: str
minimum: float = 0.
maximum: float = 1.
direction: int = 1
min_gain: float = 0.
penalty: float = 0.
def __post_init__(self):
if not isinstance(self.name,str) or not self.name.strip():raise ValueError('metric name required')
if not all(math.isfinite(x) for x in (self.minimum,self.maximum,self.min_gain,self.penalty)):
raise ValueError('metric constants must be finite')
if self.maximum<=self.minimum or self.penalty<0 or isinstance(self.direction,bool) or self.direction not in (-1,1):
raise ValueError('invalid bounds, direction or penalty')
@dataclass(frozen=True)
class ParetoAuditResult:
accepted: bool
n_pairs: int
look: int
lower_gain_bounds: dict
empirical_gains: dict
radii: dict
active_bounds: dict
attempt_delta: float
look_delta: float
candidate_id: str
status: str
scope: str='registered metrics only; fresh IID pairs, fixed proposal and known bounds'
def confidence_radius(n: int,variance: float,width: float,delta: float,method: str='hybrid') -> tuple[float,str]:
"""width is the known range width of signed paired DIFFERENCES.
A pair of returns each in [a,b] gives difference width 2*(b-a),
not (b-a). Hybrid allocates delta/2 to each candidate inequality.
"""
if isinstance(n,bool) or not isinstance(n,int) or n<2:raise ValueError('n>=2 required')
if not all(math.isfinite(x) for x in (variance,width,delta)) or variance<0 or width<=0 or not 0<delta<1:
raise ValueError('invalid variance/range/delta')
if method not in ('hybrid','hoeffding','bernstein'):raise ValueError('unknown confidence method')
d=delta/2 if method=='hybrid' else delta
h=width*math.sqrt(math.log(1/d)/(2*n))
l=math.log(2/d)
eb=math.sqrt(2*variance*l/n)+7*width*l/(3*(n-1))
if method=='hoeffding':return h,'hoeffding'
if method=='bernstein':return eb,'bernstein'
return (eb,'bernstein') if eb<h else (h,'hoeffding')
class SequentialParetoAudit:
"""Single-proposal evaluator with O(number of metrics) retained statistics.
Register sample sizes before outcomes; each fresh pair is consumed once.
Calling add() with differently partitioned batches gives identical looks.
The global confidence ledger MUST survive model rollback and restart.
Passing ledger_path persists its reservation immediately. Single process;
concurrent writers need an external transactional/locking mechanism.
"""
def __init__(self,metrics,ledger: ConfidenceLedger,*,candidate_id: str,
looks=(32,64,128,256,512,1024,2048,4096,8192,16384),
method='hybrid',ledger_path: str | Path | None=None):
self.metrics=tuple(metrics);self.looks=tuple(looks);self.method=method
if not self.metrics or not all(isinstance(s,MetricSpec) for s in self.metrics):raise ValueError('MetricSpec sequence required')
if len({s.name for s in self.metrics})!=len(self.metrics):raise ValueError('duplicate metric names')
if not self.looks or any(isinstance(n,bool) or not isinstance(n,int) or n<2 for n in self.looks) or any(b<=a for a,b in zip(self.looks,self.looks[1:])):
raise ValueError('register strictly increasing integer looks >=2')
if method not in ('hybrid','hoeffding','bernstein'):raise ValueError('invalid confidence method')
if not isinstance(candidate_id,str) or not candidate_id.strip():raise ValueError('fixed candidate ID required')
self.candidate_id=candidate_id
self.n=0;self.look_index=0
self.mean=np.zeros(len(self.metrics));self.m2=np.zeros(len(self.metrics))
self.result=None;self.attempt_delta=ledger.spend()
if ledger_path is not None:ledger.save(ledger_path)
@property
def finished(self):return bool(self.result is not None and self.result.accepted) or self.look_index>=len(self.looks)
def _look(self):
j=self.look_index+1
alpha=self.attempt_delta*6/(math.pi**2*j*j)
lower={};radii={};bounds={};empirical={}
for k,spec in enumerate(self.metrics):
radius,bound=confidence_radius(self.n,max(0.,float(self.m2[k]/(self.n-1))),
2*(spec.maximum-spec.minimum),alpha/len(self.metrics),self.method)
lower[spec.name]=float(self.mean[k]-radius-spec.penalty)
radii[spec.name]=radius;bounds[spec.name]=bound;empirical[spec.name]=float(self.mean[k])
accept=all(lower[s.name]>=s.min_gain for s in self.metrics)
status='certified_registered_margins' if accept else ('inconclusive_budget_exhausted' if j==len(self.looks) else 'continue')
self.result=ParetoAuditResult(bool(accept),self.n,j,lower,empirical,radii,bounds,
self.attempt_delta,alpha,self.candidate_id,status)
self.look_index+=1
def add(self,candidate,baseline,*,candidate_id: str) -> ParetoAuditResult | None:
if candidate_id!=self.candidate_id:raise ValueError('proposal changed during evaluation')
if self.finished:raise RuntimeError('audit already finished')
c=np.asarray(candidate,dtype=np.float64);b=np.asarray(baseline,dtype=np.float64)
if c.ndim==1 and len(self.metrics)==1:c=c[:,None]
if b.ndim==1 and len(self.metrics)==1:b=b[:,None]
if c.ndim!=2 or c.shape!=b.shape or c.shape[1]!=len(self.metrics) or len(c)<1:
raise ValueError('paired outcomes [N,metrics] required')
if not np.isfinite(c).all() or not np.isfinite(b).all():raise ValueError('nonfinite outcome')
for k,s in enumerate(self.metrics):
if (c[:,k]<s.minimum).any() or (c[:,k]>s.maximum).any() or (b[:,k]<s.minimum).any() or (b[:,k]>s.maximum).any():
raise ValueError('outcome outside declared bounds')
diff=(c-b)*np.array([s.direction for s in self.metrics])
offset=0
# Aggregate chunks with parallel Welford, stopping at each registered look.
while offset<len(diff) and not self.finished:
take=min(len(diff)-offset,self.looks[self.look_index]-self.n)
batch=diff[offset:offset+take];mean=batch.mean(0)
m2=((batch-mean)**2).sum(0);delta=mean-self.mean;total=self.n+take
self.m2+=m2+delta*delta*self.n*take/total
self.mean+=delta*take/total;self.n=total;offset+=take
if self.n==self.looks[self.look_index]:self._look()
return self.result
def save(self,path: str | Path):
data={'schema':'celestis-sequential-audit-v1','metrics':[asdict(s) for s in self.metrics],
'looks':self.looks,'method':self.method,'candidate_id':self.candidate_id,
'n':self.n,'look_index':self.look_index,'mean':self.mean.tolist(),'m2':self.m2.tolist(),
'attempt_delta':self.attempt_delta,'result':None if self.result is None else asdict(self.result)}
p=Path(path);p.parent.mkdir(parents=True,exist_ok=True);tmp=p.with_suffix(p.suffix+'.tmp')
tmp.write_text(json.dumps(data,indent=2,allow_nan=False)+'\n',encoding='utf-8');tmp.replace(p)
@classmethod
def load(cls,path: str | Path):
"""Resume one audit; never rewind/reuse consumed evidence or confidence."""
data=json.loads(Path(path).read_text(encoding='utf-8'))
if data.get('schema')!='celestis-sequential-audit-v1':raise ValueError('unknown audit schema')
# Validate configuration without consuming a real confidence ledger.
obj=cls([MetricSpec(**s) for s in data['metrics']],ConfidenceLedger(),
candidate_id=data['candidate_id'],looks=data['looks'],method=data['method'])
n=data['n'];i=data['look_index'];d=data['attempt_delta']
if isinstance(n,bool) or not isinstance(n,int) or n<0 or n>obj.looks[-1] or isinstance(i,bool) or not isinstance(i,int) or not 0<=i<=len(obj.looks):
raise ValueError('invalid persisted sample counts')
if i!=sum(n>=v for v in obj.looks) or not math.isfinite(d) or not 0<d<1:
raise ValueError('invalid persisted confidence state')
mean=np.asarray(data['mean'],dtype=float);m2=np.asarray(data['m2'],dtype=float)
if mean.shape!=(len(obj.metrics),) or m2.shape!=mean.shape or not np.isfinite(mean).all() or not np.isfinite(m2).all() or (m2<0).any():
raise ValueError('invalid persisted moments')
obj.n=n;obj.look_index=i;obj.mean=mean;obj.m2=m2;obj.attempt_delta=d
obj.result=None if data['result'] is None else ParetoAuditResult(**data['result'])
if (i==0)!=(obj.result is None):raise ValueError('missing/inconsistent result')
if obj.result is not None and (obj.result.look!=i or obj.result.n_pairs!=obj.looks[i-1] or obj.result.candidate_id!=obj.candidate_id):
raise ValueError('inconsistent persisted result')
return obj