File size: 12,808 Bytes
6e46358
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
"""Certificate-guided exact two-circuit search; finite NumPy prototype.

Standard quadratic/Cauchy tools are used; no worldwide-priority claim.
Bounds are exact-arithmetic theorems; implementation adds numerical margins,
but is not an outward-rounded interval arithmetic verifier.
"""
from __future__ import annotations
import argparse,csv,hashlib,json,time
from pathlib import Path
import numpy as np
from scipy.linalg import qr

ROOT=Path(__file__).resolve().parent

def instance(seed,n,q,r,regime):
    rng=np.random.default_rng(np.random.SeedSequence([seed,n,q,r,{'low_rank':1,'full_rank':2,'suppressor':3}[regime]]));p=q+r
    B=rng.normal(size=(r,p));raw=rng.normal(size=(n,p))
    if regime=='low_rank':
        latent=rng.normal(size=(n,8));raw=latent@rng.normal(size=(8,p))/np.sqrt(8)+.0003*raw
    if regime=='suppressor':
        # The informative difference is weak as two individual directions.
        common=rng.normal(size=n);signal=rng.normal(size=n)
        raw[:,r]=common+.03*signal;raw[:,r+1]=common-.03*signal
    start=time.perf_counter_ns()
    piv=qr(B,pivoting=True,mode='economic')[2][:r] if regime!='suppressor' else np.arange(r)
    non=np.array([j for j in range(p) if j not in set(piv)],int)
    T=np.linalg.solve(B[:,piv],B[:,non]);U=raw[:,non]-raw[:,piv]@T
    Q=np.eye(q)+T.T@T
    setup=(time.perf_counter_ns()-start)/1e9
    if regime=='suppressor':
        # Make the innovation pair retain the designed cancellation. Raw pivot
        # features are zero only in the new-task domain, not in anchors.
        raw[:,piv]=0.;U=raw[:,non].copy();y=signal+.02*rng.normal(size=n)
    else:
        coef=rng.normal(size=q);coef/=np.linalg.norm(coef);y=U@coef+.05*rng.normal(size=n)
    return dict(U=U,y=y,Q=Q,setup_seconds=setup,p=p,q=q,r=r,n=n,regime=regime,seed=seed)

def exact_scores(K,h):
    a=np.diag(K);det=a[:,None]*a[None,:]-K*K
    numer=a[None,:]*h[:,None]**2+a[:,None]*h[None,:]**2-2*K*h[:,None]*h[None,:]
    with np.errstate(divide='ignore',invalid='ignore'):G=.5*numer/det
    G=np.where(np.triu(np.ones(K.shape,dtype=bool),1),G,-np.inf)
    return G

def pair_value(cross,i,j,diag,h):
    det=diag[i]*diag[j]-cross*cross
    if det<=0:return float('inf')
    return float(.5*(diag[j]*h[i]**2+diag[i]*h[j]**2-2*cross*h[i]*h[j])/det)

def choose(values):
    # Consistent finite-precision tie policy for the exact output.
    m=np.max(values);inds=np.flatnonzero(values>=m-1e-10*(1+abs(m)))
    return np.unravel_index(inds[0],values.shape),float(m)

def dense(task,reg=1e-4):
    U,y,Q=task['U'],task['y'],task['Q'];start=time.perf_counter_ns();n,q=U.shape
    h=U.T@y/n;K=U.T@U/n+reg*Q;G=exact_scores(K,h);pair,gain=choose(G)
    seconds=(time.perf_counter_ns()-start)/1e9
    return dict(method='dense_all_pairs',seconds=seconds,end_to_end_seconds=seconds+task['setup_seconds'],pair=list(map(int,pair)),gain=gain,exact_cross_queries=q*(q-1)//2,landmarks=0,bound_rounds=0,certified=True,fallback=False)

def screened(task,rule='gain',reg=1e-4,max_landmarks=16,queries_per_round=2):
    U,y,Q=task['U'],task['y'],task['Q'];start=time.perf_counter_ns();n,q=U.shape
    h=U.T@y/n;d=np.einsum('ij,ij->j',U,U)/n;diag=d+reg*np.diag(Q);yy=float(y@y/n)
    # Include the response as a landmark. A response vector is an observed
    # training input, never a validation/test outcome used to tune this rule.
    v=y/max(np.linalg.norm(y),1e-300);orth=[v]
    L=[v@U/np.sqrt(n)];known=np.zeros((q,q),bool);observed=np.full((q,q),-np.inf)
    best=-np.inf;bestpair=None;queries=0;rounds=0;certified=False;fallback=False
    floor_upper=exact_scores(reg*Q,h)
    mask=np.triu(np.ones((q,q),bool),1)
    for step in range(max_landmarks+1):
        LP=np.array(L);center=LP.T@LP;remaining=np.maximum(d-np.sum(LP*LP,axis=0),0)
        # Inflate the Cauchy envelope instead of treating numerical projections
        # as exact. This is a tested margin, not a rigorous rounding proof.
        padding=2e-10*(1+np.max(d));remaining+=padding
        radius=np.sqrt(remaining[:,None]*remaining[None,:]);lo=reg*Q+center-radius;hi=reg*Q+center+radius
        def upper_at(x):
            det=diag[:,None]*diag[None,:]-x*x
            num=diag[None,:]*h[:,None]**2+diag[:,None]*h[None,:]**2-2*x*h[:,None]*h[None,:]
            with np.errstate(divide='ignore',invalid='ignore'):g=.5*num/det
            return np.where(det>1e-24,g,np.inf)
        ub=np.minimum(np.maximum(upper_at(lo),upper_at(hi)),floor_upper)
        ub=np.minimum(ub,yy/2)
        ub=np.where(mask,ub,0.);ub+=1e-9*(1+np.abs(ub));ub=np.where(mask&~known,ub,-np.inf);rounds+=1
        for _ in range(queries_per_round):
            if np.max(ub)<=best-1e-10*(1+abs(best)):
                certified=True;break
            ij=np.unravel_index(np.argmax(ub),ub.shape);i,j=map(int,ij)
            if not np.isfinite(ub[i,j]):break
            cross=float(U[:,i]@U[:,j]/n+reg*Q[i,j]);g=pair_value(cross,i,j,diag,h)
            known[i,j]=True;observed[i,j]=g;ub[i,j]=-np.inf;queries+=1
            if g>best+1e-10*(1+abs(best)) or bestpair is None or (abs(g-best)<=1e-10*(1+abs(best)) and (i,j)<bestpair):best=g;bestpair=(i,j)
        if certified:break
        if np.max(ub)<=best-1e-10*(1+abs(best)):
            certified=True;break
        if step==max_landmarks:break
        if rule=='gain':
            i,j=np.unravel_index(np.argmax(ub),ub.shape);candidates=[int(i),int(j)];idx=max(candidates,key=lambda k:remaining[k])
        elif rule=='variance':idx=int(np.argmax(remaining))
        else:
            rng=np.random.default_rng(task['seed']+step+438);idx=int(rng.choice(np.flatnonzero(remaining>padding*2))) if np.any(remaining>padding*2) else int(np.argmax(remaining))
        z=U[:,idx].copy()
        # Reorthogonalize to reduce cancellation in nearly rank-deficient data.
        for _ in range(2):
            for vv in orth:z-=vv*(vv@z)
        norm=np.linalg.norm(z)
        if norm<1e-12*np.sqrt(max(d[idx],1.)*n):break
        z/=norm;orth.append(z);L.append(z@U/np.sqrt(n))
    if not certified:
        # An explicit fallback bounds how many scalar queries are issued before
        # using the strongest dense BLAS path. Its cost remains fully counted.
        K=U.T@U/n+reg*Q;G=exact_scores(K,h);pair,best=choose(G);bestpair=tuple(map(int,pair));queries+=q*(q-1)//2;fallback=True
    seconds=(time.perf_counter_ns()-start)/1e9
    return dict(method='screen_'+rule,seconds=seconds,end_to_end_seconds=seconds+task['setup_seconds'],pair=list(bestpair),gain=best,exact_cross_queries=queries,landmarks=len(L),bound_rounds=rounds,certified=certified,fallback=fallback)

def batched(task,adaptive=True,reg=1e-4):
    """Observable pilot chooses a dense or batched projection backend.

    It is a repair of repeated scalar bookkeeping, not a new nullspace solver.
    A final dense fallback preserves the candidate family and best gain.
    """
    U,y,Q=task['U'],task['y'],task['Q'];start=time.perf_counter_ns();n,q=U.shape
    h=U.T@y/n;d=np.einsum('ij,ij->j',U,U)/n;diag=d+reg*np.diag(Q);yy=float(y@y/n)
    pilot=U[np.linspace(0,n-1,min(48,n),dtype=int)]
    _,R,piv=qr(pilot,pivoting=True,mode='economic');sv=np.abs(np.diag(R));rank=int(np.sum(sv>max(sv[0],1e-12)*.003))
    fallback=False;queries=0;landmarks=0;rounds=0;certified=False
    if not adaptive or rank<=16:
        k=min(max(rank,2),16) if adaptive else min(8,q)
        # One matrix-matrix product replaces many scalar projection passes.
        Z=np.column_stack([y,U[:,piv[:k]]]);V=np.linalg.qr(Z,mode='reduced')[0]
        L=V.T@U/np.sqrt(n);landmarks=L.shape[0];center=L.T@L
        rem=np.maximum(d-np.einsum('ij,ij->j',L,L),0)+2e-10*(1+np.max(d));rad=np.sqrt(rem[:,None]*rem[None,:])
        def at(cross):
            det=diag[:,None]*diag[None,:]-cross*cross
            num=diag[None,:]*h[:,None]**2+diag[:,None]*h[None,:]**2-2*cross*h[:,None]*h[None,:]
            with np.errstate(divide='ignore',invalid='ignore'):v=.5*num/det
            return np.where(det>1e-24,v,np.inf)
        ub=np.maximum(at(reg*Q+center-rad),at(reg*Q+center+rad));ub=np.minimum(ub,exact_scores(reg*Q,h));ub=np.minimum(ub,yy/2)
        mask=np.triu(np.ones((q,q),bool),1);ub=np.where(mask,ub,0.);ub+=1e-9*(1+abs(ub));ub=np.where(mask,ub,-np.inf);rounds=1
        best=-np.inf;bestpair=None
        # Only a small number of expensive exact dots before strong fallback.
        for _ in range(16):
            if np.max(ub)<=best-1e-10*(1+abs(best)):
                certified=True;break
            i,j=map(int,np.unravel_index(np.argmax(ub),ub.shape));cross=float(U[:,i]@U[:,j]/n+reg*Q[i,j]);gain=pair_value(cross,i,j,diag,h);ub[i,j]=-np.inf;queries+=1
            if bestpair is None or gain>best+1e-10*(1+abs(best)):best=gain;bestpair=(i,j)
        if np.max(ub)<=best-1e-10*(1+abs(best)):certified=True
    if not certified:
        K=U.T@U/n+reg*Q;G=exact_scores(K,h);bestpair,best=choose(G);fallback=True;queries+=q*(q-1)//2
    sec=(time.perf_counter_ns()-start)/1e9
    return dict(method='pilot_batch' if adaptive else 'fixed_batch8',seconds=sec,end_to_end_seconds=sec+task['setup_seconds'],pair=list(map(int,bestpair)),gain=float(best),exact_cross_queries=queries,landmarks=landmarks,bound_rounds=rounds,certified=certified,fallback=fallback)

def test_bounds():
    rng=np.random.default_rng(611);checks=0;excess=0.
    for _ in range(60):
        U=rng.normal(size=(30,9));y=rng.normal(size=30);W=rng.normal(size=(2,9));Q=np.eye(9)+W.T@W
        reg=.03;h=U.T@y/len(y);d=np.mean(U*U,axis=0);diag=d+reg*np.diag(Q)
        V=np.linalg.qr(np.column_stack([y,U[:,:3]]))[0];L=V.T@U/np.sqrt(len(y));cen=L.T@L;rem=np.maximum(d-np.sum(L*L,axis=0),0)
        K=U.T@U/len(y)+reg*Q;actual=exact_scores(K,h)
        for i in range(9):
            for j in range(i+1,9):
                radius=np.sqrt(rem[i]*rem[j]);bounds=[pair_value(reg*Q[i,j]+cen[i,j]+s*radius,i,j,diag,h) for s in [-1,1]]
                gap=actual[i,j]-max(bounds);excess=max(excess,gap);assert gap<=1e-9;checks+=1
    return dict(pair_bound_checks=checks,max_bound_excess=excess)

def run(out,seeds=8,phase='explore'):
    out.mkdir(parents=True,exist_ok=True)
    configs=[(1024,128,2,'low_rank'),(1024,128,2,'full_rank'),(2048,512,4,'low_rank'),(2048,512,4,'full_rank'),(2048,512,4,'suppressor'),(8192,512,4,'low_rank')]
    rows=[];rng=np.random.default_rng(99101)
    for seed in range(seeds):
        for n,q,r,regime in configs:
            task=instance(seed+(100000 if phase=='confirm' else 0),n,q,r,regime)
            results=[]
            for method in rng.permutation(['dense','gain','variance','random','pilot_batch','fixed_batch8']):
                a=dense(task) if method=='dense' else batched(task,method=='pilot_batch') if method in ('pilot_batch','fixed_batch8') else screened(task,method)
                a.update(seed=seed,n=n,q=q,r=r,regime=regime,phase=phase);results.append(a)
            reference=next(r for r in results if r['method']=='dense_all_pairs')
            for a in results:
                a['gain_error']=abs(a['gain']-reference['gain']);a['same_pair']=a['pair']==reference['pair'];a['gain_match']=a['gain_error']<=1e-8*(1+reference['gain']);rows.append(a)
    with (out/'rows.csv').open('w') as f:
        writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)
    summ=[]
    for n,q,r,regime in configs:
        for method in ['dense_all_pairs','screen_gain','screen_variance','screen_random','pilot_batch','fixed_batch8']:
            rs=[x for x in rows if x['n']==n and x['q']==q and x['regime']==regime and x['method']==method]
            summ.append(dict(n=n,q=q,r=r,regime=regime,method=method,seeds=len(rs),mean_seconds=float(np.mean([x['seconds'] for x in rs])),mean_end_to_end_seconds=float(np.mean([x['end_to_end_seconds'] for x in rs])),mean_queries=float(np.mean([x['exact_cross_queries'] for x in rs])),mean_landmarks=float(np.mean([x['landmarks'] for x in rs])),certified_fraction=float(np.mean([x['certified'] for x in rs])),fallback_fraction=float(np.mean([x['fallback'] for x in rs])),gain_mismatches=sum(not x['gain_match'] for x in rs)))
    report=dict(phase=phase,seeds=seeds,summary=summ,checks=test_bounds(),scope='Exact two-circuit winner discovery conditional on finite arithmetic margins; uses standard Cauchy/convexity tools. Complete compound-packet space restricted to pairs of supplied fundamental circuits. Strong dense and variance-landmark controls included; feature/circuit setup charged separately.')
    (out/'summary.json').write_text(json.dumps(report,indent=2));print(json.dumps(report,indent=2))

if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--out',type=Path,default=ROOT/'exploratory');p.add_argument('--seeds',type=int,default=4);p.add_argument('--phase',default='explore');a=p.parse_args();run(a.out,a.seeds,a.phase)