File size: 11,595 Bytes
973efa6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
#!/usr/bin/env python3
"""Standalone certified return-compression experiments for ELYSIAEN.

NumPy/SciPy/Matplotlib only. No earlier project module is imported. The full
return matrix is retained by the independent oracle, never by CompressedReturn.
Arithmetic work models are counts, not CPU/GPU or photonic benchmarks.
"""
from __future__ import annotations
import os
os.environ.setdefault('OPENBLAS_NUM_THREADS', '1')
os.environ.setdefault('OMP_NUM_THREADS', '1')
from dataclasses import dataclass
from pathlib import Path
import argparse
import json
import platform
import numpy as np
import scipy
from scipy.linalg import solve


@dataclass(frozen=True)
class CompressedReturn:
    U: np.ndarray
    V: np.ndarray
    weight: np.ndarray
    return_on_weight: np.ndarray
    delta: float


def weighted_inf(x, weight):
    return float(np.max(np.abs(x)/weight, initial=0.0))


def compile_return(C, U, V, weight):
    """Oracle/offline compilation; measured deployment needs valid envelopes."""
    a=np.asarray(weight, dtype=float)
    if np.any(a<=0) or np.min(C, initial=0)<0:
        raise ValueError('Expected positive weights and nonnegative true return')
    E=np.abs(C-U@V)
    delta=weighted_inf(E@a,a)
    arrays=[np.array(z,copy=True) for z in (U,V,a,C@a)]
    for z in arrays: z.setflags(write=False)
    return CompressedReturn(*arrays,delta)


def evaluate_diagonal(capsule, bdiag, ldiag, rdiag, f):
    """Only compressed arrays; no true/dense return or full-state callback.

    This optimized path assumes diagonal B,L,R. The true A is admitted by a
    positive witness derived from a and C a. Any error certificate is ordinary
    floating-point evaluation of an exact inequality, not outward rounding.
    """
    U,V,a,c,delta=(capsule.U,capsule.V,capsule.weight,
                   capsule.return_on_weight,capsule.delta)
    b,l,r=map(np.asarray,(bdiag,ldiag,rdiag))
    if any(np.min(z,initial=0)<0 for z in (b,l,r)) or np.any(b>=1):
        raise ValueError('Nonnegative diagonal maps and I-B invertible required')
    tR=weighted_inf(r*a,a)
    slack=a-b*a-tR*l*c
    if np.min(slack)<=0:
        raise ValueError('The retained true-class stability witness fails')
    P=(l/(1-b))[:,None]*U
    T=V*r[None,:]
    q=f/(1-b)
    K=np.eye(V.shape[0])-T@P
    z=solve(K,T@q,assume_a='gen',check_finite=True)
    u=q+P@z
    residual=(1-b)*u-l*(U@(V@(r*u)))-f
    forcing=np.abs(residual)+delta*weighted_inf(r*u,a)*l*a
    beta=float(np.max(forcing/slack, initial=0.0))
    return u,beta,{'small_rank':V.shape[0], 'true_weighted_slack_min':float(np.min(slack/a)),
                   'small_condition_2':float(np.linalg.cond(K)),
                   'retained_array_bytes':sum(z.nbytes for z in (U,V,a,c))}


def positive_world(k,rng):
    q=10
    u=rng.uniform(.2,1.2,(k,q))
    v=rng.uniform(.2,1.2,(q,k))
    u/=u.sum(axis=0,keepdims=True)
    v/=v.sum(axis=1,keepdims=True)
    decay=.55**np.arange(q)
    u*=decay[None,:]
    # The positive diagonal tail makes the return full rank. Compressibility
    # is a stipulated generated property, not inferred for arbitrary scenes.
    U0=np.column_stack((u,.001*np.eye(k)))
    V0=np.vstack((v,np.eye(k)))
    C0=U0@V0
    scale=.60/np.max(C0.sum(axis=1))
    U0*=scale
    a=np.exp(rng.uniform(-1.5,1.5,k))
    U=a[:,None]*U0
    V=V0/a[None,:]
    return U@V,U,V,a


def signed_svd_control(rng):
    # Search a fixed seeded family for the well-known fact that truncating an
    # asymmetric nonnormal stable positive operator need not preserve stability.
    for attempt in range(1500):
        k=5
        C0=rng.uniform(0,1,(k,k))
        C0*=.85/max(abs(np.linalg.eigvals(C0)))
        w=np.exp(rng.uniform(-7,7,k))
        C=w[:,None]*C0/w[None,:]
        uu,ss,vv=np.linalg.svd(C,full_matrices=False)
        for rank in (2,3):
            Cr=(uu[:,:rank]*ss[:rank])@vv[:rank]
            rho=float(max(abs(np.linalg.eigvals(Cr))))
            if rho>1.02 and np.min(Cr)<-1e-7:
                return {'found':True,'attempt':attempt,'rank':rank,
                        'true_spectral_radius':float(max(abs(np.linalg.eigvals(C)))),
                        'truncated_spectral_radius':rho,'minimum_truncated_entry':float(Cr.min()),
                        'C':C.tolist(),'C_rank':Cr.tolist(),
                        'meaning':'SVD rank truncation can destroy positivity and stability; certificate uses true class.'}
    return {'found':False,'meaning':'No such counterexample found in this finite search; no preservation claim follows.'}


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--quick',action='store_true')
    parser.add_argument('--output-prefix',default='v5_compression')
    args=parser.parse_args()
    rng=np.random.default_rng(2026102551)
    count=12 if args.quick else 60
    records=[]; max_reconstruction=0.; max_ratio=0.; violations=0
    monotone_checks=0; monotone_violations=0; signed_checks=0
    frontier=[]
    for case in range(count):
        k=(16,32,64)[case%3]
        C,U,V,a=positive_world(k,rng)
        b=rng.uniform(0,.14,k); l=rng.uniform(.25,1,k); r=rng.uniform(.25,1,k)
        f=a*rng.uniform(.1,1,k)
        O=rng.uniform(0,1,(3,k))/a[None,:]/k
        A=np.diag(b)+l[:,None]*C*r[None,:]
        exact=solve(np.eye(k)-A,f)
        ranks=(1,2,4,8,10,k+10)
        previous=None
        for rank in ranks:
            cap=compile_return(C,U[:,:rank],V[:rank],a)
            approx,beta,info=evaluate_diagonal(cap,b,l,r,f)
            approx_direct=solve(np.eye(k)-np.diag(b)-l[:,None]*(cap.U@cap.V)*r[None,:],f)
            max_reconstruction=max(max_reconstruction,weighted_inf(approx-approx_direct,a))
            err=weighted_inf(exact-approx,a)
            out_err=np.abs(O@(exact-approx)); out_bound=(np.abs(O)@a)*beta
            if err>beta+2e-10 or np.any(out_err>out_bound+2e-10): violations+=1
            if beta>1e-13: max_ratio=max(max_ratio,err/beta)
            if previous is not None:
                monotone_checks+=1
                if np.min(approx-previous)<-2e-10: monotone_violations+=1
            previous=approx
            rec={'case':case,'k':k,'factor_count':rank,'error':err,'certificate':beta,
                 'relative_return_envelope':cap.delta,**info}
            records.append(rec)
            if case==1: frontier.append(rec)
        # Signed SVD factors use the very same true-class compression barrier.
        uu,ss,vv=np.linalg.svd(C,full_matrices=False)
        for rank in (2,5,min(10,k)):
            cap=compile_return(C,uu[:,:rank]*ss[:rank],vv[:rank],a)
            approx,beta,_=evaluate_diagonal(cap,b,l,r,f)
            if weighted_inf(exact-approx,a)>beta+2e-10: violations+=1
            signed_checks+=1
    assert violations==0 and monotone_violations==0
    near=[]
    for eps in np.logspace(-1,-6,20):
        delta=1e-4
        exact=1/eps; approx=1/(eps+delta)
        actual=abs(exact-approx)
        certificate=delta*approx/eps
        assert actual<=certificate+1e-5*max(1,actual)
        near.append({'epsilon':float(eps),'return_error':delta,'actual_state_error':actual,
                     'certificate':certificate})
    work=[]
    for k in (32,64,128,256):
        dense=2*k**3/3+2*k*k
        for rank in (1,2,4,8,12):
            # One dense r-core factorization per local configuration and one RHS.
            low=2*k*rank**2+2*rank**3/3+8*k*rank+2*rank**2+12*k
            work.append({'k':k,'rank':rank,'dense_digital_model_flops':dense,
                         'compressed_digital_model_flops':low,'modeled_ratio':dense/low})
    signed_control=signed_svd_control(rng)
    assert signed_control['found'], 'Seeded signed-SVD negative control was not reproduced'
    # Simple exact impossibility control: any deficient-rank Cr has a kernel.
    gamma=.6; k=8
    Cr=np.zeros((k,k));Cr[:3,:3]=gamma*np.eye(3)
    z=np.zeros(k);z[-1]=1
    lower_bound_error=float(np.linalg.norm(z/(1-gamma)-solve(np.eye(k)-Cr,z)))
    assert abs(lower_bound_error-gamma/(1-gamma))<1e-12
    result={'project':'ELYSIAEN certified return compression','date':'2026-10-25',
            'seed':2026102551,'software':{'Python':platform.python_version(),'NumPy':np.__version__,'SciPy':scipy.__version__},
            'random_capsules':count,'positive_prefix_candidate_checks':len(records),
            'signed_svd_candidate_checks':signed_checks,'certificate_violations':violations,
            'monotone_prefix_checks':monotone_checks,'monotone_prefix_violations':monotone_violations,
            'maximum_small_solve_reconstruction_error':max_reconstruction,
            'maximum_actual_error_to_certificate_ratio':max_ratio,
            'retained_contract':'U,V,a,Ca,delta only; no dense true return in evaluate_diagonal',
            'signed_svd_negative_control':signed_control,
            'full_rank_negative_control':{'gamma':gamma,'k':k,'rank':3,'observed_error':lower_bound_error,'lower_bound':gamma/(1-gamma)},
            'rank_frontier':frontier,'near_critical':near,'digital_work_model':work,'records':records,
            'scope':'Finite arithmetic identities, stated diagonal local maps, generated compressibility and oracle-derived offline envelopes. Flop models are not measured timing/energy or photonic speedups. Ordinary double precision, not outward-rounded certificates.'}
    path=Path(args.output_prefix);path.parent.mkdir(parents=True,exist_ok=True)
    path.with_name(path.name+'_results.json').write_text(json.dumps(result,indent=2)+'\n')
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    plt.rcParams.update({'font.size':11,'axes.spines.top':False,'axes.spines.right':False})
    fig,axes=plt.subplots(1,2,figsize=(9,4.2),constrained_layout=True)
    # Plot practical nonexact prefixes. Exact reconstruction reaches ordinary
    # floating-point noise, not an outward-rounded certificate floor.
    shown=[x for x in frontier if x['factor_count']<=10]
    ranks=[x['factor_count'] for x in shown]
    axes[0].semilogy(ranks,[x['error'] for x in shown],'o-',label='Actual state error')
    axes[0].semilogy(ranks,[x['certificate'] for x in shown],'s--',label='Certified barrier')
    axes[0].set(xlabel='Retained positive factors',ylabel='Weighted infinity error',title='Compression versus accuracy');axes[0].legend()
    axes[1].loglog([x['epsilon'] for x in near],[x['actual_state_error'] for x in near],'o-',label='Actual = barrier')
    axes[1].invert_xaxis();axes[1].set(xlabel='True feedback slack',ylabel='State error for return error 10⁻⁴',title='Near-unit return remains sensitive')
    for ax in axes: ax.grid(alpha=.2)
    fig.suptitle('Finite generated transport; no hardware measurements',fontsize=12)
    fig.savefig(path.with_suffix('.png'),dpi=170);plt.close(fig)
    fig,ax=plt.subplots(figsize=(8,3.4),constrained_layout=True)
    for rank in (2,4,8,12):
        rr=[x for x in work if x['rank']==rank]
        ax.plot([x['k'] for x in rr],[x['modeled_ratio'] for x in rr],'o-',label=f'r={rank}')
    ax.axhline(1,color='gray',lw=.7);ax.set(xlabel='Capsule dimension k',ylabel='Dense / compressed work model',title='Same algorithm, digital baseline');ax.legend();ax.grid(alpha=.2)
    fig.savefig(path.with_name(path.name+'_work').with_suffix('.png'),dpi=170);plt.close(fig)
    print(json.dumps({k:result[k] for k in ['random_capsules','positive_prefix_candidate_checks','signed_svd_candidate_checks','certificate_violations','monotone_prefix_checks','maximum_small_solve_reconstruction_error','maximum_actual_error_to_certificate_ratio']},indent=2))


if __name__=='__main__': main()