File size: 17,407 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
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
"""Digital surrogate studies for Iyeumaring M7 and M8.

No measurements in this file are measurements of photonic/neuromorphic hardware.
Python elapsed times are host timings. Energy and accelerator latency are models.
Run: OPENBLAS_NUM_THREADS=1 python hardware_study.py --output .
"""
from __future__ import annotations

import argparse
from collections import deque
from dataclasses import dataclass, asdict
import json
from pathlib import Path
import platform
import time

import numpy as np


def ci(values, seed=941, samples=3000):
    a = np.asarray(values, float)
    rng = np.random.default_rng(seed)
    b = a[rng.integers(len(a), size=(samples, len(a)))].mean(axis=1)
    return {"mean": float(a.mean()), "median": float(np.median(a)),
            "mean_ci95": [float(x) for x in np.quantile(b, [.025, .975])]}


def quantize(x, bits, low=-1.0, high=1.0):
    levels = 2**bits - 1
    return np.round((np.clip(x, low, high)-low)/(high-low)*levels)/levels*(high-low)+low


def decompose_orthogonal(q):
    """Real Givens decomposition; rotations are an abstract interferometer mesh.

    Logical all-to-all Givens connectivity is used, not a fabricated chip layout.
    """
    a = np.asarray(q).copy()
    rotations = []
    n = a.shape[0]
    for j in range(n-1):
        for i in range(n-1, j, -1):
            theta = float(np.arctan2(a[i, j], a[j, j]))
            c, s = np.cos(theta), np.sin(theta)
            aj, ai = a[j].copy(), a[i].copy()
            a[j], a[i] = c*aj+s*ai, -s*aj+c*ai
            rotations.append((j, i, theta))
    return rotations, np.diag(a).copy()


def reconstruct_orthogonal(rotations, diagonal, phase_bits=None, drift_std=0., rng=None):
    a = np.diag(diagonal)
    for j, i, theta in reversed(rotations):
        if phase_bits is not None:
            theta = float(quantize(theta, phase_bits, -np.pi, np.pi))
        if drift_std:
            theta += rng.normal(0., drift_std)
        c, s = np.cos(theta), np.sin(theta)
        aj, ai = a[j].copy(), a[i].copy()
        a[j], a[i] = c*aj-s*ai, s*aj+c*ai
    return a


def photonic_surrogate(seeds=range(12), inputs=256, m=64, n=32):
    """Program W=U Sigma Vt, with angle/DAC/ADC quantization and readout noise."""
    rows = []
    for seed in seeds:
        rng = np.random.default_rng(50000+seed)
        w = rng.normal(size=(m,n))
        u, s, vt = np.linalg.svd(w, full_matrices=True)
        s /= s.max()
        sig = np.zeros((m,n)); sig[np.arange(n),np.arange(n)] = s
        w = u@sig@vt
        ru, du = decompose_orthogonal(u)
        rv, dv = decompose_orthogonal(vt)
        x = rng.normal(size=(n,inputs)); x /= np.linalg.norm(x,axis=0)
        exact = w@x
        exact_top = np.argmax(exact,axis=0)
        margin = np.sort(exact,axis=0)[-1]-np.sort(exact,axis=0)[-2]
        for bits, drift, read_std in [(6,.0005,.002),(8,.0005,.002),(10,.0005,.002),(8,.005,.01)]:
            # Independent hardware draw per configuration; seed replicates paired
            # digital data. Drift is fixed during a 256-vector calibration block.
            hrng = np.random.default_rng(100000+seed*100+bits+int(drift*1e6))
            uq = reconstruct_orthogonal(ru,du,bits,drift,hrng)
            vq = reconstruct_orthogonal(rv,dv,bits,drift,hrng)
            sq = quantize(s,8,0,1)
            sigq = np.zeros((m,n)); sigq[np.arange(n),np.arange(n)]=sq
            effective_w = uq@sigq@vq
            noisy = effective_w@quantize(x,8)
            # Signed homodyne amplitude readout, after calibrated loss compensation.
            noisy += hrng.normal(0,read_std,size=noisy.shape)
            adc_saturated_inputs = np.any(np.abs(noisy)>1.,axis=0)
            noisy = quantize(noisy,8)
            err = np.max(np.abs(noisy-exact),axis=0)
            top = np.argmax(noisy,axis=0)
            # A posteriori sufficient certificate, using known exact scores only
            # in this simulation. Real hardware requires a validated error bound.
            certified = margin > 2*err
            # Uniform probabilistic error certificate, assuming the effective
            # matrix has been calibrated exactly. This cannot use exact Wx.
            # DAC and ADC half-bin errors plus a Gaussian union-bound envelope.
            alpha = 1e-3
            matrix_error = np.linalg.norm(effective_w-w,axis=1)[:,None]*np.linalg.norm(x,axis=0)[None,:]
            dac_error = np.abs(effective_w).sum(axis=1)[:,None]/255
            noise_envelope = read_std*np.sqrt(2*np.log(2*m*inputs/alpha))
            bound = matrix_error+dac_error+noise_envelope+1/255
            upper = noisy+bound
            selected_lower = (noisy-bound)[top,np.arange(inputs)]
            upper[top,np.arange(inputs)] = -np.inf
            calibrated_certified = (selected_lower > upper.max(axis=0)) & ~adc_saturated_inputs
            order = np.argsort(noisy,axis=0)[-4:]
            top4 = np.any(order == exact_top[None,:],axis=0)
            rows.append({"seed":seed,"phase_bits":bits,"drift_std_rad":drift,
                         "readout_std_normalized":read_std,"top1_agreement":float(np.mean(top==exact_top)),
                         "top4_recall":float(np.mean(top4)),
                         "relative_rmse":float(np.linalg.norm(noisy-exact)/np.linalg.norm(exact)),
                         "certified_fraction":float(np.mean(certified)),
                         "certificate_errors":int(np.sum(certified&(top!=exact_top))),
                         "calibrated_certified_fraction":float(np.mean(calibrated_certified)),
                         "calibrated_certificate_errors":int(np.sum(calibrated_certified&(top!=exact_top))),
                         "adc_saturated_inputs":int(adc_saturated_inputs.sum()),
                         "median_score_gap":float(np.median(margin))})
    groups=[]
    for bits,drift,noise in [(6,.0005,.002),(8,.0005,.002),(10,.0005,.002),(8,.005,.01)]:
        sel=[r for r in rows if r['phase_bits']==bits and r['drift_std_rad']==drift]
        groups.append({"phase_bits":bits,"drift_std_rad":drift,"readout_std_normalized":noise,
                       **{k:ci([r[k] for r in sel]) for k in ['top1_agreement','top4_recall','relative_rmse','certified_fraction','calibrated_certified_fraction']},
                       "certificate_errors":sum(r['certificate_errors'] for r in sel),
                       "calibrated_certificate_errors":sum(r['calibrated_certificate_errors'] for r in sel)})
    return {"dimensions":[m,n],"inputs_per_seed":inputs,"seeds":list(seeds),
            "rows":rows,"summary":groups,
            "certificate_note":"certified_fraction uses exact-reference error and is only a posteriori. calibrated_certified_fraction uses matrix perturbation/DAC/ADC bounds and a Gaussian union bound alpha=0.001 per 256-input block, conditional on exact calibration of the effective matrix; real calibration uncertainty must be added."}


@dataclass
class CostAssumptions:
    digital_mac_per_second: float = 1e13
    digital_energy_per_mac_J: float = .5e-12
    digital_control_static_W: float = .5
    host_launch_s: float = 50e-9
    host_batch: int = 1024
    interface_s: float = 5e-9
    dac_s: float = 1e-9
    optical_propagation_s: float = .1e-9
    adc_s: float = 2e-9
    phase_program_s: float = 50e-6
    phase_program_energy_each_J: float = 1e-9
    calibration_s: float = 100e-6
    calibration_every_vectors: int = 100000
    calibration_energy_J: float = 10e-6
    dac_energy_each_J: float = 2e-12
    adc_energy_each_J: float = 5e-12
    io_energy_each_J: float = 2e-12
    memory_energy_each_J: float = 2e-12
    control_static_W: float = .5
    thermo_phase_static_each_W: float = .005
    low_static_phase_each_W: float = 1e-6
    photons_per_output: int = 100000
    wavelength_m: float = 1550e-9
    laser_wall_plug_efficiency: float = .2
    local_oscillator_multiplier: float = 10.
    fixed_loss_dB: float = 6.
    loss_per_mesh_stage_dB: float = .03
    memory_bandwidth_B_per_s: float = 512e9


def hardware_costs(a=CostAssumptions()):
    """Scenario calculation, NOT a hardware benchmark. All inputs explicit."""
    rows=[]
    for m,n in [(64,32),(128,128),(512,512)]:
        phases=(m*(m-1)+n*(n-1))//2
        loss_db=a.fixed_loss_dB+a.loss_per_mesh_stage_dB*(m+n)
        eta=10**(-loss_db/10)
        photon_energy=6.62607015e-34*299792458/a.wavelength_m
        laser=a.photons_per_output*m*photon_energy*a.local_oscillator_multiplier/(eta*a.laser_wall_plug_efficiency)
        for reuse in [100,10000,1000000]:
            launch=a.host_launch_s/a.host_batch
            memtime=2*(m*n/reuse+m+n)/a.memory_bandwidth_B_per_s
            td=launch+max(m*n/a.digital_mac_per_second,memtime)
            ed=(m*n*a.digital_energy_per_mac_J+m*n/reuse*a.memory_energy_each_J+
                (m+n)*a.io_energy_each_J+a.digital_control_static_W*td)
            for mode,perphase in [('thermo_optic',a.thermo_phase_static_each_W),('low_static_hypothesis',a.low_static_phase_each_W)]:
                po=a.control_static_W+phases*perphase
                to=(launch+a.interface_s+a.dac_s+a.optical_propagation_s+a.adc_s+
                    a.phase_program_s/reuse+a.calibration_s/a.calibration_every_vectors)
                eo=(laser+n*a.dac_energy_each_J+m*a.adc_energy_each_J+po*to+
                    phases*a.phase_program_energy_each_J/reuse+
                    a.calibration_energy_J/a.calibration_every_vectors+
                    (m+n)*a.io_energy_each_J)
                rows.append({"shape":[m,n],"weight_reuse":reuse,"phase_mode":mode,
                             "phase_count":phases,"loss_dB":loss_db,"static_power_W":po,
                             "within_50W_static_envelope":po<=50,
                             "digital_time_ns":td*1e9,"optical_time_ns":to*1e9,
                             "modeled_speed_ratio_digital_over_optical":td/to,
                             "digital_energy_nJ":ed*1e9,"optical_energy_nJ":eo*1e9,
                             "modeled_energy_ratio_digital_over_optical":ed/eo})
    return {"status":"analytical scenario; assumptions not measurements or vendor specifications",
            "assumptions":asdict(a),"rows":rows,
            "omissions":["routing-layout feasibility","fan-out and wavelength-specific crosstalk",
                         "laser relative-intensity noise spectral model","full chip heat transport",
                         "nonlinear activation and optimizer cost","hardware-specific host synchronization"],
            "loss_note":"Losses are scenario input, not a layout-extracted result. Effective loss is compensated in the ranking simulation; resulting readout noise is an independent normalized input."}


def delayed_data(seed,k,train=12000,test=3000,horizon=12,rho=.9):
    rng=np.random.default_rng(200000+seed)
    ids=rng.integers(k,size=train+test)
    amplitudes=rng.choice([-1.,1.],size=train+test)
    theta=rng.normal(size=k)
    rewards=np.zeros(train+test)
    hist=deque()
    for t,(idx,amp) in enumerate(zip(ids,amplitudes)):
        hist.append((t,int(idx),amp))
        if len(hist)>horizon:hist.popleft()
        rewards[t]=sum((rho**(t-ti))*v*theta[j] for ti,j,v in hist)+rng.normal(0,.1)
    return ids,amplitudes,rewards,theta,train


def dense_trace(ids,amplitudes,rewards,k,train,horizon=12,rho=.9,lr=.035):
    w=np.zeros(k);e=np.zeros(k);errors=[]
    start=time.perf_counter()
    for t,(idx,amp,reward) in enumerate(zip(ids,amplitudes,rewards)):
        e*=rho;e[idx]+=amp
        if t>=horizon:e[ids[t-horizon]]-=rho**horizon*amplitudes[t-horizon]
        delta=reward-w@e
        if t<train:w+=lr*delta*e
        else:errors.append(delta**2)
    return w,np.asarray(errors),time.perf_counter()-start


def sparse_trace(ids,amplitudes,rewards,k,train,horizon=12,rho=.9,lr=.035):
    w=np.zeros(k);e={};counts={};errors=[];max_active=0;active_sum=0
    start=time.perf_counter()
    for t,(idx,amp,reward) in enumerate(zip(ids,amplitudes,rewards)):
        idx=int(idx)
        for j in e:e[j]*=rho
        e[idx]=e.get(idx,0.)+amp;counts[idx]=counts.get(idx,0)+1
        if t>=horizon:
            old=int(ids[t-horizon]);counts[old]-=1
            if counts[old]==0:del e[old];del counts[old]
            else:e[old]-=rho**horizon*amplitudes[t-horizon]
        delta=reward-sum(w[j]*v for j,v in e.items())
        if t<train:
            for j,v in e.items():w[j]+=lr*delta*v
        else:errors.append(delta**2)
        max_active=max(max_active,len(e));active_sum+=len(e)
    return w,np.asarray(errors),time.perf_counter()-start,max_active,active_sum/len(ids)


def immediate_bandit(ids,amplitudes,rewards,k,train,lr=.035):
    w=np.zeros(k);errors=[]
    start=time.perf_counter()
    for t,(idx,amp,reward) in enumerate(zip(ids,amplitudes,rewards)):
        delta=reward-w[idx]*amp
        if t<train:w[idx]+=lr*delta*amp
        else:errors.append(delta**2)
    return w,np.asarray(errors),time.perf_counter()-start


def neuromorphic_study(seeds=range(8),dimensions=(256,4096,16384),train=12000,test=3000):
    rows=[]
    for k in dimensions:
        for seed in seeds:
            ids,amps,r,theta,nt=delayed_data(seed,k,train,test)
            # Alternate order limits systematic timing order bias.
            if seed%2:
                ws,es,ts,ma,aa=sparse_trace(ids,amps,r,k,nt)
                wd,ed,td=dense_trace(ids,amps,r,k,nt)
            else:
                wd,ed,td=dense_trace(ids,amps,r,k,nt)
                ws,es,ts,ma,aa=sparse_trace(ids,amps,r,k,nt)
            wb,eb,tb=immediate_bandit(ids,amps,r,k,nt)
            rows.append({"seed":seed,"candidate_fragments":k,"dense_trace_mse":float(ed.mean()),
                         "sparse_trace_mse":float(es.mean()),"immediate_bandit_mse":float(eb.mean()),
                         "dense_host_seconds":td,"sparse_host_seconds":ts,"immediate_host_seconds":tb,
                         "dense_over_sparse_host_speed_ratio":td/ts,
                         "max_weight_difference":float(np.max(np.abs(wd-ws))),
                         "max_squared_error_difference":float(np.max(np.abs(ed-es))),
                         "max_active_traces":ma,"mean_active_traces":aa,
                         "approx_trace_touch_ratio_dense_over_sparse":k/aa,
                         "dense_trace_storage_float64_bytes":8*k,
                         "sparse_trace_payload_float64_bytes":8*ma,
                         "weight_storage_float64_bytes_both":8*k})
    summary=[]
    for k in dimensions:
        sel=[r for r in rows if r['candidate_fragments']==k]
        summary.append({"candidate_fragments":k,
                        **{key:ci([r[key] for r in sel]) for key in ['dense_trace_mse','sparse_trace_mse','immediate_bandit_mse','dense_over_sparse_host_speed_ratio','approx_trace_touch_ratio_dense_over_sparse']},
                        "max_weight_difference":max(r['max_weight_difference'] for r in sel),
                        "max_squared_error_difference":max(r['max_squared_error_difference'] for r in sel)})
    return {"seeds":list(seeds),"train_events":train,"test_events":test,"horizon":12,"rho":.9,
            "learning_rate":.035,"reward_noise_std":.1,"rows":rows,"summary":summary,
            "baseline_note":"Dense and sparse are mathematically identical finite-horizon eligibility regression. Immediate bandit deliberately lacks delayed features and is a diagnostic baseline, not a competitive delayed-credit algorithm. No e-prop or BrainTrace reproduction is claimed."}


def self_tests():
    rng=np.random.default_rng(123)
    q,_=np.linalg.qr(rng.normal(size=(13,13)))
    rotations,diagonal=decompose_orthogonal(q)
    qr=reconstruct_orthogonal(rotations,diagonal)
    assert np.max(np.abs(q-qr))<1e-12
    assert np.max(np.abs(qr.T@qr-np.eye(13)))<1e-12
    ids,amps,r,_,nt=delayed_data(100,31,train=300,test=100)
    wd,ed,_=dense_trace(ids,amps,r,31,nt)
    ws,es,_,ma,_=sparse_trace(ids,amps,r,31,nt)
    assert np.max(np.abs(wd-ws))<1e-12
    assert np.max(np.abs(ed-es))<1e-11
    assert ma<=12
    costs=hardware_costs()
    assert all(r['digital_time_ns']>0 and r['optical_time_ns']>0 and r['optical_energy_nJ']>0 for r in costs['rows'])
    return {"checks_passed":5,"max_mesh_reconstruction_error":float(np.max(np.abs(q-qr))),
            "max_trace_weight_error":float(np.max(np.abs(wd-ws)))}


def main():
    p=argparse.ArgumentParser();p.add_argument('--output',default='.');p.add_argument('--quick',action='store_true')
    args=p.parse_args();out=Path(args.output);out.mkdir(parents=True,exist_ok=True)
    start=time.perf_counter()
    tests=self_tests()
    results={"environment":{"python":platform.python_version(),"numpy":np.__version__,"platform":platform.platform()},
             "self_tests":tests,"photonic":photonic_surrogate(seeds=range(3) if args.quick else range(12)),
             "hardware_cost_model":hardware_costs(),
             "neuromorphic":neuromorphic_study(seeds=range(2) if args.quick else range(8),train=2000 if args.quick else 12000,test=500 if args.quick else 3000)}
    results['study_host_seconds']=time.perf_counter()-start
    (out/'hardware_results.json').write_text(json.dumps(results,indent=2))
    print(json.dumps({"self_tests":tests,"photonic_summary":results['photonic']['summary'],
                      "neuromorphic_summary":results['neuromorphic']['summary'],"study_host_seconds":results['study_host_seconds']},indent=2))


if __name__=='__main__':main()