"""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=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 t0 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()